]> Git Repo - qemu.git/blob - linux-user/syscall.c
linux-user: Fix socketcall() syscall support
[qemu.git] / linux-user / syscall.c
1 /*
2  *  Linux syscalls
3  *
4  *  Copyright (c) 2003 Fabrice Bellard
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19 #define _ATFILE_SOURCE
20 #include "qemu/osdep.h"
21 #include "qemu/cutils.h"
22 #include "qemu/path.h"
23 #include <elf.h>
24 #include <endian.h>
25 #include <grp.h>
26 #include <sys/ipc.h>
27 #include <sys/msg.h>
28 #include <sys/wait.h>
29 #include <sys/mount.h>
30 #include <sys/file.h>
31 #include <sys/fsuid.h>
32 #include <sys/personality.h>
33 #include <sys/prctl.h>
34 #include <sys/resource.h>
35 #include <sys/swap.h>
36 #include <linux/capability.h>
37 #include <sched.h>
38 #include <sys/timex.h>
39 #ifdef __ia64__
40 int __clone2(int (*fn)(void *), void *child_stack_base,
41              size_t stack_size, int flags, void *arg, ...);
42 #endif
43 #include <sys/socket.h>
44 #include <sys/un.h>
45 #include <sys/uio.h>
46 #include <poll.h>
47 #include <sys/times.h>
48 #include <sys/shm.h>
49 #include <sys/sem.h>
50 #include <sys/statfs.h>
51 #include <utime.h>
52 #include <sys/sysinfo.h>
53 #include <sys/signalfd.h>
54 //#include <sys/user.h>
55 #include <netinet/ip.h>
56 #include <netinet/tcp.h>
57 #include <linux/wireless.h>
58 #include <linux/icmp.h>
59 #include "qemu-common.h"
60 #ifdef CONFIG_TIMERFD
61 #include <sys/timerfd.h>
62 #endif
63 #ifdef TARGET_GPROF
64 #include <sys/gmon.h>
65 #endif
66 #ifdef CONFIG_EVENTFD
67 #include <sys/eventfd.h>
68 #endif
69 #ifdef CONFIG_EPOLL
70 #include <sys/epoll.h>
71 #endif
72 #ifdef CONFIG_ATTR
73 #include "qemu/xattr.h"
74 #endif
75 #ifdef CONFIG_SENDFILE
76 #include <sys/sendfile.h>
77 #endif
78
79 #define termios host_termios
80 #define winsize host_winsize
81 #define termio host_termio
82 #define sgttyb host_sgttyb /* same as target */
83 #define tchars host_tchars /* same as target */
84 #define ltchars host_ltchars /* same as target */
85
86 #include <linux/termios.h>
87 #include <linux/unistd.h>
88 #include <linux/cdrom.h>
89 #include <linux/hdreg.h>
90 #include <linux/soundcard.h>
91 #include <linux/kd.h>
92 #include <linux/mtio.h>
93 #include <linux/fs.h>
94 #if defined(CONFIG_FIEMAP)
95 #include <linux/fiemap.h>
96 #endif
97 #include <linux/fb.h>
98 #include <linux/vt.h>
99 #include <linux/dm-ioctl.h>
100 #include <linux/reboot.h>
101 #include <linux/route.h>
102 #include <linux/filter.h>
103 #include <linux/blkpg.h>
104 #include <netpacket/packet.h>
105 #include <linux/netlink.h>
106 #ifdef CONFIG_RTNETLINK
107 #include <linux/rtnetlink.h>
108 #include <linux/if_bridge.h>
109 #endif
110 #include <linux/audit.h>
111 #include "linux_loop.h"
112 #include "uname.h"
113
114 #include "qemu.h"
115
116 #ifndef CLONE_IO
117 #define CLONE_IO                0x80000000      /* Clone io context */
118 #endif
119
120 /* We can't directly call the host clone syscall, because this will
121  * badly confuse libc (breaking mutexes, for example). So we must
122  * divide clone flags into:
123  *  * flag combinations that look like pthread_create()
124  *  * flag combinations that look like fork()
125  *  * flags we can implement within QEMU itself
126  *  * flags we can't support and will return an error for
127  */
128 /* For thread creation, all these flags must be present; for
129  * fork, none must be present.
130  */
131 #define CLONE_THREAD_FLAGS                              \
132     (CLONE_VM | CLONE_FS | CLONE_FILES |                \
133      CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM)
134
135 /* These flags are ignored:
136  * CLONE_DETACHED is now ignored by the kernel;
137  * CLONE_IO is just an optimisation hint to the I/O scheduler
138  */
139 #define CLONE_IGNORED_FLAGS                     \
140     (CLONE_DETACHED | CLONE_IO)
141
142 /* Flags for fork which we can implement within QEMU itself */
143 #define CLONE_OPTIONAL_FORK_FLAGS               \
144     (CLONE_SETTLS | CLONE_PARENT_SETTID |       \
145      CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID)
146
147 /* Flags for thread creation which we can implement within QEMU itself */
148 #define CLONE_OPTIONAL_THREAD_FLAGS                             \
149     (CLONE_SETTLS | CLONE_PARENT_SETTID |                       \
150      CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID | CLONE_PARENT)
151
152 #define CLONE_INVALID_FORK_FLAGS                                        \
153     (~(CSIGNAL | CLONE_OPTIONAL_FORK_FLAGS | CLONE_IGNORED_FLAGS))
154
155 #define CLONE_INVALID_THREAD_FLAGS                                      \
156     (~(CSIGNAL | CLONE_THREAD_FLAGS | CLONE_OPTIONAL_THREAD_FLAGS |     \
157        CLONE_IGNORED_FLAGS))
158
159 /* CLONE_VFORK is special cased early in do_fork(). The other flag bits
160  * have almost all been allocated. We cannot support any of
161  * CLONE_NEWNS, CLONE_NEWCGROUP, CLONE_NEWUTS, CLONE_NEWIPC,
162  * CLONE_NEWUSER, CLONE_NEWPID, CLONE_NEWNET, CLONE_PTRACE, CLONE_UNTRACED.
163  * The checks against the invalid thread masks above will catch these.
164  * (The one remaining unallocated bit is 0x1000 which used to be CLONE_PID.)
165  */
166
167 //#define DEBUG
168 /* Define DEBUG_ERESTARTSYS to force every syscall to be restarted
169  * once. This exercises the codepaths for restart.
170  */
171 //#define DEBUG_ERESTARTSYS
172
173 //#include <linux/msdos_fs.h>
174 #define VFAT_IOCTL_READDIR_BOTH         _IOR('r', 1, struct linux_dirent [2])
175 #define VFAT_IOCTL_READDIR_SHORT        _IOR('r', 2, struct linux_dirent [2])
176
177 #undef _syscall0
178 #undef _syscall1
179 #undef _syscall2
180 #undef _syscall3
181 #undef _syscall4
182 #undef _syscall5
183 #undef _syscall6
184
185 #define _syscall0(type,name)            \
186 static type name (void)                 \
187 {                                       \
188         return syscall(__NR_##name);    \
189 }
190
191 #define _syscall1(type,name,type1,arg1)         \
192 static type name (type1 arg1)                   \
193 {                                               \
194         return syscall(__NR_##name, arg1);      \
195 }
196
197 #define _syscall2(type,name,type1,arg1,type2,arg2)      \
198 static type name (type1 arg1,type2 arg2)                \
199 {                                                       \
200         return syscall(__NR_##name, arg1, arg2);        \
201 }
202
203 #define _syscall3(type,name,type1,arg1,type2,arg2,type3,arg3)   \
204 static type name (type1 arg1,type2 arg2,type3 arg3)             \
205 {                                                               \
206         return syscall(__NR_##name, arg1, arg2, arg3);          \
207 }
208
209 #define _syscall4(type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4)        \
210 static type name (type1 arg1,type2 arg2,type3 arg3,type4 arg4)                  \
211 {                                                                               \
212         return syscall(__NR_##name, arg1, arg2, arg3, arg4);                    \
213 }
214
215 #define _syscall5(type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4,        \
216                   type5,arg5)                                                   \
217 static type name (type1 arg1,type2 arg2,type3 arg3,type4 arg4,type5 arg5)       \
218 {                                                                               \
219         return syscall(__NR_##name, arg1, arg2, arg3, arg4, arg5);              \
220 }
221
222
223 #define _syscall6(type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4,        \
224                   type5,arg5,type6,arg6)                                        \
225 static type name (type1 arg1,type2 arg2,type3 arg3,type4 arg4,type5 arg5,       \
226                   type6 arg6)                                                   \
227 {                                                                               \
228         return syscall(__NR_##name, arg1, arg2, arg3, arg4, arg5, arg6);        \
229 }
230
231
232 #define __NR_sys_uname __NR_uname
233 #define __NR_sys_getcwd1 __NR_getcwd
234 #define __NR_sys_getdents __NR_getdents
235 #define __NR_sys_getdents64 __NR_getdents64
236 #define __NR_sys_getpriority __NR_getpriority
237 #define __NR_sys_rt_sigqueueinfo __NR_rt_sigqueueinfo
238 #define __NR_sys_syslog __NR_syslog
239 #define __NR_sys_futex __NR_futex
240 #define __NR_sys_inotify_init __NR_inotify_init
241 #define __NR_sys_inotify_add_watch __NR_inotify_add_watch
242 #define __NR_sys_inotify_rm_watch __NR_inotify_rm_watch
243
244 #if defined(__alpha__) || defined (__ia64__) || defined(__x86_64__) || \
245     defined(__s390x__)
246 #define __NR__llseek __NR_lseek
247 #endif
248
249 /* Newer kernel ports have llseek() instead of _llseek() */
250 #if defined(TARGET_NR_llseek) && !defined(TARGET_NR__llseek)
251 #define TARGET_NR__llseek TARGET_NR_llseek
252 #endif
253
254 #ifdef __NR_gettid
255 _syscall0(int, gettid)
256 #else
257 /* This is a replacement for the host gettid() and must return a host
258    errno. */
259 static int gettid(void) {
260     return -ENOSYS;
261 }
262 #endif
263 #if defined(TARGET_NR_getdents) && defined(__NR_getdents)
264 _syscall3(int, sys_getdents, uint, fd, struct linux_dirent *, dirp, uint, count);
265 #endif
266 #if !defined(__NR_getdents) || \
267     (defined(TARGET_NR_getdents64) && defined(__NR_getdents64))
268 _syscall3(int, sys_getdents64, uint, fd, struct linux_dirent64 *, dirp, uint, count);
269 #endif
270 #if defined(TARGET_NR__llseek) && defined(__NR_llseek)
271 _syscall5(int, _llseek,  uint,  fd, ulong, hi, ulong, lo,
272           loff_t *, res, uint, wh);
273 #endif
274 _syscall3(int,sys_rt_sigqueueinfo,int,pid,int,sig,siginfo_t *,uinfo)
275 _syscall3(int,sys_syslog,int,type,char*,bufp,int,len)
276 #ifdef __NR_exit_group
277 _syscall1(int,exit_group,int,error_code)
278 #endif
279 #if defined(TARGET_NR_set_tid_address) && defined(__NR_set_tid_address)
280 _syscall1(int,set_tid_address,int *,tidptr)
281 #endif
282 #if defined(TARGET_NR_futex) && defined(__NR_futex)
283 _syscall6(int,sys_futex,int *,uaddr,int,op,int,val,
284           const struct timespec *,timeout,int *,uaddr2,int,val3)
285 #endif
286 #define __NR_sys_sched_getaffinity __NR_sched_getaffinity
287 _syscall3(int, sys_sched_getaffinity, pid_t, pid, unsigned int, len,
288           unsigned long *, user_mask_ptr);
289 #define __NR_sys_sched_setaffinity __NR_sched_setaffinity
290 _syscall3(int, sys_sched_setaffinity, pid_t, pid, unsigned int, len,
291           unsigned long *, user_mask_ptr);
292 _syscall4(int, reboot, int, magic1, int, magic2, unsigned int, cmd,
293           void *, arg);
294 _syscall2(int, capget, struct __user_cap_header_struct *, header,
295           struct __user_cap_data_struct *, data);
296 _syscall2(int, capset, struct __user_cap_header_struct *, header,
297           struct __user_cap_data_struct *, data);
298 #if defined(TARGET_NR_ioprio_get) && defined(__NR_ioprio_get)
299 _syscall2(int, ioprio_get, int, which, int, who)
300 #endif
301 #if defined(TARGET_NR_ioprio_set) && defined(__NR_ioprio_set)
302 _syscall3(int, ioprio_set, int, which, int, who, int, ioprio)
303 #endif
304 #if defined(TARGET_NR_getrandom) && defined(__NR_getrandom)
305 _syscall3(int, getrandom, void *, buf, size_t, buflen, unsigned int, flags)
306 #endif
307
308 static bitmask_transtbl fcntl_flags_tbl[] = {
309   { TARGET_O_ACCMODE,   TARGET_O_WRONLY,    O_ACCMODE,   O_WRONLY,    },
310   { TARGET_O_ACCMODE,   TARGET_O_RDWR,      O_ACCMODE,   O_RDWR,      },
311   { TARGET_O_CREAT,     TARGET_O_CREAT,     O_CREAT,     O_CREAT,     },
312   { TARGET_O_EXCL,      TARGET_O_EXCL,      O_EXCL,      O_EXCL,      },
313   { TARGET_O_NOCTTY,    TARGET_O_NOCTTY,    O_NOCTTY,    O_NOCTTY,    },
314   { TARGET_O_TRUNC,     TARGET_O_TRUNC,     O_TRUNC,     O_TRUNC,     },
315   { TARGET_O_APPEND,    TARGET_O_APPEND,    O_APPEND,    O_APPEND,    },
316   { TARGET_O_NONBLOCK,  TARGET_O_NONBLOCK,  O_NONBLOCK,  O_NONBLOCK,  },
317   { TARGET_O_SYNC,      TARGET_O_DSYNC,     O_SYNC,      O_DSYNC,     },
318   { TARGET_O_SYNC,      TARGET_O_SYNC,      O_SYNC,      O_SYNC,      },
319   { TARGET_FASYNC,      TARGET_FASYNC,      FASYNC,      FASYNC,      },
320   { TARGET_O_DIRECTORY, TARGET_O_DIRECTORY, O_DIRECTORY, O_DIRECTORY, },
321   { TARGET_O_NOFOLLOW,  TARGET_O_NOFOLLOW,  O_NOFOLLOW,  O_NOFOLLOW,  },
322 #if defined(O_DIRECT)
323   { TARGET_O_DIRECT,    TARGET_O_DIRECT,    O_DIRECT,    O_DIRECT,    },
324 #endif
325 #if defined(O_NOATIME)
326   { TARGET_O_NOATIME,   TARGET_O_NOATIME,   O_NOATIME,   O_NOATIME    },
327 #endif
328 #if defined(O_CLOEXEC)
329   { TARGET_O_CLOEXEC,   TARGET_O_CLOEXEC,   O_CLOEXEC,   O_CLOEXEC    },
330 #endif
331 #if defined(O_PATH)
332   { TARGET_O_PATH,      TARGET_O_PATH,      O_PATH,      O_PATH       },
333 #endif
334   /* Don't terminate the list prematurely on 64-bit host+guest.  */
335 #if TARGET_O_LARGEFILE != 0 || O_LARGEFILE != 0
336   { TARGET_O_LARGEFILE, TARGET_O_LARGEFILE, O_LARGEFILE, O_LARGEFILE, },
337 #endif
338   { 0, 0, 0, 0 }
339 };
340
341 enum {
342     QEMU_IFLA_BR_UNSPEC,
343     QEMU_IFLA_BR_FORWARD_DELAY,
344     QEMU_IFLA_BR_HELLO_TIME,
345     QEMU_IFLA_BR_MAX_AGE,
346     QEMU_IFLA_BR_AGEING_TIME,
347     QEMU_IFLA_BR_STP_STATE,
348     QEMU_IFLA_BR_PRIORITY,
349     QEMU_IFLA_BR_VLAN_FILTERING,
350     QEMU_IFLA_BR_VLAN_PROTOCOL,
351     QEMU_IFLA_BR_GROUP_FWD_MASK,
352     QEMU_IFLA_BR_ROOT_ID,
353     QEMU_IFLA_BR_BRIDGE_ID,
354     QEMU_IFLA_BR_ROOT_PORT,
355     QEMU_IFLA_BR_ROOT_PATH_COST,
356     QEMU_IFLA_BR_TOPOLOGY_CHANGE,
357     QEMU_IFLA_BR_TOPOLOGY_CHANGE_DETECTED,
358     QEMU_IFLA_BR_HELLO_TIMER,
359     QEMU_IFLA_BR_TCN_TIMER,
360     QEMU_IFLA_BR_TOPOLOGY_CHANGE_TIMER,
361     QEMU_IFLA_BR_GC_TIMER,
362     QEMU_IFLA_BR_GROUP_ADDR,
363     QEMU_IFLA_BR_FDB_FLUSH,
364     QEMU_IFLA_BR_MCAST_ROUTER,
365     QEMU_IFLA_BR_MCAST_SNOOPING,
366     QEMU_IFLA_BR_MCAST_QUERY_USE_IFADDR,
367     QEMU_IFLA_BR_MCAST_QUERIER,
368     QEMU_IFLA_BR_MCAST_HASH_ELASTICITY,
369     QEMU_IFLA_BR_MCAST_HASH_MAX,
370     QEMU_IFLA_BR_MCAST_LAST_MEMBER_CNT,
371     QEMU_IFLA_BR_MCAST_STARTUP_QUERY_CNT,
372     QEMU_IFLA_BR_MCAST_LAST_MEMBER_INTVL,
373     QEMU_IFLA_BR_MCAST_MEMBERSHIP_INTVL,
374     QEMU_IFLA_BR_MCAST_QUERIER_INTVL,
375     QEMU_IFLA_BR_MCAST_QUERY_INTVL,
376     QEMU_IFLA_BR_MCAST_QUERY_RESPONSE_INTVL,
377     QEMU_IFLA_BR_MCAST_STARTUP_QUERY_INTVL,
378     QEMU_IFLA_BR_NF_CALL_IPTABLES,
379     QEMU_IFLA_BR_NF_CALL_IP6TABLES,
380     QEMU_IFLA_BR_NF_CALL_ARPTABLES,
381     QEMU_IFLA_BR_VLAN_DEFAULT_PVID,
382     QEMU_IFLA_BR_PAD,
383     QEMU_IFLA_BR_VLAN_STATS_ENABLED,
384     QEMU_IFLA_BR_MCAST_STATS_ENABLED,
385     QEMU___IFLA_BR_MAX,
386 };
387
388 enum {
389     QEMU_IFLA_UNSPEC,
390     QEMU_IFLA_ADDRESS,
391     QEMU_IFLA_BROADCAST,
392     QEMU_IFLA_IFNAME,
393     QEMU_IFLA_MTU,
394     QEMU_IFLA_LINK,
395     QEMU_IFLA_QDISC,
396     QEMU_IFLA_STATS,
397     QEMU_IFLA_COST,
398     QEMU_IFLA_PRIORITY,
399     QEMU_IFLA_MASTER,
400     QEMU_IFLA_WIRELESS,
401     QEMU_IFLA_PROTINFO,
402     QEMU_IFLA_TXQLEN,
403     QEMU_IFLA_MAP,
404     QEMU_IFLA_WEIGHT,
405     QEMU_IFLA_OPERSTATE,
406     QEMU_IFLA_LINKMODE,
407     QEMU_IFLA_LINKINFO,
408     QEMU_IFLA_NET_NS_PID,
409     QEMU_IFLA_IFALIAS,
410     QEMU_IFLA_NUM_VF,
411     QEMU_IFLA_VFINFO_LIST,
412     QEMU_IFLA_STATS64,
413     QEMU_IFLA_VF_PORTS,
414     QEMU_IFLA_PORT_SELF,
415     QEMU_IFLA_AF_SPEC,
416     QEMU_IFLA_GROUP,
417     QEMU_IFLA_NET_NS_FD,
418     QEMU_IFLA_EXT_MASK,
419     QEMU_IFLA_PROMISCUITY,
420     QEMU_IFLA_NUM_TX_QUEUES,
421     QEMU_IFLA_NUM_RX_QUEUES,
422     QEMU_IFLA_CARRIER,
423     QEMU_IFLA_PHYS_PORT_ID,
424     QEMU_IFLA_CARRIER_CHANGES,
425     QEMU_IFLA_PHYS_SWITCH_ID,
426     QEMU_IFLA_LINK_NETNSID,
427     QEMU_IFLA_PHYS_PORT_NAME,
428     QEMU_IFLA_PROTO_DOWN,
429     QEMU_IFLA_GSO_MAX_SEGS,
430     QEMU_IFLA_GSO_MAX_SIZE,
431     QEMU_IFLA_PAD,
432     QEMU_IFLA_XDP,
433     QEMU___IFLA_MAX
434 };
435
436 enum {
437     QEMU_IFLA_BRPORT_UNSPEC,
438     QEMU_IFLA_BRPORT_STATE,
439     QEMU_IFLA_BRPORT_PRIORITY,
440     QEMU_IFLA_BRPORT_COST,
441     QEMU_IFLA_BRPORT_MODE,
442     QEMU_IFLA_BRPORT_GUARD,
443     QEMU_IFLA_BRPORT_PROTECT,
444     QEMU_IFLA_BRPORT_FAST_LEAVE,
445     QEMU_IFLA_BRPORT_LEARNING,
446     QEMU_IFLA_BRPORT_UNICAST_FLOOD,
447     QEMU_IFLA_BRPORT_PROXYARP,
448     QEMU_IFLA_BRPORT_LEARNING_SYNC,
449     QEMU_IFLA_BRPORT_PROXYARP_WIFI,
450     QEMU_IFLA_BRPORT_ROOT_ID,
451     QEMU_IFLA_BRPORT_BRIDGE_ID,
452     QEMU_IFLA_BRPORT_DESIGNATED_PORT,
453     QEMU_IFLA_BRPORT_DESIGNATED_COST,
454     QEMU_IFLA_BRPORT_ID,
455     QEMU_IFLA_BRPORT_NO,
456     QEMU_IFLA_BRPORT_TOPOLOGY_CHANGE_ACK,
457     QEMU_IFLA_BRPORT_CONFIG_PENDING,
458     QEMU_IFLA_BRPORT_MESSAGE_AGE_TIMER,
459     QEMU_IFLA_BRPORT_FORWARD_DELAY_TIMER,
460     QEMU_IFLA_BRPORT_HOLD_TIMER,
461     QEMU_IFLA_BRPORT_FLUSH,
462     QEMU_IFLA_BRPORT_MULTICAST_ROUTER,
463     QEMU_IFLA_BRPORT_PAD,
464     QEMU___IFLA_BRPORT_MAX
465 };
466
467 enum {
468     QEMU_IFLA_INFO_UNSPEC,
469     QEMU_IFLA_INFO_KIND,
470     QEMU_IFLA_INFO_DATA,
471     QEMU_IFLA_INFO_XSTATS,
472     QEMU_IFLA_INFO_SLAVE_KIND,
473     QEMU_IFLA_INFO_SLAVE_DATA,
474     QEMU___IFLA_INFO_MAX,
475 };
476
477 enum {
478     QEMU_IFLA_INET_UNSPEC,
479     QEMU_IFLA_INET_CONF,
480     QEMU___IFLA_INET_MAX,
481 };
482
483 enum {
484     QEMU_IFLA_INET6_UNSPEC,
485     QEMU_IFLA_INET6_FLAGS,
486     QEMU_IFLA_INET6_CONF,
487     QEMU_IFLA_INET6_STATS,
488     QEMU_IFLA_INET6_MCAST,
489     QEMU_IFLA_INET6_CACHEINFO,
490     QEMU_IFLA_INET6_ICMP6STATS,
491     QEMU_IFLA_INET6_TOKEN,
492     QEMU_IFLA_INET6_ADDR_GEN_MODE,
493     QEMU___IFLA_INET6_MAX
494 };
495
496 typedef abi_long (*TargetFdDataFunc)(void *, size_t);
497 typedef abi_long (*TargetFdAddrFunc)(void *, abi_ulong, socklen_t);
498 typedef struct TargetFdTrans {
499     TargetFdDataFunc host_to_target_data;
500     TargetFdDataFunc target_to_host_data;
501     TargetFdAddrFunc target_to_host_addr;
502 } TargetFdTrans;
503
504 static TargetFdTrans **target_fd_trans;
505
506 static unsigned int target_fd_max;
507
508 static TargetFdDataFunc fd_trans_target_to_host_data(int fd)
509 {
510     if (fd >= 0 && fd < target_fd_max && target_fd_trans[fd]) {
511         return target_fd_trans[fd]->target_to_host_data;
512     }
513     return NULL;
514 }
515
516 static TargetFdDataFunc fd_trans_host_to_target_data(int fd)
517 {
518     if (fd >= 0 && fd < target_fd_max && target_fd_trans[fd]) {
519         return target_fd_trans[fd]->host_to_target_data;
520     }
521     return NULL;
522 }
523
524 static TargetFdAddrFunc fd_trans_target_to_host_addr(int fd)
525 {
526     if (fd >= 0 && fd < target_fd_max && target_fd_trans[fd]) {
527         return target_fd_trans[fd]->target_to_host_addr;
528     }
529     return NULL;
530 }
531
532 static void fd_trans_register(int fd, TargetFdTrans *trans)
533 {
534     unsigned int oldmax;
535
536     if (fd >= target_fd_max) {
537         oldmax = target_fd_max;
538         target_fd_max = ((fd >> 6) + 1) << 6; /* by slice of 64 entries */
539         target_fd_trans = g_renew(TargetFdTrans *,
540                                   target_fd_trans, target_fd_max);
541         memset((void *)(target_fd_trans + oldmax), 0,
542                (target_fd_max - oldmax) * sizeof(TargetFdTrans *));
543     }
544     target_fd_trans[fd] = trans;
545 }
546
547 static void fd_trans_unregister(int fd)
548 {
549     if (fd >= 0 && fd < target_fd_max) {
550         target_fd_trans[fd] = NULL;
551     }
552 }
553
554 static void fd_trans_dup(int oldfd, int newfd)
555 {
556     fd_trans_unregister(newfd);
557     if (oldfd < target_fd_max && target_fd_trans[oldfd]) {
558         fd_trans_register(newfd, target_fd_trans[oldfd]);
559     }
560 }
561
562 static int sys_getcwd1(char *buf, size_t size)
563 {
564   if (getcwd(buf, size) == NULL) {
565       /* getcwd() sets errno */
566       return (-1);
567   }
568   return strlen(buf)+1;
569 }
570
571 #ifdef TARGET_NR_utimensat
572 #if defined(__NR_utimensat)
573 #define __NR_sys_utimensat __NR_utimensat
574 _syscall4(int,sys_utimensat,int,dirfd,const char *,pathname,
575           const struct timespec *,tsp,int,flags)
576 #else
577 static int sys_utimensat(int dirfd, const char *pathname,
578                          const struct timespec times[2], int flags)
579 {
580     errno = ENOSYS;
581     return -1;
582 }
583 #endif
584 #endif /* TARGET_NR_utimensat */
585
586 #ifdef CONFIG_INOTIFY
587 #include <sys/inotify.h>
588
589 #if defined(TARGET_NR_inotify_init) && defined(__NR_inotify_init)
590 static int sys_inotify_init(void)
591 {
592   return (inotify_init());
593 }
594 #endif
595 #if defined(TARGET_NR_inotify_add_watch) && defined(__NR_inotify_add_watch)
596 static int sys_inotify_add_watch(int fd,const char *pathname, int32_t mask)
597 {
598   return (inotify_add_watch(fd, pathname, mask));
599 }
600 #endif
601 #if defined(TARGET_NR_inotify_rm_watch) && defined(__NR_inotify_rm_watch)
602 static int sys_inotify_rm_watch(int fd, int32_t wd)
603 {
604   return (inotify_rm_watch(fd, wd));
605 }
606 #endif
607 #ifdef CONFIG_INOTIFY1
608 #if defined(TARGET_NR_inotify_init1) && defined(__NR_inotify_init1)
609 static int sys_inotify_init1(int flags)
610 {
611   return (inotify_init1(flags));
612 }
613 #endif
614 #endif
615 #else
616 /* Userspace can usually survive runtime without inotify */
617 #undef TARGET_NR_inotify_init
618 #undef TARGET_NR_inotify_init1
619 #undef TARGET_NR_inotify_add_watch
620 #undef TARGET_NR_inotify_rm_watch
621 #endif /* CONFIG_INOTIFY  */
622
623 #if defined(TARGET_NR_prlimit64)
624 #ifndef __NR_prlimit64
625 # define __NR_prlimit64 -1
626 #endif
627 #define __NR_sys_prlimit64 __NR_prlimit64
628 /* The glibc rlimit structure may not be that used by the underlying syscall */
629 struct host_rlimit64 {
630     uint64_t rlim_cur;
631     uint64_t rlim_max;
632 };
633 _syscall4(int, sys_prlimit64, pid_t, pid, int, resource,
634           const struct host_rlimit64 *, new_limit,
635           struct host_rlimit64 *, old_limit)
636 #endif
637
638
639 #if defined(TARGET_NR_timer_create)
640 /* Maxiumum of 32 active POSIX timers allowed at any one time. */
641 static timer_t g_posix_timers[32] = { 0, } ;
642
643 static inline int next_free_host_timer(void)
644 {
645     int k ;
646     /* FIXME: Does finding the next free slot require a lock? */
647     for (k = 0; k < ARRAY_SIZE(g_posix_timers); k++) {
648         if (g_posix_timers[k] == 0) {
649             g_posix_timers[k] = (timer_t) 1;
650             return k;
651         }
652     }
653     return -1;
654 }
655 #endif
656
657 /* ARM EABI and MIPS expect 64bit types aligned even on pairs or registers */
658 #ifdef TARGET_ARM
659 static inline int regpairs_aligned(void *cpu_env) {
660     return ((((CPUARMState *)cpu_env)->eabi) == 1) ;
661 }
662 #elif defined(TARGET_MIPS) && (TARGET_ABI_BITS == 32)
663 static inline int regpairs_aligned(void *cpu_env) { return 1; }
664 #elif defined(TARGET_PPC) && !defined(TARGET_PPC64)
665 /* SysV AVI for PPC32 expects 64bit parameters to be passed on odd/even pairs
666  * of registers which translates to the same as ARM/MIPS, because we start with
667  * r3 as arg1 */
668 static inline int regpairs_aligned(void *cpu_env) { return 1; }
669 #else
670 static inline int regpairs_aligned(void *cpu_env) { return 0; }
671 #endif
672
673 #define ERRNO_TABLE_SIZE 1200
674
675 /* target_to_host_errno_table[] is initialized from
676  * host_to_target_errno_table[] in syscall_init(). */
677 static uint16_t target_to_host_errno_table[ERRNO_TABLE_SIZE] = {
678 };
679
680 /*
681  * This list is the union of errno values overridden in asm-<arch>/errno.h
682  * minus the errnos that are not actually generic to all archs.
683  */
684 static uint16_t host_to_target_errno_table[ERRNO_TABLE_SIZE] = {
685     [EAGAIN]            = TARGET_EAGAIN,
686     [EIDRM]             = TARGET_EIDRM,
687     [ECHRNG]            = TARGET_ECHRNG,
688     [EL2NSYNC]          = TARGET_EL2NSYNC,
689     [EL3HLT]            = TARGET_EL3HLT,
690     [EL3RST]            = TARGET_EL3RST,
691     [ELNRNG]            = TARGET_ELNRNG,
692     [EUNATCH]           = TARGET_EUNATCH,
693     [ENOCSI]            = TARGET_ENOCSI,
694     [EL2HLT]            = TARGET_EL2HLT,
695     [EDEADLK]           = TARGET_EDEADLK,
696     [ENOLCK]            = TARGET_ENOLCK,
697     [EBADE]             = TARGET_EBADE,
698     [EBADR]             = TARGET_EBADR,
699     [EXFULL]            = TARGET_EXFULL,
700     [ENOANO]            = TARGET_ENOANO,
701     [EBADRQC]           = TARGET_EBADRQC,
702     [EBADSLT]           = TARGET_EBADSLT,
703     [EBFONT]            = TARGET_EBFONT,
704     [ENOSTR]            = TARGET_ENOSTR,
705     [ENODATA]           = TARGET_ENODATA,
706     [ETIME]             = TARGET_ETIME,
707     [ENOSR]             = TARGET_ENOSR,
708     [ENONET]            = TARGET_ENONET,
709     [ENOPKG]            = TARGET_ENOPKG,
710     [EREMOTE]           = TARGET_EREMOTE,
711     [ENOLINK]           = TARGET_ENOLINK,
712     [EADV]              = TARGET_EADV,
713     [ESRMNT]            = TARGET_ESRMNT,
714     [ECOMM]             = TARGET_ECOMM,
715     [EPROTO]            = TARGET_EPROTO,
716     [EDOTDOT]           = TARGET_EDOTDOT,
717     [EMULTIHOP]         = TARGET_EMULTIHOP,
718     [EBADMSG]           = TARGET_EBADMSG,
719     [ENAMETOOLONG]      = TARGET_ENAMETOOLONG,
720     [EOVERFLOW]         = TARGET_EOVERFLOW,
721     [ENOTUNIQ]          = TARGET_ENOTUNIQ,
722     [EBADFD]            = TARGET_EBADFD,
723     [EREMCHG]           = TARGET_EREMCHG,
724     [ELIBACC]           = TARGET_ELIBACC,
725     [ELIBBAD]           = TARGET_ELIBBAD,
726     [ELIBSCN]           = TARGET_ELIBSCN,
727     [ELIBMAX]           = TARGET_ELIBMAX,
728     [ELIBEXEC]          = TARGET_ELIBEXEC,
729     [EILSEQ]            = TARGET_EILSEQ,
730     [ENOSYS]            = TARGET_ENOSYS,
731     [ELOOP]             = TARGET_ELOOP,
732     [ERESTART]          = TARGET_ERESTART,
733     [ESTRPIPE]          = TARGET_ESTRPIPE,
734     [ENOTEMPTY]         = TARGET_ENOTEMPTY,
735     [EUSERS]            = TARGET_EUSERS,
736     [ENOTSOCK]          = TARGET_ENOTSOCK,
737     [EDESTADDRREQ]      = TARGET_EDESTADDRREQ,
738     [EMSGSIZE]          = TARGET_EMSGSIZE,
739     [EPROTOTYPE]        = TARGET_EPROTOTYPE,
740     [ENOPROTOOPT]       = TARGET_ENOPROTOOPT,
741     [EPROTONOSUPPORT]   = TARGET_EPROTONOSUPPORT,
742     [ESOCKTNOSUPPORT]   = TARGET_ESOCKTNOSUPPORT,
743     [EOPNOTSUPP]        = TARGET_EOPNOTSUPP,
744     [EPFNOSUPPORT]      = TARGET_EPFNOSUPPORT,
745     [EAFNOSUPPORT]      = TARGET_EAFNOSUPPORT,
746     [EADDRINUSE]        = TARGET_EADDRINUSE,
747     [EADDRNOTAVAIL]     = TARGET_EADDRNOTAVAIL,
748     [ENETDOWN]          = TARGET_ENETDOWN,
749     [ENETUNREACH]       = TARGET_ENETUNREACH,
750     [ENETRESET]         = TARGET_ENETRESET,
751     [ECONNABORTED]      = TARGET_ECONNABORTED,
752     [ECONNRESET]        = TARGET_ECONNRESET,
753     [ENOBUFS]           = TARGET_ENOBUFS,
754     [EISCONN]           = TARGET_EISCONN,
755     [ENOTCONN]          = TARGET_ENOTCONN,
756     [EUCLEAN]           = TARGET_EUCLEAN,
757     [ENOTNAM]           = TARGET_ENOTNAM,
758     [ENAVAIL]           = TARGET_ENAVAIL,
759     [EISNAM]            = TARGET_EISNAM,
760     [EREMOTEIO]         = TARGET_EREMOTEIO,
761     [EDQUOT]            = TARGET_EDQUOT,
762     [ESHUTDOWN]         = TARGET_ESHUTDOWN,
763     [ETOOMANYREFS]      = TARGET_ETOOMANYREFS,
764     [ETIMEDOUT]         = TARGET_ETIMEDOUT,
765     [ECONNREFUSED]      = TARGET_ECONNREFUSED,
766     [EHOSTDOWN]         = TARGET_EHOSTDOWN,
767     [EHOSTUNREACH]      = TARGET_EHOSTUNREACH,
768     [EALREADY]          = TARGET_EALREADY,
769     [EINPROGRESS]       = TARGET_EINPROGRESS,
770     [ESTALE]            = TARGET_ESTALE,
771     [ECANCELED]         = TARGET_ECANCELED,
772     [ENOMEDIUM]         = TARGET_ENOMEDIUM,
773     [EMEDIUMTYPE]       = TARGET_EMEDIUMTYPE,
774 #ifdef ENOKEY
775     [ENOKEY]            = TARGET_ENOKEY,
776 #endif
777 #ifdef EKEYEXPIRED
778     [EKEYEXPIRED]       = TARGET_EKEYEXPIRED,
779 #endif
780 #ifdef EKEYREVOKED
781     [EKEYREVOKED]       = TARGET_EKEYREVOKED,
782 #endif
783 #ifdef EKEYREJECTED
784     [EKEYREJECTED]      = TARGET_EKEYREJECTED,
785 #endif
786 #ifdef EOWNERDEAD
787     [EOWNERDEAD]        = TARGET_EOWNERDEAD,
788 #endif
789 #ifdef ENOTRECOVERABLE
790     [ENOTRECOVERABLE]   = TARGET_ENOTRECOVERABLE,
791 #endif
792 #ifdef ENOMSG
793     [ENOMSG]            = TARGET_ENOMSG,
794 #endif
795 };
796
797 static inline int host_to_target_errno(int err)
798 {
799     if (err >= 0 && err < ERRNO_TABLE_SIZE &&
800         host_to_target_errno_table[err]) {
801         return host_to_target_errno_table[err];
802     }
803     return err;
804 }
805
806 static inline int target_to_host_errno(int err)
807 {
808     if (err >= 0 && err < ERRNO_TABLE_SIZE &&
809         target_to_host_errno_table[err]) {
810         return target_to_host_errno_table[err];
811     }
812     return err;
813 }
814
815 static inline abi_long get_errno(abi_long ret)
816 {
817     if (ret == -1)
818         return -host_to_target_errno(errno);
819     else
820         return ret;
821 }
822
823 static inline int is_error(abi_long ret)
824 {
825     return (abi_ulong)ret >= (abi_ulong)(-4096);
826 }
827
828 const char *target_strerror(int err)
829 {
830     if (err == TARGET_ERESTARTSYS) {
831         return "To be restarted";
832     }
833     if (err == TARGET_QEMU_ESIGRETURN) {
834         return "Successful exit from sigreturn";
835     }
836
837     if ((err >= ERRNO_TABLE_SIZE) || (err < 0)) {
838         return NULL;
839     }
840     return strerror(target_to_host_errno(err));
841 }
842
843 #define safe_syscall0(type, name) \
844 static type safe_##name(void) \
845 { \
846     return safe_syscall(__NR_##name); \
847 }
848
849 #define safe_syscall1(type, name, type1, arg1) \
850 static type safe_##name(type1 arg1) \
851 { \
852     return safe_syscall(__NR_##name, arg1); \
853 }
854
855 #define safe_syscall2(type, name, type1, arg1, type2, arg2) \
856 static type safe_##name(type1 arg1, type2 arg2) \
857 { \
858     return safe_syscall(__NR_##name, arg1, arg2); \
859 }
860
861 #define safe_syscall3(type, name, type1, arg1, type2, arg2, type3, arg3) \
862 static type safe_##name(type1 arg1, type2 arg2, type3 arg3) \
863 { \
864     return safe_syscall(__NR_##name, arg1, arg2, arg3); \
865 }
866
867 #define safe_syscall4(type, name, type1, arg1, type2, arg2, type3, arg3, \
868     type4, arg4) \
869 static type safe_##name(type1 arg1, type2 arg2, type3 arg3, type4 arg4) \
870 { \
871     return safe_syscall(__NR_##name, arg1, arg2, arg3, arg4); \
872 }
873
874 #define safe_syscall5(type, name, type1, arg1, type2, arg2, type3, arg3, \
875     type4, arg4, type5, arg5) \
876 static type safe_##name(type1 arg1, type2 arg2, type3 arg3, type4 arg4, \
877     type5 arg5) \
878 { \
879     return safe_syscall(__NR_##name, arg1, arg2, arg3, arg4, arg5); \
880 }
881
882 #define safe_syscall6(type, name, type1, arg1, type2, arg2, type3, arg3, \
883     type4, arg4, type5, arg5, type6, arg6) \
884 static type safe_##name(type1 arg1, type2 arg2, type3 arg3, type4 arg4, \
885     type5 arg5, type6 arg6) \
886 { \
887     return safe_syscall(__NR_##name, arg1, arg2, arg3, arg4, arg5, arg6); \
888 }
889
890 safe_syscall3(ssize_t, read, int, fd, void *, buff, size_t, count)
891 safe_syscall3(ssize_t, write, int, fd, const void *, buff, size_t, count)
892 safe_syscall4(int, openat, int, dirfd, const char *, pathname, \
893               int, flags, mode_t, mode)
894 safe_syscall4(pid_t, wait4, pid_t, pid, int *, status, int, options, \
895               struct rusage *, rusage)
896 safe_syscall5(int, waitid, idtype_t, idtype, id_t, id, siginfo_t *, infop, \
897               int, options, struct rusage *, rusage)
898 safe_syscall3(int, execve, const char *, filename, char **, argv, char **, envp)
899 safe_syscall6(int, pselect6, int, nfds, fd_set *, readfds, fd_set *, writefds, \
900               fd_set *, exceptfds, struct timespec *, timeout, void *, sig)
901 safe_syscall5(int, ppoll, struct pollfd *, ufds, unsigned int, nfds,
902               struct timespec *, tsp, const sigset_t *, sigmask,
903               size_t, sigsetsize)
904 safe_syscall6(int, epoll_pwait, int, epfd, struct epoll_event *, events,
905               int, maxevents, int, timeout, const sigset_t *, sigmask,
906               size_t, sigsetsize)
907 safe_syscall6(int,futex,int *,uaddr,int,op,int,val, \
908               const struct timespec *,timeout,int *,uaddr2,int,val3)
909 safe_syscall2(int, rt_sigsuspend, sigset_t *, newset, size_t, sigsetsize)
910 safe_syscall2(int, kill, pid_t, pid, int, sig)
911 safe_syscall2(int, tkill, int, tid, int, sig)
912 safe_syscall3(int, tgkill, int, tgid, int, pid, int, sig)
913 safe_syscall3(ssize_t, readv, int, fd, const struct iovec *, iov, int, iovcnt)
914 safe_syscall3(ssize_t, writev, int, fd, const struct iovec *, iov, int, iovcnt)
915 safe_syscall3(int, connect, int, fd, const struct sockaddr *, addr,
916               socklen_t, addrlen)
917 safe_syscall6(ssize_t, sendto, int, fd, const void *, buf, size_t, len,
918               int, flags, const struct sockaddr *, addr, socklen_t, addrlen)
919 safe_syscall6(ssize_t, recvfrom, int, fd, void *, buf, size_t, len,
920               int, flags, struct sockaddr *, addr, socklen_t *, addrlen)
921 safe_syscall3(ssize_t, sendmsg, int, fd, const struct msghdr *, msg, int, flags)
922 safe_syscall3(ssize_t, recvmsg, int, fd, struct msghdr *, msg, int, flags)
923 safe_syscall2(int, flock, int, fd, int, operation)
924 safe_syscall4(int, rt_sigtimedwait, const sigset_t *, these, siginfo_t *, uinfo,
925               const struct timespec *, uts, size_t, sigsetsize)
926 safe_syscall4(int, accept4, int, fd, struct sockaddr *, addr, socklen_t *, len,
927               int, flags)
928 safe_syscall2(int, nanosleep, const struct timespec *, req,
929               struct timespec *, rem)
930 #ifdef TARGET_NR_clock_nanosleep
931 safe_syscall4(int, clock_nanosleep, const clockid_t, clock, int, flags,
932               const struct timespec *, req, struct timespec *, rem)
933 #endif
934 #ifdef __NR_msgsnd
935 safe_syscall4(int, msgsnd, int, msgid, const void *, msgp, size_t, sz,
936               int, flags)
937 safe_syscall5(int, msgrcv, int, msgid, void *, msgp, size_t, sz,
938               long, msgtype, int, flags)
939 safe_syscall4(int, semtimedop, int, semid, struct sembuf *, tsops,
940               unsigned, nsops, const struct timespec *, timeout)
941 #else
942 /* This host kernel architecture uses a single ipc syscall; fake up
943  * wrappers for the sub-operations to hide this implementation detail.
944  * Annoyingly we can't include linux/ipc.h to get the constant definitions
945  * for the call parameter because some structs in there conflict with the
946  * sys/ipc.h ones. So we just define them here, and rely on them being
947  * the same for all host architectures.
948  */
949 #define Q_SEMTIMEDOP 4
950 #define Q_MSGSND 11
951 #define Q_MSGRCV 12
952 #define Q_IPCCALL(VERSION, OP) ((VERSION) << 16 | (OP))
953
954 safe_syscall6(int, ipc, int, call, long, first, long, second, long, third,
955               void *, ptr, long, fifth)
956 static int safe_msgsnd(int msgid, const void *msgp, size_t sz, int flags)
957 {
958     return safe_ipc(Q_IPCCALL(0, Q_MSGSND), msgid, sz, flags, (void *)msgp, 0);
959 }
960 static int safe_msgrcv(int msgid, void *msgp, size_t sz, long type, int flags)
961 {
962     return safe_ipc(Q_IPCCALL(1, Q_MSGRCV), msgid, sz, flags, msgp, type);
963 }
964 static int safe_semtimedop(int semid, struct sembuf *tsops, unsigned nsops,
965                            const struct timespec *timeout)
966 {
967     return safe_ipc(Q_IPCCALL(0, Q_SEMTIMEDOP), semid, nsops, 0, tsops,
968                     (long)timeout);
969 }
970 #endif
971 #if defined(TARGET_NR_mq_open) && defined(__NR_mq_open)
972 safe_syscall5(int, mq_timedsend, int, mqdes, const char *, msg_ptr,
973               size_t, len, unsigned, prio, const struct timespec *, timeout)
974 safe_syscall5(int, mq_timedreceive, int, mqdes, char *, msg_ptr,
975               size_t, len, unsigned *, prio, const struct timespec *, timeout)
976 #endif
977 /* We do ioctl like this rather than via safe_syscall3 to preserve the
978  * "third argument might be integer or pointer or not present" behaviour of
979  * the libc function.
980  */
981 #define safe_ioctl(...) safe_syscall(__NR_ioctl, __VA_ARGS__)
982 /* Similarly for fcntl. Note that callers must always:
983  *  pass the F_GETLK64 etc constants rather than the unsuffixed F_GETLK
984  *  use the flock64 struct rather than unsuffixed flock
985  * This will then work and use a 64-bit offset for both 32-bit and 64-bit hosts.
986  */
987 #ifdef __NR_fcntl64
988 #define safe_fcntl(...) safe_syscall(__NR_fcntl64, __VA_ARGS__)
989 #else
990 #define safe_fcntl(...) safe_syscall(__NR_fcntl, __VA_ARGS__)
991 #endif
992
993 static inline int host_to_target_sock_type(int host_type)
994 {
995     int target_type;
996
997     switch (host_type & 0xf /* SOCK_TYPE_MASK */) {
998     case SOCK_DGRAM:
999         target_type = TARGET_SOCK_DGRAM;
1000         break;
1001     case SOCK_STREAM:
1002         target_type = TARGET_SOCK_STREAM;
1003         break;
1004     default:
1005         target_type = host_type & 0xf /* SOCK_TYPE_MASK */;
1006         break;
1007     }
1008
1009 #if defined(SOCK_CLOEXEC)
1010     if (host_type & SOCK_CLOEXEC) {
1011         target_type |= TARGET_SOCK_CLOEXEC;
1012     }
1013 #endif
1014
1015 #if defined(SOCK_NONBLOCK)
1016     if (host_type & SOCK_NONBLOCK) {
1017         target_type |= TARGET_SOCK_NONBLOCK;
1018     }
1019 #endif
1020
1021     return target_type;
1022 }
1023
1024 static abi_ulong target_brk;
1025 static abi_ulong target_original_brk;
1026 static abi_ulong brk_page;
1027
1028 void target_set_brk(abi_ulong new_brk)
1029 {
1030     target_original_brk = target_brk = HOST_PAGE_ALIGN(new_brk);
1031     brk_page = HOST_PAGE_ALIGN(target_brk);
1032 }
1033
1034 //#define DEBUGF_BRK(message, args...) do { fprintf(stderr, (message), ## args); } while (0)
1035 #define DEBUGF_BRK(message, args...)
1036
1037 /* do_brk() must return target values and target errnos. */
1038 abi_long do_brk(abi_ulong new_brk)
1039 {
1040     abi_long mapped_addr;
1041     abi_ulong new_alloc_size;
1042
1043     DEBUGF_BRK("do_brk(" TARGET_ABI_FMT_lx ") -> ", new_brk);
1044
1045     if (!new_brk) {
1046         DEBUGF_BRK(TARGET_ABI_FMT_lx " (!new_brk)\n", target_brk);
1047         return target_brk;
1048     }
1049     if (new_brk < target_original_brk) {
1050         DEBUGF_BRK(TARGET_ABI_FMT_lx " (new_brk < target_original_brk)\n",
1051                    target_brk);
1052         return target_brk;
1053     }
1054
1055     /* If the new brk is less than the highest page reserved to the
1056      * target heap allocation, set it and we're almost done...  */
1057     if (new_brk <= brk_page) {
1058         /* Heap contents are initialized to zero, as for anonymous
1059          * mapped pages.  */
1060         if (new_brk > target_brk) {
1061             memset(g2h(target_brk), 0, new_brk - target_brk);
1062         }
1063         target_brk = new_brk;
1064         DEBUGF_BRK(TARGET_ABI_FMT_lx " (new_brk <= brk_page)\n", target_brk);
1065         return target_brk;
1066     }
1067
1068     /* We need to allocate more memory after the brk... Note that
1069      * we don't use MAP_FIXED because that will map over the top of
1070      * any existing mapping (like the one with the host libc or qemu
1071      * itself); instead we treat "mapped but at wrong address" as
1072      * a failure and unmap again.
1073      */
1074     new_alloc_size = HOST_PAGE_ALIGN(new_brk - brk_page);
1075     mapped_addr = get_errno(target_mmap(brk_page, new_alloc_size,
1076                                         PROT_READ|PROT_WRITE,
1077                                         MAP_ANON|MAP_PRIVATE, 0, 0));
1078
1079     if (mapped_addr == brk_page) {
1080         /* Heap contents are initialized to zero, as for anonymous
1081          * mapped pages.  Technically the new pages are already
1082          * initialized to zero since they *are* anonymous mapped
1083          * pages, however we have to take care with the contents that
1084          * come from the remaining part of the previous page: it may
1085          * contains garbage data due to a previous heap usage (grown
1086          * then shrunken).  */
1087         memset(g2h(target_brk), 0, brk_page - target_brk);
1088
1089         target_brk = new_brk;
1090         brk_page = HOST_PAGE_ALIGN(target_brk);
1091         DEBUGF_BRK(TARGET_ABI_FMT_lx " (mapped_addr == brk_page)\n",
1092             target_brk);
1093         return target_brk;
1094     } else if (mapped_addr != -1) {
1095         /* Mapped but at wrong address, meaning there wasn't actually
1096          * enough space for this brk.
1097          */
1098         target_munmap(mapped_addr, new_alloc_size);
1099         mapped_addr = -1;
1100         DEBUGF_BRK(TARGET_ABI_FMT_lx " (mapped_addr != -1)\n", target_brk);
1101     }
1102     else {
1103         DEBUGF_BRK(TARGET_ABI_FMT_lx " (otherwise)\n", target_brk);
1104     }
1105
1106 #if defined(TARGET_ALPHA)
1107     /* We (partially) emulate OSF/1 on Alpha, which requires we
1108        return a proper errno, not an unchanged brk value.  */
1109     return -TARGET_ENOMEM;
1110 #endif
1111     /* For everything else, return the previous break. */
1112     return target_brk;
1113 }
1114
1115 static inline abi_long copy_from_user_fdset(fd_set *fds,
1116                                             abi_ulong target_fds_addr,
1117                                             int n)
1118 {
1119     int i, nw, j, k;
1120     abi_ulong b, *target_fds;
1121
1122     nw = DIV_ROUND_UP(n, TARGET_ABI_BITS);
1123     if (!(target_fds = lock_user(VERIFY_READ,
1124                                  target_fds_addr,
1125                                  sizeof(abi_ulong) * nw,
1126                                  1)))
1127         return -TARGET_EFAULT;
1128
1129     FD_ZERO(fds);
1130     k = 0;
1131     for (i = 0; i < nw; i++) {
1132         /* grab the abi_ulong */
1133         __get_user(b, &target_fds[i]);
1134         for (j = 0; j < TARGET_ABI_BITS; j++) {
1135             /* check the bit inside the abi_ulong */
1136             if ((b >> j) & 1)
1137                 FD_SET(k, fds);
1138             k++;
1139         }
1140     }
1141
1142     unlock_user(target_fds, target_fds_addr, 0);
1143
1144     return 0;
1145 }
1146
1147 static inline abi_ulong copy_from_user_fdset_ptr(fd_set *fds, fd_set **fds_ptr,
1148                                                  abi_ulong target_fds_addr,
1149                                                  int n)
1150 {
1151     if (target_fds_addr) {
1152         if (copy_from_user_fdset(fds, target_fds_addr, n))
1153             return -TARGET_EFAULT;
1154         *fds_ptr = fds;
1155     } else {
1156         *fds_ptr = NULL;
1157     }
1158     return 0;
1159 }
1160
1161 static inline abi_long copy_to_user_fdset(abi_ulong target_fds_addr,
1162                                           const fd_set *fds,
1163                                           int n)
1164 {
1165     int i, nw, j, k;
1166     abi_long v;
1167     abi_ulong *target_fds;
1168
1169     nw = DIV_ROUND_UP(n, TARGET_ABI_BITS);
1170     if (!(target_fds = lock_user(VERIFY_WRITE,
1171                                  target_fds_addr,
1172                                  sizeof(abi_ulong) * nw,
1173                                  0)))
1174         return -TARGET_EFAULT;
1175
1176     k = 0;
1177     for (i = 0; i < nw; i++) {
1178         v = 0;
1179         for (j = 0; j < TARGET_ABI_BITS; j++) {
1180             v |= ((abi_ulong)(FD_ISSET(k, fds) != 0) << j);
1181             k++;
1182         }
1183         __put_user(v, &target_fds[i]);
1184     }
1185
1186     unlock_user(target_fds, target_fds_addr, sizeof(abi_ulong) * nw);
1187
1188     return 0;
1189 }
1190
1191 #if defined(__alpha__)
1192 #define HOST_HZ 1024
1193 #else
1194 #define HOST_HZ 100
1195 #endif
1196
1197 static inline abi_long host_to_target_clock_t(long ticks)
1198 {
1199 #if HOST_HZ == TARGET_HZ
1200     return ticks;
1201 #else
1202     return ((int64_t)ticks * TARGET_HZ) / HOST_HZ;
1203 #endif
1204 }
1205
1206 static inline abi_long host_to_target_rusage(abi_ulong target_addr,
1207                                              const struct rusage *rusage)
1208 {
1209     struct target_rusage *target_rusage;
1210
1211     if (!lock_user_struct(VERIFY_WRITE, target_rusage, target_addr, 0))
1212         return -TARGET_EFAULT;
1213     target_rusage->ru_utime.tv_sec = tswapal(rusage->ru_utime.tv_sec);
1214     target_rusage->ru_utime.tv_usec = tswapal(rusage->ru_utime.tv_usec);
1215     target_rusage->ru_stime.tv_sec = tswapal(rusage->ru_stime.tv_sec);
1216     target_rusage->ru_stime.tv_usec = tswapal(rusage->ru_stime.tv_usec);
1217     target_rusage->ru_maxrss = tswapal(rusage->ru_maxrss);
1218     target_rusage->ru_ixrss = tswapal(rusage->ru_ixrss);
1219     target_rusage->ru_idrss = tswapal(rusage->ru_idrss);
1220     target_rusage->ru_isrss = tswapal(rusage->ru_isrss);
1221     target_rusage->ru_minflt = tswapal(rusage->ru_minflt);
1222     target_rusage->ru_majflt = tswapal(rusage->ru_majflt);
1223     target_rusage->ru_nswap = tswapal(rusage->ru_nswap);
1224     target_rusage->ru_inblock = tswapal(rusage->ru_inblock);
1225     target_rusage->ru_oublock = tswapal(rusage->ru_oublock);
1226     target_rusage->ru_msgsnd = tswapal(rusage->ru_msgsnd);
1227     target_rusage->ru_msgrcv = tswapal(rusage->ru_msgrcv);
1228     target_rusage->ru_nsignals = tswapal(rusage->ru_nsignals);
1229     target_rusage->ru_nvcsw = tswapal(rusage->ru_nvcsw);
1230     target_rusage->ru_nivcsw = tswapal(rusage->ru_nivcsw);
1231     unlock_user_struct(target_rusage, target_addr, 1);
1232
1233     return 0;
1234 }
1235
1236 static inline rlim_t target_to_host_rlim(abi_ulong target_rlim)
1237 {
1238     abi_ulong target_rlim_swap;
1239     rlim_t result;
1240     
1241     target_rlim_swap = tswapal(target_rlim);
1242     if (target_rlim_swap == TARGET_RLIM_INFINITY)
1243         return RLIM_INFINITY;
1244
1245     result = target_rlim_swap;
1246     if (target_rlim_swap != (rlim_t)result)
1247         return RLIM_INFINITY;
1248     
1249     return result;
1250 }
1251
1252 static inline abi_ulong host_to_target_rlim(rlim_t rlim)
1253 {
1254     abi_ulong target_rlim_swap;
1255     abi_ulong result;
1256     
1257     if (rlim == RLIM_INFINITY || rlim != (abi_long)rlim)
1258         target_rlim_swap = TARGET_RLIM_INFINITY;
1259     else
1260         target_rlim_swap = rlim;
1261     result = tswapal(target_rlim_swap);
1262     
1263     return result;
1264 }
1265
1266 static inline int target_to_host_resource(int code)
1267 {
1268     switch (code) {
1269     case TARGET_RLIMIT_AS:
1270         return RLIMIT_AS;
1271     case TARGET_RLIMIT_CORE:
1272         return RLIMIT_CORE;
1273     case TARGET_RLIMIT_CPU:
1274         return RLIMIT_CPU;
1275     case TARGET_RLIMIT_DATA:
1276         return RLIMIT_DATA;
1277     case TARGET_RLIMIT_FSIZE:
1278         return RLIMIT_FSIZE;
1279     case TARGET_RLIMIT_LOCKS:
1280         return RLIMIT_LOCKS;
1281     case TARGET_RLIMIT_MEMLOCK:
1282         return RLIMIT_MEMLOCK;
1283     case TARGET_RLIMIT_MSGQUEUE:
1284         return RLIMIT_MSGQUEUE;
1285     case TARGET_RLIMIT_NICE:
1286         return RLIMIT_NICE;
1287     case TARGET_RLIMIT_NOFILE:
1288         return RLIMIT_NOFILE;
1289     case TARGET_RLIMIT_NPROC:
1290         return RLIMIT_NPROC;
1291     case TARGET_RLIMIT_RSS:
1292         return RLIMIT_RSS;
1293     case TARGET_RLIMIT_RTPRIO:
1294         return RLIMIT_RTPRIO;
1295     case TARGET_RLIMIT_SIGPENDING:
1296         return RLIMIT_SIGPENDING;
1297     case TARGET_RLIMIT_STACK:
1298         return RLIMIT_STACK;
1299     default:
1300         return code;
1301     }
1302 }
1303
1304 static inline abi_long copy_from_user_timeval(struct timeval *tv,
1305                                               abi_ulong target_tv_addr)
1306 {
1307     struct target_timeval *target_tv;
1308
1309     if (!lock_user_struct(VERIFY_READ, target_tv, target_tv_addr, 1))
1310         return -TARGET_EFAULT;
1311
1312     __get_user(tv->tv_sec, &target_tv->tv_sec);
1313     __get_user(tv->tv_usec, &target_tv->tv_usec);
1314
1315     unlock_user_struct(target_tv, target_tv_addr, 0);
1316
1317     return 0;
1318 }
1319
1320 static inline abi_long copy_to_user_timeval(abi_ulong target_tv_addr,
1321                                             const struct timeval *tv)
1322 {
1323     struct target_timeval *target_tv;
1324
1325     if (!lock_user_struct(VERIFY_WRITE, target_tv, target_tv_addr, 0))
1326         return -TARGET_EFAULT;
1327
1328     __put_user(tv->tv_sec, &target_tv->tv_sec);
1329     __put_user(tv->tv_usec, &target_tv->tv_usec);
1330
1331     unlock_user_struct(target_tv, target_tv_addr, 1);
1332
1333     return 0;
1334 }
1335
1336 static inline abi_long copy_from_user_timezone(struct timezone *tz,
1337                                                abi_ulong target_tz_addr)
1338 {
1339     struct target_timezone *target_tz;
1340
1341     if (!lock_user_struct(VERIFY_READ, target_tz, target_tz_addr, 1)) {
1342         return -TARGET_EFAULT;
1343     }
1344
1345     __get_user(tz->tz_minuteswest, &target_tz->tz_minuteswest);
1346     __get_user(tz->tz_dsttime, &target_tz->tz_dsttime);
1347
1348     unlock_user_struct(target_tz, target_tz_addr, 0);
1349
1350     return 0;
1351 }
1352
1353 #if defined(TARGET_NR_mq_open) && defined(__NR_mq_open)
1354 #include <mqueue.h>
1355
1356 static inline abi_long copy_from_user_mq_attr(struct mq_attr *attr,
1357                                               abi_ulong target_mq_attr_addr)
1358 {
1359     struct target_mq_attr *target_mq_attr;
1360
1361     if (!lock_user_struct(VERIFY_READ, target_mq_attr,
1362                           target_mq_attr_addr, 1))
1363         return -TARGET_EFAULT;
1364
1365     __get_user(attr->mq_flags, &target_mq_attr->mq_flags);
1366     __get_user(attr->mq_maxmsg, &target_mq_attr->mq_maxmsg);
1367     __get_user(attr->mq_msgsize, &target_mq_attr->mq_msgsize);
1368     __get_user(attr->mq_curmsgs, &target_mq_attr->mq_curmsgs);
1369
1370     unlock_user_struct(target_mq_attr, target_mq_attr_addr, 0);
1371
1372     return 0;
1373 }
1374
1375 static inline abi_long copy_to_user_mq_attr(abi_ulong target_mq_attr_addr,
1376                                             const struct mq_attr *attr)
1377 {
1378     struct target_mq_attr *target_mq_attr;
1379
1380     if (!lock_user_struct(VERIFY_WRITE, target_mq_attr,
1381                           target_mq_attr_addr, 0))
1382         return -TARGET_EFAULT;
1383
1384     __put_user(attr->mq_flags, &target_mq_attr->mq_flags);
1385     __put_user(attr->mq_maxmsg, &target_mq_attr->mq_maxmsg);
1386     __put_user(attr->mq_msgsize, &target_mq_attr->mq_msgsize);
1387     __put_user(attr->mq_curmsgs, &target_mq_attr->mq_curmsgs);
1388
1389     unlock_user_struct(target_mq_attr, target_mq_attr_addr, 1);
1390
1391     return 0;
1392 }
1393 #endif
1394
1395 #if defined(TARGET_NR_select) || defined(TARGET_NR__newselect)
1396 /* do_select() must return target values and target errnos. */
1397 static abi_long do_select(int n,
1398                           abi_ulong rfd_addr, abi_ulong wfd_addr,
1399                           abi_ulong efd_addr, abi_ulong target_tv_addr)
1400 {
1401     fd_set rfds, wfds, efds;
1402     fd_set *rfds_ptr, *wfds_ptr, *efds_ptr;
1403     struct timeval tv;
1404     struct timespec ts, *ts_ptr;
1405     abi_long ret;
1406
1407     ret = copy_from_user_fdset_ptr(&rfds, &rfds_ptr, rfd_addr, n);
1408     if (ret) {
1409         return ret;
1410     }
1411     ret = copy_from_user_fdset_ptr(&wfds, &wfds_ptr, wfd_addr, n);
1412     if (ret) {
1413         return ret;
1414     }
1415     ret = copy_from_user_fdset_ptr(&efds, &efds_ptr, efd_addr, n);
1416     if (ret) {
1417         return ret;
1418     }
1419
1420     if (target_tv_addr) {
1421         if (copy_from_user_timeval(&tv, target_tv_addr))
1422             return -TARGET_EFAULT;
1423         ts.tv_sec = tv.tv_sec;
1424         ts.tv_nsec = tv.tv_usec * 1000;
1425         ts_ptr = &ts;
1426     } else {
1427         ts_ptr = NULL;
1428     }
1429
1430     ret = get_errno(safe_pselect6(n, rfds_ptr, wfds_ptr, efds_ptr,
1431                                   ts_ptr, NULL));
1432
1433     if (!is_error(ret)) {
1434         if (rfd_addr && copy_to_user_fdset(rfd_addr, &rfds, n))
1435             return -TARGET_EFAULT;
1436         if (wfd_addr && copy_to_user_fdset(wfd_addr, &wfds, n))
1437             return -TARGET_EFAULT;
1438         if (efd_addr && copy_to_user_fdset(efd_addr, &efds, n))
1439             return -TARGET_EFAULT;
1440
1441         if (target_tv_addr) {
1442             tv.tv_sec = ts.tv_sec;
1443             tv.tv_usec = ts.tv_nsec / 1000;
1444             if (copy_to_user_timeval(target_tv_addr, &tv)) {
1445                 return -TARGET_EFAULT;
1446             }
1447         }
1448     }
1449
1450     return ret;
1451 }
1452
1453 #if defined(TARGET_WANT_OLD_SYS_SELECT)
1454 static abi_long do_old_select(abi_ulong arg1)
1455 {
1456     struct target_sel_arg_struct *sel;
1457     abi_ulong inp, outp, exp, tvp;
1458     long nsel;
1459
1460     if (!lock_user_struct(VERIFY_READ, sel, arg1, 1)) {
1461         return -TARGET_EFAULT;
1462     }
1463
1464     nsel = tswapal(sel->n);
1465     inp = tswapal(sel->inp);
1466     outp = tswapal(sel->outp);
1467     exp = tswapal(sel->exp);
1468     tvp = tswapal(sel->tvp);
1469
1470     unlock_user_struct(sel, arg1, 0);
1471
1472     return do_select(nsel, inp, outp, exp, tvp);
1473 }
1474 #endif
1475 #endif
1476
1477 static abi_long do_pipe2(int host_pipe[], int flags)
1478 {
1479 #ifdef CONFIG_PIPE2
1480     return pipe2(host_pipe, flags);
1481 #else
1482     return -ENOSYS;
1483 #endif
1484 }
1485
1486 static abi_long do_pipe(void *cpu_env, abi_ulong pipedes,
1487                         int flags, int is_pipe2)
1488 {
1489     int host_pipe[2];
1490     abi_long ret;
1491     ret = flags ? do_pipe2(host_pipe, flags) : pipe(host_pipe);
1492
1493     if (is_error(ret))
1494         return get_errno(ret);
1495
1496     /* Several targets have special calling conventions for the original
1497        pipe syscall, but didn't replicate this into the pipe2 syscall.  */
1498     if (!is_pipe2) {
1499 #if defined(TARGET_ALPHA)
1500         ((CPUAlphaState *)cpu_env)->ir[IR_A4] = host_pipe[1];
1501         return host_pipe[0];
1502 #elif defined(TARGET_MIPS)
1503         ((CPUMIPSState*)cpu_env)->active_tc.gpr[3] = host_pipe[1];
1504         return host_pipe[0];
1505 #elif defined(TARGET_SH4)
1506         ((CPUSH4State*)cpu_env)->gregs[1] = host_pipe[1];
1507         return host_pipe[0];
1508 #elif defined(TARGET_SPARC)
1509         ((CPUSPARCState*)cpu_env)->regwptr[1] = host_pipe[1];
1510         return host_pipe[0];
1511 #endif
1512     }
1513
1514     if (put_user_s32(host_pipe[0], pipedes)
1515         || put_user_s32(host_pipe[1], pipedes + sizeof(host_pipe[0])))
1516         return -TARGET_EFAULT;
1517     return get_errno(ret);
1518 }
1519
1520 static inline abi_long target_to_host_ip_mreq(struct ip_mreqn *mreqn,
1521                                               abi_ulong target_addr,
1522                                               socklen_t len)
1523 {
1524     struct target_ip_mreqn *target_smreqn;
1525
1526     target_smreqn = lock_user(VERIFY_READ, target_addr, len, 1);
1527     if (!target_smreqn)
1528         return -TARGET_EFAULT;
1529     mreqn->imr_multiaddr.s_addr = target_smreqn->imr_multiaddr.s_addr;
1530     mreqn->imr_address.s_addr = target_smreqn->imr_address.s_addr;
1531     if (len == sizeof(struct target_ip_mreqn))
1532         mreqn->imr_ifindex = tswapal(target_smreqn->imr_ifindex);
1533     unlock_user(target_smreqn, target_addr, 0);
1534
1535     return 0;
1536 }
1537
1538 static inline abi_long target_to_host_sockaddr(int fd, struct sockaddr *addr,
1539                                                abi_ulong target_addr,
1540                                                socklen_t len)
1541 {
1542     const socklen_t unix_maxlen = sizeof (struct sockaddr_un);
1543     sa_family_t sa_family;
1544     struct target_sockaddr *target_saddr;
1545
1546     if (fd_trans_target_to_host_addr(fd)) {
1547         return fd_trans_target_to_host_addr(fd)(addr, target_addr, len);
1548     }
1549
1550     target_saddr = lock_user(VERIFY_READ, target_addr, len, 1);
1551     if (!target_saddr)
1552         return -TARGET_EFAULT;
1553
1554     sa_family = tswap16(target_saddr->sa_family);
1555
1556     /* Oops. The caller might send a incomplete sun_path; sun_path
1557      * must be terminated by \0 (see the manual page), but
1558      * unfortunately it is quite common to specify sockaddr_un
1559      * length as "strlen(x->sun_path)" while it should be
1560      * "strlen(...) + 1". We'll fix that here if needed.
1561      * Linux kernel has a similar feature.
1562      */
1563
1564     if (sa_family == AF_UNIX) {
1565         if (len < unix_maxlen && len > 0) {
1566             char *cp = (char*)target_saddr;
1567
1568             if ( cp[len-1] && !cp[len] )
1569                 len++;
1570         }
1571         if (len > unix_maxlen)
1572             len = unix_maxlen;
1573     }
1574
1575     memcpy(addr, target_saddr, len);
1576     addr->sa_family = sa_family;
1577     if (sa_family == AF_NETLINK) {
1578         struct sockaddr_nl *nladdr;
1579
1580         nladdr = (struct sockaddr_nl *)addr;
1581         nladdr->nl_pid = tswap32(nladdr->nl_pid);
1582         nladdr->nl_groups = tswap32(nladdr->nl_groups);
1583     } else if (sa_family == AF_PACKET) {
1584         struct target_sockaddr_ll *lladdr;
1585
1586         lladdr = (struct target_sockaddr_ll *)addr;
1587         lladdr->sll_ifindex = tswap32(lladdr->sll_ifindex);
1588         lladdr->sll_hatype = tswap16(lladdr->sll_hatype);
1589     }
1590     unlock_user(target_saddr, target_addr, 0);
1591
1592     return 0;
1593 }
1594
1595 static inline abi_long host_to_target_sockaddr(abi_ulong target_addr,
1596                                                struct sockaddr *addr,
1597                                                socklen_t len)
1598 {
1599     struct target_sockaddr *target_saddr;
1600
1601     if (len == 0) {
1602         return 0;
1603     }
1604
1605     target_saddr = lock_user(VERIFY_WRITE, target_addr, len, 0);
1606     if (!target_saddr)
1607         return -TARGET_EFAULT;
1608     memcpy(target_saddr, addr, len);
1609     if (len >= offsetof(struct target_sockaddr, sa_family) +
1610         sizeof(target_saddr->sa_family)) {
1611         target_saddr->sa_family = tswap16(addr->sa_family);
1612     }
1613     if (addr->sa_family == AF_NETLINK && len >= sizeof(struct sockaddr_nl)) {
1614         struct sockaddr_nl *target_nl = (struct sockaddr_nl *)target_saddr;
1615         target_nl->nl_pid = tswap32(target_nl->nl_pid);
1616         target_nl->nl_groups = tswap32(target_nl->nl_groups);
1617     } else if (addr->sa_family == AF_PACKET) {
1618         struct sockaddr_ll *target_ll = (struct sockaddr_ll *)target_saddr;
1619         target_ll->sll_ifindex = tswap32(target_ll->sll_ifindex);
1620         target_ll->sll_hatype = tswap16(target_ll->sll_hatype);
1621     }
1622     unlock_user(target_saddr, target_addr, len);
1623
1624     return 0;
1625 }
1626
1627 static inline abi_long target_to_host_cmsg(struct msghdr *msgh,
1628                                            struct target_msghdr *target_msgh)
1629 {
1630     struct cmsghdr *cmsg = CMSG_FIRSTHDR(msgh);
1631     abi_long msg_controllen;
1632     abi_ulong target_cmsg_addr;
1633     struct target_cmsghdr *target_cmsg, *target_cmsg_start;
1634     socklen_t space = 0;
1635     
1636     msg_controllen = tswapal(target_msgh->msg_controllen);
1637     if (msg_controllen < sizeof (struct target_cmsghdr)) 
1638         goto the_end;
1639     target_cmsg_addr = tswapal(target_msgh->msg_control);
1640     target_cmsg = lock_user(VERIFY_READ, target_cmsg_addr, msg_controllen, 1);
1641     target_cmsg_start = target_cmsg;
1642     if (!target_cmsg)
1643         return -TARGET_EFAULT;
1644
1645     while (cmsg && target_cmsg) {
1646         void *data = CMSG_DATA(cmsg);
1647         void *target_data = TARGET_CMSG_DATA(target_cmsg);
1648
1649         int len = tswapal(target_cmsg->cmsg_len)
1650                   - TARGET_CMSG_ALIGN(sizeof (struct target_cmsghdr));
1651
1652         space += CMSG_SPACE(len);
1653         if (space > msgh->msg_controllen) {
1654             space -= CMSG_SPACE(len);
1655             /* This is a QEMU bug, since we allocated the payload
1656              * area ourselves (unlike overflow in host-to-target
1657              * conversion, which is just the guest giving us a buffer
1658              * that's too small). It can't happen for the payload types
1659              * we currently support; if it becomes an issue in future
1660              * we would need to improve our allocation strategy to
1661              * something more intelligent than "twice the size of the
1662              * target buffer we're reading from".
1663              */
1664             gemu_log("Host cmsg overflow\n");
1665             break;
1666         }
1667
1668         if (tswap32(target_cmsg->cmsg_level) == TARGET_SOL_SOCKET) {
1669             cmsg->cmsg_level = SOL_SOCKET;
1670         } else {
1671             cmsg->cmsg_level = tswap32(target_cmsg->cmsg_level);
1672         }
1673         cmsg->cmsg_type = tswap32(target_cmsg->cmsg_type);
1674         cmsg->cmsg_len = CMSG_LEN(len);
1675
1676         if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
1677             int *fd = (int *)data;
1678             int *target_fd = (int *)target_data;
1679             int i, numfds = len / sizeof(int);
1680
1681             for (i = 0; i < numfds; i++) {
1682                 __get_user(fd[i], target_fd + i);
1683             }
1684         } else if (cmsg->cmsg_level == SOL_SOCKET
1685                &&  cmsg->cmsg_type == SCM_CREDENTIALS) {
1686             struct ucred *cred = (struct ucred *)data;
1687             struct target_ucred *target_cred =
1688                 (struct target_ucred *)target_data;
1689
1690             __get_user(cred->pid, &target_cred->pid);
1691             __get_user(cred->uid, &target_cred->uid);
1692             __get_user(cred->gid, &target_cred->gid);
1693         } else {
1694             gemu_log("Unsupported ancillary data: %d/%d\n",
1695                                         cmsg->cmsg_level, cmsg->cmsg_type);
1696             memcpy(data, target_data, len);
1697         }
1698
1699         cmsg = CMSG_NXTHDR(msgh, cmsg);
1700         target_cmsg = TARGET_CMSG_NXTHDR(target_msgh, target_cmsg,
1701                                          target_cmsg_start);
1702     }
1703     unlock_user(target_cmsg, target_cmsg_addr, 0);
1704  the_end:
1705     msgh->msg_controllen = space;
1706     return 0;
1707 }
1708
1709 static inline abi_long host_to_target_cmsg(struct target_msghdr *target_msgh,
1710                                            struct msghdr *msgh)
1711 {
1712     struct cmsghdr *cmsg = CMSG_FIRSTHDR(msgh);
1713     abi_long msg_controllen;
1714     abi_ulong target_cmsg_addr;
1715     struct target_cmsghdr *target_cmsg, *target_cmsg_start;
1716     socklen_t space = 0;
1717
1718     msg_controllen = tswapal(target_msgh->msg_controllen);
1719     if (msg_controllen < sizeof (struct target_cmsghdr)) 
1720         goto the_end;
1721     target_cmsg_addr = tswapal(target_msgh->msg_control);
1722     target_cmsg = lock_user(VERIFY_WRITE, target_cmsg_addr, msg_controllen, 0);
1723     target_cmsg_start = target_cmsg;
1724     if (!target_cmsg)
1725         return -TARGET_EFAULT;
1726
1727     while (cmsg && target_cmsg) {
1728         void *data = CMSG_DATA(cmsg);
1729         void *target_data = TARGET_CMSG_DATA(target_cmsg);
1730
1731         int len = cmsg->cmsg_len - CMSG_ALIGN(sizeof (struct cmsghdr));
1732         int tgt_len, tgt_space;
1733
1734         /* We never copy a half-header but may copy half-data;
1735          * this is Linux's behaviour in put_cmsg(). Note that
1736          * truncation here is a guest problem (which we report
1737          * to the guest via the CTRUNC bit), unlike truncation
1738          * in target_to_host_cmsg, which is a QEMU bug.
1739          */
1740         if (msg_controllen < sizeof(struct cmsghdr)) {
1741             target_msgh->msg_flags |= tswap32(MSG_CTRUNC);
1742             break;
1743         }
1744
1745         if (cmsg->cmsg_level == SOL_SOCKET) {
1746             target_cmsg->cmsg_level = tswap32(TARGET_SOL_SOCKET);
1747         } else {
1748             target_cmsg->cmsg_level = tswap32(cmsg->cmsg_level);
1749         }
1750         target_cmsg->cmsg_type = tswap32(cmsg->cmsg_type);
1751
1752         tgt_len = TARGET_CMSG_LEN(len);
1753
1754         /* Payload types which need a different size of payload on
1755          * the target must adjust tgt_len here.
1756          */
1757         switch (cmsg->cmsg_level) {
1758         case SOL_SOCKET:
1759             switch (cmsg->cmsg_type) {
1760             case SO_TIMESTAMP:
1761                 tgt_len = sizeof(struct target_timeval);
1762                 break;
1763             default:
1764                 break;
1765             }
1766         default:
1767             break;
1768         }
1769
1770         if (msg_controllen < tgt_len) {
1771             target_msgh->msg_flags |= tswap32(MSG_CTRUNC);
1772             tgt_len = msg_controllen;
1773         }
1774
1775         /* We must now copy-and-convert len bytes of payload
1776          * into tgt_len bytes of destination space. Bear in mind
1777          * that in both source and destination we may be dealing
1778          * with a truncated value!
1779          */
1780         switch (cmsg->cmsg_level) {
1781         case SOL_SOCKET:
1782             switch (cmsg->cmsg_type) {
1783             case SCM_RIGHTS:
1784             {
1785                 int *fd = (int *)data;
1786                 int *target_fd = (int *)target_data;
1787                 int i, numfds = tgt_len / sizeof(int);
1788
1789                 for (i = 0; i < numfds; i++) {
1790                     __put_user(fd[i], target_fd + i);
1791                 }
1792                 break;
1793             }
1794             case SO_TIMESTAMP:
1795             {
1796                 struct timeval *tv = (struct timeval *)data;
1797                 struct target_timeval *target_tv =
1798                     (struct target_timeval *)target_data;
1799
1800                 if (len != sizeof(struct timeval) ||
1801                     tgt_len != sizeof(struct target_timeval)) {
1802                     goto unimplemented;
1803                 }
1804
1805                 /* copy struct timeval to target */
1806                 __put_user(tv->tv_sec, &target_tv->tv_sec);
1807                 __put_user(tv->tv_usec, &target_tv->tv_usec);
1808                 break;
1809             }
1810             case SCM_CREDENTIALS:
1811             {
1812                 struct ucred *cred = (struct ucred *)data;
1813                 struct target_ucred *target_cred =
1814                     (struct target_ucred *)target_data;
1815
1816                 __put_user(cred->pid, &target_cred->pid);
1817                 __put_user(cred->uid, &target_cred->uid);
1818                 __put_user(cred->gid, &target_cred->gid);
1819                 break;
1820             }
1821             default:
1822                 goto unimplemented;
1823             }
1824             break;
1825
1826         default:
1827         unimplemented:
1828             gemu_log("Unsupported ancillary data: %d/%d\n",
1829                                         cmsg->cmsg_level, cmsg->cmsg_type);
1830             memcpy(target_data, data, MIN(len, tgt_len));
1831             if (tgt_len > len) {
1832                 memset(target_data + len, 0, tgt_len - len);
1833             }
1834         }
1835
1836         target_cmsg->cmsg_len = tswapal(tgt_len);
1837         tgt_space = TARGET_CMSG_SPACE(len);
1838         if (msg_controllen < tgt_space) {
1839             tgt_space = msg_controllen;
1840         }
1841         msg_controllen -= tgt_space;
1842         space += tgt_space;
1843         cmsg = CMSG_NXTHDR(msgh, cmsg);
1844         target_cmsg = TARGET_CMSG_NXTHDR(target_msgh, target_cmsg,
1845                                          target_cmsg_start);
1846     }
1847     unlock_user(target_cmsg, target_cmsg_addr, space);
1848  the_end:
1849     target_msgh->msg_controllen = tswapal(space);
1850     return 0;
1851 }
1852
1853 static void tswap_nlmsghdr(struct nlmsghdr *nlh)
1854 {
1855     nlh->nlmsg_len = tswap32(nlh->nlmsg_len);
1856     nlh->nlmsg_type = tswap16(nlh->nlmsg_type);
1857     nlh->nlmsg_flags = tswap16(nlh->nlmsg_flags);
1858     nlh->nlmsg_seq = tswap32(nlh->nlmsg_seq);
1859     nlh->nlmsg_pid = tswap32(nlh->nlmsg_pid);
1860 }
1861
1862 static abi_long host_to_target_for_each_nlmsg(struct nlmsghdr *nlh,
1863                                               size_t len,
1864                                               abi_long (*host_to_target_nlmsg)
1865                                                        (struct nlmsghdr *))
1866 {
1867     uint32_t nlmsg_len;
1868     abi_long ret;
1869
1870     while (len > sizeof(struct nlmsghdr)) {
1871
1872         nlmsg_len = nlh->nlmsg_len;
1873         if (nlmsg_len < sizeof(struct nlmsghdr) ||
1874             nlmsg_len > len) {
1875             break;
1876         }
1877
1878         switch (nlh->nlmsg_type) {
1879         case NLMSG_DONE:
1880             tswap_nlmsghdr(nlh);
1881             return 0;
1882         case NLMSG_NOOP:
1883             break;
1884         case NLMSG_ERROR:
1885         {
1886             struct nlmsgerr *e = NLMSG_DATA(nlh);
1887             e->error = tswap32(e->error);
1888             tswap_nlmsghdr(&e->msg);
1889             tswap_nlmsghdr(nlh);
1890             return 0;
1891         }
1892         default:
1893             ret = host_to_target_nlmsg(nlh);
1894             if (ret < 0) {
1895                 tswap_nlmsghdr(nlh);
1896                 return ret;
1897             }
1898             break;
1899         }
1900         tswap_nlmsghdr(nlh);
1901         len -= NLMSG_ALIGN(nlmsg_len);
1902         nlh = (struct nlmsghdr *)(((char*)nlh) + NLMSG_ALIGN(nlmsg_len));
1903     }
1904     return 0;
1905 }
1906
1907 static abi_long target_to_host_for_each_nlmsg(struct nlmsghdr *nlh,
1908                                               size_t len,
1909                                               abi_long (*target_to_host_nlmsg)
1910                                                        (struct nlmsghdr *))
1911 {
1912     int ret;
1913
1914     while (len > sizeof(struct nlmsghdr)) {
1915         if (tswap32(nlh->nlmsg_len) < sizeof(struct nlmsghdr) ||
1916             tswap32(nlh->nlmsg_len) > len) {
1917             break;
1918         }
1919         tswap_nlmsghdr(nlh);
1920         switch (nlh->nlmsg_type) {
1921         case NLMSG_DONE:
1922             return 0;
1923         case NLMSG_NOOP:
1924             break;
1925         case NLMSG_ERROR:
1926         {
1927             struct nlmsgerr *e = NLMSG_DATA(nlh);
1928             e->error = tswap32(e->error);
1929             tswap_nlmsghdr(&e->msg);
1930             return 0;
1931         }
1932         default:
1933             ret = target_to_host_nlmsg(nlh);
1934             if (ret < 0) {
1935                 return ret;
1936             }
1937         }
1938         len -= NLMSG_ALIGN(nlh->nlmsg_len);
1939         nlh = (struct nlmsghdr *)(((char *)nlh) + NLMSG_ALIGN(nlh->nlmsg_len));
1940     }
1941     return 0;
1942 }
1943
1944 #ifdef CONFIG_RTNETLINK
1945 static abi_long host_to_target_for_each_nlattr(struct nlattr *nlattr,
1946                                                size_t len, void *context,
1947                                                abi_long (*host_to_target_nlattr)
1948                                                         (struct nlattr *,
1949                                                          void *context))
1950 {
1951     unsigned short nla_len;
1952     abi_long ret;
1953
1954     while (len > sizeof(struct nlattr)) {
1955         nla_len = nlattr->nla_len;
1956         if (nla_len < sizeof(struct nlattr) ||
1957             nla_len > len) {
1958             break;
1959         }
1960         ret = host_to_target_nlattr(nlattr, context);
1961         nlattr->nla_len = tswap16(nlattr->nla_len);
1962         nlattr->nla_type = tswap16(nlattr->nla_type);
1963         if (ret < 0) {
1964             return ret;
1965         }
1966         len -= NLA_ALIGN(nla_len);
1967         nlattr = (struct nlattr *)(((char *)nlattr) + NLA_ALIGN(nla_len));
1968     }
1969     return 0;
1970 }
1971
1972 static abi_long host_to_target_for_each_rtattr(struct rtattr *rtattr,
1973                                                size_t len,
1974                                                abi_long (*host_to_target_rtattr)
1975                                                         (struct rtattr *))
1976 {
1977     unsigned short rta_len;
1978     abi_long ret;
1979
1980     while (len > sizeof(struct rtattr)) {
1981         rta_len = rtattr->rta_len;
1982         if (rta_len < sizeof(struct rtattr) ||
1983             rta_len > len) {
1984             break;
1985         }
1986         ret = host_to_target_rtattr(rtattr);
1987         rtattr->rta_len = tswap16(rtattr->rta_len);
1988         rtattr->rta_type = tswap16(rtattr->rta_type);
1989         if (ret < 0) {
1990             return ret;
1991         }
1992         len -= RTA_ALIGN(rta_len);
1993         rtattr = (struct rtattr *)(((char *)rtattr) + RTA_ALIGN(rta_len));
1994     }
1995     return 0;
1996 }
1997
1998 #define NLA_DATA(nla) ((void *)((char *)(nla)) + NLA_HDRLEN)
1999
2000 static abi_long host_to_target_data_bridge_nlattr(struct nlattr *nlattr,
2001                                                   void *context)
2002 {
2003     uint16_t *u16;
2004     uint32_t *u32;
2005     uint64_t *u64;
2006
2007     switch (nlattr->nla_type) {
2008     /* no data */
2009     case QEMU_IFLA_BR_FDB_FLUSH:
2010         break;
2011     /* binary */
2012     case QEMU_IFLA_BR_GROUP_ADDR:
2013         break;
2014     /* uint8_t */
2015     case QEMU_IFLA_BR_VLAN_FILTERING:
2016     case QEMU_IFLA_BR_TOPOLOGY_CHANGE:
2017     case QEMU_IFLA_BR_TOPOLOGY_CHANGE_DETECTED:
2018     case QEMU_IFLA_BR_MCAST_ROUTER:
2019     case QEMU_IFLA_BR_MCAST_SNOOPING:
2020     case QEMU_IFLA_BR_MCAST_QUERY_USE_IFADDR:
2021     case QEMU_IFLA_BR_MCAST_QUERIER:
2022     case QEMU_IFLA_BR_NF_CALL_IPTABLES:
2023     case QEMU_IFLA_BR_NF_CALL_IP6TABLES:
2024     case QEMU_IFLA_BR_NF_CALL_ARPTABLES:
2025         break;
2026     /* uint16_t */
2027     case QEMU_IFLA_BR_PRIORITY:
2028     case QEMU_IFLA_BR_VLAN_PROTOCOL:
2029     case QEMU_IFLA_BR_GROUP_FWD_MASK:
2030     case QEMU_IFLA_BR_ROOT_PORT:
2031     case QEMU_IFLA_BR_VLAN_DEFAULT_PVID:
2032         u16 = NLA_DATA(nlattr);
2033         *u16 = tswap16(*u16);
2034         break;
2035     /* uint32_t */
2036     case QEMU_IFLA_BR_FORWARD_DELAY:
2037     case QEMU_IFLA_BR_HELLO_TIME:
2038     case QEMU_IFLA_BR_MAX_AGE:
2039     case QEMU_IFLA_BR_AGEING_TIME:
2040     case QEMU_IFLA_BR_STP_STATE:
2041     case QEMU_IFLA_BR_ROOT_PATH_COST:
2042     case QEMU_IFLA_BR_MCAST_HASH_ELASTICITY:
2043     case QEMU_IFLA_BR_MCAST_HASH_MAX:
2044     case QEMU_IFLA_BR_MCAST_LAST_MEMBER_CNT:
2045     case QEMU_IFLA_BR_MCAST_STARTUP_QUERY_CNT:
2046         u32 = NLA_DATA(nlattr);
2047         *u32 = tswap32(*u32);
2048         break;
2049     /* uint64_t */
2050     case QEMU_IFLA_BR_HELLO_TIMER:
2051     case QEMU_IFLA_BR_TCN_TIMER:
2052     case QEMU_IFLA_BR_GC_TIMER:
2053     case QEMU_IFLA_BR_TOPOLOGY_CHANGE_TIMER:
2054     case QEMU_IFLA_BR_MCAST_LAST_MEMBER_INTVL:
2055     case QEMU_IFLA_BR_MCAST_MEMBERSHIP_INTVL:
2056     case QEMU_IFLA_BR_MCAST_QUERIER_INTVL:
2057     case QEMU_IFLA_BR_MCAST_QUERY_INTVL:
2058     case QEMU_IFLA_BR_MCAST_QUERY_RESPONSE_INTVL:
2059     case QEMU_IFLA_BR_MCAST_STARTUP_QUERY_INTVL:
2060         u64 = NLA_DATA(nlattr);
2061         *u64 = tswap64(*u64);
2062         break;
2063     /* ifla_bridge_id: uin8_t[] */
2064     case QEMU_IFLA_BR_ROOT_ID:
2065     case QEMU_IFLA_BR_BRIDGE_ID:
2066         break;
2067     default:
2068         gemu_log("Unknown QEMU_IFLA_BR type %d\n", nlattr->nla_type);
2069         break;
2070     }
2071     return 0;
2072 }
2073
2074 static abi_long host_to_target_slave_data_bridge_nlattr(struct nlattr *nlattr,
2075                                                         void *context)
2076 {
2077     uint16_t *u16;
2078     uint32_t *u32;
2079     uint64_t *u64;
2080
2081     switch (nlattr->nla_type) {
2082     /* uint8_t */
2083     case QEMU_IFLA_BRPORT_STATE:
2084     case QEMU_IFLA_BRPORT_MODE:
2085     case QEMU_IFLA_BRPORT_GUARD:
2086     case QEMU_IFLA_BRPORT_PROTECT:
2087     case QEMU_IFLA_BRPORT_FAST_LEAVE:
2088     case QEMU_IFLA_BRPORT_LEARNING:
2089     case QEMU_IFLA_BRPORT_UNICAST_FLOOD:
2090     case QEMU_IFLA_BRPORT_PROXYARP:
2091     case QEMU_IFLA_BRPORT_LEARNING_SYNC:
2092     case QEMU_IFLA_BRPORT_PROXYARP_WIFI:
2093     case QEMU_IFLA_BRPORT_TOPOLOGY_CHANGE_ACK:
2094     case QEMU_IFLA_BRPORT_CONFIG_PENDING:
2095     case QEMU_IFLA_BRPORT_MULTICAST_ROUTER:
2096         break;
2097     /* uint16_t */
2098     case QEMU_IFLA_BRPORT_PRIORITY:
2099     case QEMU_IFLA_BRPORT_DESIGNATED_PORT:
2100     case QEMU_IFLA_BRPORT_DESIGNATED_COST:
2101     case QEMU_IFLA_BRPORT_ID:
2102     case QEMU_IFLA_BRPORT_NO:
2103         u16 = NLA_DATA(nlattr);
2104         *u16 = tswap16(*u16);
2105         break;
2106     /* uin32_t */
2107     case QEMU_IFLA_BRPORT_COST:
2108         u32 = NLA_DATA(nlattr);
2109         *u32 = tswap32(*u32);
2110         break;
2111     /* uint64_t */
2112     case QEMU_IFLA_BRPORT_MESSAGE_AGE_TIMER:
2113     case QEMU_IFLA_BRPORT_FORWARD_DELAY_TIMER:
2114     case QEMU_IFLA_BRPORT_HOLD_TIMER:
2115         u64 = NLA_DATA(nlattr);
2116         *u64 = tswap64(*u64);
2117         break;
2118     /* ifla_bridge_id: uint8_t[] */
2119     case QEMU_IFLA_BRPORT_ROOT_ID:
2120     case QEMU_IFLA_BRPORT_BRIDGE_ID:
2121         break;
2122     default:
2123         gemu_log("Unknown QEMU_IFLA_BRPORT type %d\n", nlattr->nla_type);
2124         break;
2125     }
2126     return 0;
2127 }
2128
2129 struct linkinfo_context {
2130     int len;
2131     char *name;
2132     int slave_len;
2133     char *slave_name;
2134 };
2135
2136 static abi_long host_to_target_data_linkinfo_nlattr(struct nlattr *nlattr,
2137                                                     void *context)
2138 {
2139     struct linkinfo_context *li_context = context;
2140
2141     switch (nlattr->nla_type) {
2142     /* string */
2143     case QEMU_IFLA_INFO_KIND:
2144         li_context->name = NLA_DATA(nlattr);
2145         li_context->len = nlattr->nla_len - NLA_HDRLEN;
2146         break;
2147     case QEMU_IFLA_INFO_SLAVE_KIND:
2148         li_context->slave_name = NLA_DATA(nlattr);
2149         li_context->slave_len = nlattr->nla_len - NLA_HDRLEN;
2150         break;
2151     /* stats */
2152     case QEMU_IFLA_INFO_XSTATS:
2153         /* FIXME: only used by CAN */
2154         break;
2155     /* nested */
2156     case QEMU_IFLA_INFO_DATA:
2157         if (strncmp(li_context->name, "bridge",
2158                     li_context->len) == 0) {
2159             return host_to_target_for_each_nlattr(NLA_DATA(nlattr),
2160                                                   nlattr->nla_len,
2161                                                   NULL,
2162                                              host_to_target_data_bridge_nlattr);
2163         } else {
2164             gemu_log("Unknown QEMU_IFLA_INFO_KIND %s\n", li_context->name);
2165         }
2166         break;
2167     case QEMU_IFLA_INFO_SLAVE_DATA:
2168         if (strncmp(li_context->slave_name, "bridge",
2169                     li_context->slave_len) == 0) {
2170             return host_to_target_for_each_nlattr(NLA_DATA(nlattr),
2171                                                   nlattr->nla_len,
2172                                                   NULL,
2173                                        host_to_target_slave_data_bridge_nlattr);
2174         } else {
2175             gemu_log("Unknown QEMU_IFLA_INFO_SLAVE_KIND %s\n",
2176                      li_context->slave_name);
2177         }
2178         break;
2179     default:
2180         gemu_log("Unknown host QEMU_IFLA_INFO type: %d\n", nlattr->nla_type);
2181         break;
2182     }
2183
2184     return 0;
2185 }
2186
2187 static abi_long host_to_target_data_inet_nlattr(struct nlattr *nlattr,
2188                                                 void *context)
2189 {
2190     uint32_t *u32;
2191     int i;
2192
2193     switch (nlattr->nla_type) {
2194     case QEMU_IFLA_INET_CONF:
2195         u32 = NLA_DATA(nlattr);
2196         for (i = 0; i < (nlattr->nla_len - NLA_HDRLEN) / sizeof(*u32);
2197              i++) {
2198             u32[i] = tswap32(u32[i]);
2199         }
2200         break;
2201     default:
2202         gemu_log("Unknown host AF_INET type: %d\n", nlattr->nla_type);
2203     }
2204     return 0;
2205 }
2206
2207 static abi_long host_to_target_data_inet6_nlattr(struct nlattr *nlattr,
2208                                                 void *context)
2209 {
2210     uint32_t *u32;
2211     uint64_t *u64;
2212     struct ifla_cacheinfo *ci;
2213     int i;
2214
2215     switch (nlattr->nla_type) {
2216     /* binaries */
2217     case QEMU_IFLA_INET6_TOKEN:
2218         break;
2219     /* uint8_t */
2220     case QEMU_IFLA_INET6_ADDR_GEN_MODE:
2221         break;
2222     /* uint32_t */
2223     case QEMU_IFLA_INET6_FLAGS:
2224         u32 = NLA_DATA(nlattr);
2225         *u32 = tswap32(*u32);
2226         break;
2227     /* uint32_t[] */
2228     case QEMU_IFLA_INET6_CONF:
2229         u32 = NLA_DATA(nlattr);
2230         for (i = 0; i < (nlattr->nla_len - NLA_HDRLEN) / sizeof(*u32);
2231              i++) {
2232             u32[i] = tswap32(u32[i]);
2233         }
2234         break;
2235     /* ifla_cacheinfo */
2236     case QEMU_IFLA_INET6_CACHEINFO:
2237         ci = NLA_DATA(nlattr);
2238         ci->max_reasm_len = tswap32(ci->max_reasm_len);
2239         ci->tstamp = tswap32(ci->tstamp);
2240         ci->reachable_time = tswap32(ci->reachable_time);
2241         ci->retrans_time = tswap32(ci->retrans_time);
2242         break;
2243     /* uint64_t[] */
2244     case QEMU_IFLA_INET6_STATS:
2245     case QEMU_IFLA_INET6_ICMP6STATS:
2246         u64 = NLA_DATA(nlattr);
2247         for (i = 0; i < (nlattr->nla_len - NLA_HDRLEN) / sizeof(*u64);
2248              i++) {
2249             u64[i] = tswap64(u64[i]);
2250         }
2251         break;
2252     default:
2253         gemu_log("Unknown host AF_INET6 type: %d\n", nlattr->nla_type);
2254     }
2255     return 0;
2256 }
2257
2258 static abi_long host_to_target_data_spec_nlattr(struct nlattr *nlattr,
2259                                                     void *context)
2260 {
2261     switch (nlattr->nla_type) {
2262     case AF_INET:
2263         return host_to_target_for_each_nlattr(NLA_DATA(nlattr), nlattr->nla_len,
2264                                               NULL,
2265                                              host_to_target_data_inet_nlattr);
2266     case AF_INET6:
2267         return host_to_target_for_each_nlattr(NLA_DATA(nlattr), nlattr->nla_len,
2268                                               NULL,
2269                                              host_to_target_data_inet6_nlattr);
2270     default:
2271         gemu_log("Unknown host AF_SPEC type: %d\n", nlattr->nla_type);
2272         break;
2273     }
2274     return 0;
2275 }
2276
2277 static abi_long host_to_target_data_link_rtattr(struct rtattr *rtattr)
2278 {
2279     uint32_t *u32;
2280     struct rtnl_link_stats *st;
2281     struct rtnl_link_stats64 *st64;
2282     struct rtnl_link_ifmap *map;
2283     struct linkinfo_context li_context;
2284
2285     switch (rtattr->rta_type) {
2286     /* binary stream */
2287     case QEMU_IFLA_ADDRESS:
2288     case QEMU_IFLA_BROADCAST:
2289     /* string */
2290     case QEMU_IFLA_IFNAME:
2291     case QEMU_IFLA_QDISC:
2292         break;
2293     /* uin8_t */
2294     case QEMU_IFLA_OPERSTATE:
2295     case QEMU_IFLA_LINKMODE:
2296     case QEMU_IFLA_CARRIER:
2297     case QEMU_IFLA_PROTO_DOWN:
2298         break;
2299     /* uint32_t */
2300     case QEMU_IFLA_MTU:
2301     case QEMU_IFLA_LINK:
2302     case QEMU_IFLA_WEIGHT:
2303     case QEMU_IFLA_TXQLEN:
2304     case QEMU_IFLA_CARRIER_CHANGES:
2305     case QEMU_IFLA_NUM_RX_QUEUES:
2306     case QEMU_IFLA_NUM_TX_QUEUES:
2307     case QEMU_IFLA_PROMISCUITY:
2308     case QEMU_IFLA_EXT_MASK:
2309     case QEMU_IFLA_LINK_NETNSID:
2310     case QEMU_IFLA_GROUP:
2311     case QEMU_IFLA_MASTER:
2312     case QEMU_IFLA_NUM_VF:
2313         u32 = RTA_DATA(rtattr);
2314         *u32 = tswap32(*u32);
2315         break;
2316     /* struct rtnl_link_stats */
2317     case QEMU_IFLA_STATS:
2318         st = RTA_DATA(rtattr);
2319         st->rx_packets = tswap32(st->rx_packets);
2320         st->tx_packets = tswap32(st->tx_packets);
2321         st->rx_bytes = tswap32(st->rx_bytes);
2322         st->tx_bytes = tswap32(st->tx_bytes);
2323         st->rx_errors = tswap32(st->rx_errors);
2324         st->tx_errors = tswap32(st->tx_errors);
2325         st->rx_dropped = tswap32(st->rx_dropped);
2326         st->tx_dropped = tswap32(st->tx_dropped);
2327         st->multicast = tswap32(st->multicast);
2328         st->collisions = tswap32(st->collisions);
2329
2330         /* detailed rx_errors: */
2331         st->rx_length_errors = tswap32(st->rx_length_errors);
2332         st->rx_over_errors = tswap32(st->rx_over_errors);
2333         st->rx_crc_errors = tswap32(st->rx_crc_errors);
2334         st->rx_frame_errors = tswap32(st->rx_frame_errors);
2335         st->rx_fifo_errors = tswap32(st->rx_fifo_errors);
2336         st->rx_missed_errors = tswap32(st->rx_missed_errors);
2337
2338         /* detailed tx_errors */
2339         st->tx_aborted_errors = tswap32(st->tx_aborted_errors);
2340         st->tx_carrier_errors = tswap32(st->tx_carrier_errors);
2341         st->tx_fifo_errors = tswap32(st->tx_fifo_errors);
2342         st->tx_heartbeat_errors = tswap32(st->tx_heartbeat_errors);
2343         st->tx_window_errors = tswap32(st->tx_window_errors);
2344
2345         /* for cslip etc */
2346         st->rx_compressed = tswap32(st->rx_compressed);
2347         st->tx_compressed = tswap32(st->tx_compressed);
2348         break;
2349     /* struct rtnl_link_stats64 */
2350     case QEMU_IFLA_STATS64:
2351         st64 = RTA_DATA(rtattr);
2352         st64->rx_packets = tswap64(st64->rx_packets);
2353         st64->tx_packets = tswap64(st64->tx_packets);
2354         st64->rx_bytes = tswap64(st64->rx_bytes);
2355         st64->tx_bytes = tswap64(st64->tx_bytes);
2356         st64->rx_errors = tswap64(st64->rx_errors);
2357         st64->tx_errors = tswap64(st64->tx_errors);
2358         st64->rx_dropped = tswap64(st64->rx_dropped);
2359         st64->tx_dropped = tswap64(st64->tx_dropped);
2360         st64->multicast = tswap64(st64->multicast);
2361         st64->collisions = tswap64(st64->collisions);
2362
2363         /* detailed rx_errors: */
2364         st64->rx_length_errors = tswap64(st64->rx_length_errors);
2365         st64->rx_over_errors = tswap64(st64->rx_over_errors);
2366         st64->rx_crc_errors = tswap64(st64->rx_crc_errors);
2367         st64->rx_frame_errors = tswap64(st64->rx_frame_errors);
2368         st64->rx_fifo_errors = tswap64(st64->rx_fifo_errors);
2369         st64->rx_missed_errors = tswap64(st64->rx_missed_errors);
2370
2371         /* detailed tx_errors */
2372         st64->tx_aborted_errors = tswap64(st64->tx_aborted_errors);
2373         st64->tx_carrier_errors = tswap64(st64->tx_carrier_errors);
2374         st64->tx_fifo_errors = tswap64(st64->tx_fifo_errors);
2375         st64->tx_heartbeat_errors = tswap64(st64->tx_heartbeat_errors);
2376         st64->tx_window_errors = tswap64(st64->tx_window_errors);
2377
2378         /* for cslip etc */
2379         st64->rx_compressed = tswap64(st64->rx_compressed);
2380         st64->tx_compressed = tswap64(st64->tx_compressed);
2381         break;
2382     /* struct rtnl_link_ifmap */
2383     case QEMU_IFLA_MAP:
2384         map = RTA_DATA(rtattr);
2385         map->mem_start = tswap64(map->mem_start);
2386         map->mem_end = tswap64(map->mem_end);
2387         map->base_addr = tswap64(map->base_addr);
2388         map->irq = tswap16(map->irq);
2389         break;
2390     /* nested */
2391     case QEMU_IFLA_LINKINFO:
2392         memset(&li_context, 0, sizeof(li_context));
2393         return host_to_target_for_each_nlattr(RTA_DATA(rtattr), rtattr->rta_len,
2394                                               &li_context,
2395                                            host_to_target_data_linkinfo_nlattr);
2396     case QEMU_IFLA_AF_SPEC:
2397         return host_to_target_for_each_nlattr(RTA_DATA(rtattr), rtattr->rta_len,
2398                                               NULL,
2399                                              host_to_target_data_spec_nlattr);
2400     default:
2401         gemu_log("Unknown host QEMU_IFLA type: %d\n", rtattr->rta_type);
2402         break;
2403     }
2404     return 0;
2405 }
2406
2407 static abi_long host_to_target_data_addr_rtattr(struct rtattr *rtattr)
2408 {
2409     uint32_t *u32;
2410     struct ifa_cacheinfo *ci;
2411
2412     switch (rtattr->rta_type) {
2413     /* binary: depends on family type */
2414     case IFA_ADDRESS:
2415     case IFA_LOCAL:
2416         break;
2417     /* string */
2418     case IFA_LABEL:
2419         break;
2420     /* u32 */
2421     case IFA_FLAGS:
2422     case IFA_BROADCAST:
2423         u32 = RTA_DATA(rtattr);
2424         *u32 = tswap32(*u32);
2425         break;
2426     /* struct ifa_cacheinfo */
2427     case IFA_CACHEINFO:
2428         ci = RTA_DATA(rtattr);
2429         ci->ifa_prefered = tswap32(ci->ifa_prefered);
2430         ci->ifa_valid = tswap32(ci->ifa_valid);
2431         ci->cstamp = tswap32(ci->cstamp);
2432         ci->tstamp = tswap32(ci->tstamp);
2433         break;
2434     default:
2435         gemu_log("Unknown host IFA type: %d\n", rtattr->rta_type);
2436         break;
2437     }
2438     return 0;
2439 }
2440
2441 static abi_long host_to_target_data_route_rtattr(struct rtattr *rtattr)
2442 {
2443     uint32_t *u32;
2444     switch (rtattr->rta_type) {
2445     /* binary: depends on family type */
2446     case RTA_GATEWAY:
2447     case RTA_DST:
2448     case RTA_PREFSRC:
2449         break;
2450     /* u32 */
2451     case RTA_PRIORITY:
2452     case RTA_TABLE:
2453     case RTA_OIF:
2454         u32 = RTA_DATA(rtattr);
2455         *u32 = tswap32(*u32);
2456         break;
2457     default:
2458         gemu_log("Unknown host RTA type: %d\n", rtattr->rta_type);
2459         break;
2460     }
2461     return 0;
2462 }
2463
2464 static abi_long host_to_target_link_rtattr(struct rtattr *rtattr,
2465                                          uint32_t rtattr_len)
2466 {
2467     return host_to_target_for_each_rtattr(rtattr, rtattr_len,
2468                                           host_to_target_data_link_rtattr);
2469 }
2470
2471 static abi_long host_to_target_addr_rtattr(struct rtattr *rtattr,
2472                                          uint32_t rtattr_len)
2473 {
2474     return host_to_target_for_each_rtattr(rtattr, rtattr_len,
2475                                           host_to_target_data_addr_rtattr);
2476 }
2477
2478 static abi_long host_to_target_route_rtattr(struct rtattr *rtattr,
2479                                          uint32_t rtattr_len)
2480 {
2481     return host_to_target_for_each_rtattr(rtattr, rtattr_len,
2482                                           host_to_target_data_route_rtattr);
2483 }
2484
2485 static abi_long host_to_target_data_route(struct nlmsghdr *nlh)
2486 {
2487     uint32_t nlmsg_len;
2488     struct ifinfomsg *ifi;
2489     struct ifaddrmsg *ifa;
2490     struct rtmsg *rtm;
2491
2492     nlmsg_len = nlh->nlmsg_len;
2493     switch (nlh->nlmsg_type) {
2494     case RTM_NEWLINK:
2495     case RTM_DELLINK:
2496     case RTM_GETLINK:
2497         if (nlh->nlmsg_len >= NLMSG_LENGTH(sizeof(*ifi))) {
2498             ifi = NLMSG_DATA(nlh);
2499             ifi->ifi_type = tswap16(ifi->ifi_type);
2500             ifi->ifi_index = tswap32(ifi->ifi_index);
2501             ifi->ifi_flags = tswap32(ifi->ifi_flags);
2502             ifi->ifi_change = tswap32(ifi->ifi_change);
2503             host_to_target_link_rtattr(IFLA_RTA(ifi),
2504                                        nlmsg_len - NLMSG_LENGTH(sizeof(*ifi)));
2505         }
2506         break;
2507     case RTM_NEWADDR:
2508     case RTM_DELADDR:
2509     case RTM_GETADDR:
2510         if (nlh->nlmsg_len >= NLMSG_LENGTH(sizeof(*ifa))) {
2511             ifa = NLMSG_DATA(nlh);
2512             ifa->ifa_index = tswap32(ifa->ifa_index);
2513             host_to_target_addr_rtattr(IFA_RTA(ifa),
2514                                        nlmsg_len - NLMSG_LENGTH(sizeof(*ifa)));
2515         }
2516         break;
2517     case RTM_NEWROUTE:
2518     case RTM_DELROUTE:
2519     case RTM_GETROUTE:
2520         if (nlh->nlmsg_len >= NLMSG_LENGTH(sizeof(*rtm))) {
2521             rtm = NLMSG_DATA(nlh);
2522             rtm->rtm_flags = tswap32(rtm->rtm_flags);
2523             host_to_target_route_rtattr(RTM_RTA(rtm),
2524                                         nlmsg_len - NLMSG_LENGTH(sizeof(*rtm)));
2525         }
2526         break;
2527     default:
2528         return -TARGET_EINVAL;
2529     }
2530     return 0;
2531 }
2532
2533 static inline abi_long host_to_target_nlmsg_route(struct nlmsghdr *nlh,
2534                                                   size_t len)
2535 {
2536     return host_to_target_for_each_nlmsg(nlh, len, host_to_target_data_route);
2537 }
2538
2539 static abi_long target_to_host_for_each_rtattr(struct rtattr *rtattr,
2540                                                size_t len,
2541                                                abi_long (*target_to_host_rtattr)
2542                                                         (struct rtattr *))
2543 {
2544     abi_long ret;
2545
2546     while (len >= sizeof(struct rtattr)) {
2547         if (tswap16(rtattr->rta_len) < sizeof(struct rtattr) ||
2548             tswap16(rtattr->rta_len) > len) {
2549             break;
2550         }
2551         rtattr->rta_len = tswap16(rtattr->rta_len);
2552         rtattr->rta_type = tswap16(rtattr->rta_type);
2553         ret = target_to_host_rtattr(rtattr);
2554         if (ret < 0) {
2555             return ret;
2556         }
2557         len -= RTA_ALIGN(rtattr->rta_len);
2558         rtattr = (struct rtattr *)(((char *)rtattr) +
2559                  RTA_ALIGN(rtattr->rta_len));
2560     }
2561     return 0;
2562 }
2563
2564 static abi_long target_to_host_data_link_rtattr(struct rtattr *rtattr)
2565 {
2566     switch (rtattr->rta_type) {
2567     default:
2568         gemu_log("Unknown target QEMU_IFLA type: %d\n", rtattr->rta_type);
2569         break;
2570     }
2571     return 0;
2572 }
2573
2574 static abi_long target_to_host_data_addr_rtattr(struct rtattr *rtattr)
2575 {
2576     switch (rtattr->rta_type) {
2577     /* binary: depends on family type */
2578     case IFA_LOCAL:
2579     case IFA_ADDRESS:
2580         break;
2581     default:
2582         gemu_log("Unknown target IFA type: %d\n", rtattr->rta_type);
2583         break;
2584     }
2585     return 0;
2586 }
2587
2588 static abi_long target_to_host_data_route_rtattr(struct rtattr *rtattr)
2589 {
2590     uint32_t *u32;
2591     switch (rtattr->rta_type) {
2592     /* binary: depends on family type */
2593     case RTA_DST:
2594     case RTA_SRC:
2595     case RTA_GATEWAY:
2596         break;
2597     /* u32 */
2598     case RTA_OIF:
2599         u32 = RTA_DATA(rtattr);
2600         *u32 = tswap32(*u32);
2601         break;
2602     default:
2603         gemu_log("Unknown target RTA type: %d\n", rtattr->rta_type);
2604         break;
2605     }
2606     return 0;
2607 }
2608
2609 static void target_to_host_link_rtattr(struct rtattr *rtattr,
2610                                        uint32_t rtattr_len)
2611 {
2612     target_to_host_for_each_rtattr(rtattr, rtattr_len,
2613                                    target_to_host_data_link_rtattr);
2614 }
2615
2616 static void target_to_host_addr_rtattr(struct rtattr *rtattr,
2617                                      uint32_t rtattr_len)
2618 {
2619     target_to_host_for_each_rtattr(rtattr, rtattr_len,
2620                                    target_to_host_data_addr_rtattr);
2621 }
2622
2623 static void target_to_host_route_rtattr(struct rtattr *rtattr,
2624                                      uint32_t rtattr_len)
2625 {
2626     target_to_host_for_each_rtattr(rtattr, rtattr_len,
2627                                    target_to_host_data_route_rtattr);
2628 }
2629
2630 static abi_long target_to_host_data_route(struct nlmsghdr *nlh)
2631 {
2632     struct ifinfomsg *ifi;
2633     struct ifaddrmsg *ifa;
2634     struct rtmsg *rtm;
2635
2636     switch (nlh->nlmsg_type) {
2637     case RTM_GETLINK:
2638         break;
2639     case RTM_NEWLINK:
2640     case RTM_DELLINK:
2641         if (nlh->nlmsg_len >= NLMSG_LENGTH(sizeof(*ifi))) {
2642             ifi = NLMSG_DATA(nlh);
2643             ifi->ifi_type = tswap16(ifi->ifi_type);
2644             ifi->ifi_index = tswap32(ifi->ifi_index);
2645             ifi->ifi_flags = tswap32(ifi->ifi_flags);
2646             ifi->ifi_change = tswap32(ifi->ifi_change);
2647             target_to_host_link_rtattr(IFLA_RTA(ifi), nlh->nlmsg_len -
2648                                        NLMSG_LENGTH(sizeof(*ifi)));
2649         }
2650         break;
2651     case RTM_GETADDR:
2652     case RTM_NEWADDR:
2653     case RTM_DELADDR:
2654         if (nlh->nlmsg_len >= NLMSG_LENGTH(sizeof(*ifa))) {
2655             ifa = NLMSG_DATA(nlh);
2656             ifa->ifa_index = tswap32(ifa->ifa_index);
2657             target_to_host_addr_rtattr(IFA_RTA(ifa), nlh->nlmsg_len -
2658                                        NLMSG_LENGTH(sizeof(*ifa)));
2659         }
2660         break;
2661     case RTM_GETROUTE:
2662         break;
2663     case RTM_NEWROUTE:
2664     case RTM_DELROUTE:
2665         if (nlh->nlmsg_len >= NLMSG_LENGTH(sizeof(*rtm))) {
2666             rtm = NLMSG_DATA(nlh);
2667             rtm->rtm_flags = tswap32(rtm->rtm_flags);
2668             target_to_host_route_rtattr(RTM_RTA(rtm), nlh->nlmsg_len -
2669                                         NLMSG_LENGTH(sizeof(*rtm)));
2670         }
2671         break;
2672     default:
2673         return -TARGET_EOPNOTSUPP;
2674     }
2675     return 0;
2676 }
2677
2678 static abi_long target_to_host_nlmsg_route(struct nlmsghdr *nlh, size_t len)
2679 {
2680     return target_to_host_for_each_nlmsg(nlh, len, target_to_host_data_route);
2681 }
2682 #endif /* CONFIG_RTNETLINK */
2683
2684 static abi_long host_to_target_data_audit(struct nlmsghdr *nlh)
2685 {
2686     switch (nlh->nlmsg_type) {
2687     default:
2688         gemu_log("Unknown host audit message type %d\n",
2689                  nlh->nlmsg_type);
2690         return -TARGET_EINVAL;
2691     }
2692     return 0;
2693 }
2694
2695 static inline abi_long host_to_target_nlmsg_audit(struct nlmsghdr *nlh,
2696                                                   size_t len)
2697 {
2698     return host_to_target_for_each_nlmsg(nlh, len, host_to_target_data_audit);
2699 }
2700
2701 static abi_long target_to_host_data_audit(struct nlmsghdr *nlh)
2702 {
2703     switch (nlh->nlmsg_type) {
2704     case AUDIT_USER:
2705     case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
2706     case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
2707         break;
2708     default:
2709         gemu_log("Unknown target audit message type %d\n",
2710                  nlh->nlmsg_type);
2711         return -TARGET_EINVAL;
2712     }
2713
2714     return 0;
2715 }
2716
2717 static abi_long target_to_host_nlmsg_audit(struct nlmsghdr *nlh, size_t len)
2718 {
2719     return target_to_host_for_each_nlmsg(nlh, len, target_to_host_data_audit);
2720 }
2721
2722 /* do_setsockopt() Must return target values and target errnos. */
2723 static abi_long do_setsockopt(int sockfd, int level, int optname,
2724                               abi_ulong optval_addr, socklen_t optlen)
2725 {
2726     abi_long ret;
2727     int val;
2728     struct ip_mreqn *ip_mreq;
2729     struct ip_mreq_source *ip_mreq_source;
2730
2731     switch(level) {
2732     case SOL_TCP:
2733         /* TCP options all take an 'int' value.  */
2734         if (optlen < sizeof(uint32_t))
2735             return -TARGET_EINVAL;
2736
2737         if (get_user_u32(val, optval_addr))
2738             return -TARGET_EFAULT;
2739         ret = get_errno(setsockopt(sockfd, level, optname, &val, sizeof(val)));
2740         break;
2741     case SOL_IP:
2742         switch(optname) {
2743         case IP_TOS:
2744         case IP_TTL:
2745         case IP_HDRINCL:
2746         case IP_ROUTER_ALERT:
2747         case IP_RECVOPTS:
2748         case IP_RETOPTS:
2749         case IP_PKTINFO:
2750         case IP_MTU_DISCOVER:
2751         case IP_RECVERR:
2752         case IP_RECVTOS:
2753 #ifdef IP_FREEBIND
2754         case IP_FREEBIND:
2755 #endif
2756         case IP_MULTICAST_TTL:
2757         case IP_MULTICAST_LOOP:
2758             val = 0;
2759             if (optlen >= sizeof(uint32_t)) {
2760                 if (get_user_u32(val, optval_addr))
2761                     return -TARGET_EFAULT;
2762             } else if (optlen >= 1) {
2763                 if (get_user_u8(val, optval_addr))
2764                     return -TARGET_EFAULT;
2765             }
2766             ret = get_errno(setsockopt(sockfd, level, optname, &val, sizeof(val)));
2767             break;
2768         case IP_ADD_MEMBERSHIP:
2769         case IP_DROP_MEMBERSHIP:
2770             if (optlen < sizeof (struct target_ip_mreq) ||
2771                 optlen > sizeof (struct target_ip_mreqn))
2772                 return -TARGET_EINVAL;
2773
2774             ip_mreq = (struct ip_mreqn *) alloca(optlen);
2775             target_to_host_ip_mreq(ip_mreq, optval_addr, optlen);
2776             ret = get_errno(setsockopt(sockfd, level, optname, ip_mreq, optlen));
2777             break;
2778
2779         case IP_BLOCK_SOURCE:
2780         case IP_UNBLOCK_SOURCE:
2781         case IP_ADD_SOURCE_MEMBERSHIP:
2782         case IP_DROP_SOURCE_MEMBERSHIP:
2783             if (optlen != sizeof (struct target_ip_mreq_source))
2784                 return -TARGET_EINVAL;
2785
2786             ip_mreq_source = lock_user(VERIFY_READ, optval_addr, optlen, 1);
2787             ret = get_errno(setsockopt(sockfd, level, optname, ip_mreq_source, optlen));
2788             unlock_user (ip_mreq_source, optval_addr, 0);
2789             break;
2790
2791         default:
2792             goto unimplemented;
2793         }
2794         break;
2795     case SOL_IPV6:
2796         switch (optname) {
2797         case IPV6_MTU_DISCOVER:
2798         case IPV6_MTU:
2799         case IPV6_V6ONLY:
2800         case IPV6_RECVPKTINFO:
2801             val = 0;
2802             if (optlen < sizeof(uint32_t)) {
2803                 return -TARGET_EINVAL;
2804             }
2805             if (get_user_u32(val, optval_addr)) {
2806                 return -TARGET_EFAULT;
2807             }
2808             ret = get_errno(setsockopt(sockfd, level, optname,
2809                                        &val, sizeof(val)));
2810             break;
2811         default:
2812             goto unimplemented;
2813         }
2814         break;
2815     case SOL_RAW:
2816         switch (optname) {
2817         case ICMP_FILTER:
2818             /* struct icmp_filter takes an u32 value */
2819             if (optlen < sizeof(uint32_t)) {
2820                 return -TARGET_EINVAL;
2821             }
2822
2823             if (get_user_u32(val, optval_addr)) {
2824                 return -TARGET_EFAULT;
2825             }
2826             ret = get_errno(setsockopt(sockfd, level, optname,
2827                                        &val, sizeof(val)));
2828             break;
2829
2830         default:
2831             goto unimplemented;
2832         }
2833         break;
2834     case TARGET_SOL_SOCKET:
2835         switch (optname) {
2836         case TARGET_SO_RCVTIMEO:
2837         {
2838                 struct timeval tv;
2839
2840                 optname = SO_RCVTIMEO;
2841
2842 set_timeout:
2843                 if (optlen != sizeof(struct target_timeval)) {
2844                     return -TARGET_EINVAL;
2845                 }
2846
2847                 if (copy_from_user_timeval(&tv, optval_addr)) {
2848                     return -TARGET_EFAULT;
2849                 }
2850
2851                 ret = get_errno(setsockopt(sockfd, SOL_SOCKET, optname,
2852                                 &tv, sizeof(tv)));
2853                 return ret;
2854         }
2855         case TARGET_SO_SNDTIMEO:
2856                 optname = SO_SNDTIMEO;
2857                 goto set_timeout;
2858         case TARGET_SO_ATTACH_FILTER:
2859         {
2860                 struct target_sock_fprog *tfprog;
2861                 struct target_sock_filter *tfilter;
2862                 struct sock_fprog fprog;
2863                 struct sock_filter *filter;
2864                 int i;
2865
2866                 if (optlen != sizeof(*tfprog)) {
2867                     return -TARGET_EINVAL;
2868                 }
2869                 if (!lock_user_struct(VERIFY_READ, tfprog, optval_addr, 0)) {
2870                     return -TARGET_EFAULT;
2871                 }
2872                 if (!lock_user_struct(VERIFY_READ, tfilter,
2873                                       tswapal(tfprog->filter), 0)) {
2874                     unlock_user_struct(tfprog, optval_addr, 1);
2875                     return -TARGET_EFAULT;
2876                 }
2877
2878                 fprog.len = tswap16(tfprog->len);
2879                 filter = g_try_new(struct sock_filter, fprog.len);
2880                 if (filter == NULL) {
2881                     unlock_user_struct(tfilter, tfprog->filter, 1);
2882                     unlock_user_struct(tfprog, optval_addr, 1);
2883                     return -TARGET_ENOMEM;
2884                 }
2885                 for (i = 0; i < fprog.len; i++) {
2886                     filter[i].code = tswap16(tfilter[i].code);
2887                     filter[i].jt = tfilter[i].jt;
2888                     filter[i].jf = tfilter[i].jf;
2889                     filter[i].k = tswap32(tfilter[i].k);
2890                 }
2891                 fprog.filter = filter;
2892
2893                 ret = get_errno(setsockopt(sockfd, SOL_SOCKET,
2894                                 SO_ATTACH_FILTER, &fprog, sizeof(fprog)));
2895                 g_free(filter);
2896
2897                 unlock_user_struct(tfilter, tfprog->filter, 1);
2898                 unlock_user_struct(tfprog, optval_addr, 1);
2899                 return ret;
2900         }
2901         case TARGET_SO_BINDTODEVICE:
2902         {
2903                 char *dev_ifname, *addr_ifname;
2904
2905                 if (optlen > IFNAMSIZ - 1) {
2906                     optlen = IFNAMSIZ - 1;
2907                 }
2908                 dev_ifname = lock_user(VERIFY_READ, optval_addr, optlen, 1);
2909                 if (!dev_ifname) {
2910                     return -TARGET_EFAULT;
2911                 }
2912                 optname = SO_BINDTODEVICE;
2913                 addr_ifname = alloca(IFNAMSIZ);
2914                 memcpy(addr_ifname, dev_ifname, optlen);
2915                 addr_ifname[optlen] = 0;
2916                 ret = get_errno(setsockopt(sockfd, SOL_SOCKET, optname,
2917                                            addr_ifname, optlen));
2918                 unlock_user (dev_ifname, optval_addr, 0);
2919                 return ret;
2920         }
2921             /* Options with 'int' argument.  */
2922         case TARGET_SO_DEBUG:
2923                 optname = SO_DEBUG;
2924                 break;
2925         case TARGET_SO_REUSEADDR:
2926                 optname = SO_REUSEADDR;
2927                 break;
2928         case TARGET_SO_TYPE:
2929                 optname = SO_TYPE;
2930                 break;
2931         case TARGET_SO_ERROR:
2932                 optname = SO_ERROR;
2933                 break;
2934         case TARGET_SO_DONTROUTE:
2935                 optname = SO_DONTROUTE;
2936                 break;
2937         case TARGET_SO_BROADCAST:
2938                 optname = SO_BROADCAST;
2939                 break;
2940         case TARGET_SO_SNDBUF:
2941                 optname = SO_SNDBUF;
2942                 break;
2943         case TARGET_SO_SNDBUFFORCE:
2944                 optname = SO_SNDBUFFORCE;
2945                 break;
2946         case TARGET_SO_RCVBUF:
2947                 optname = SO_RCVBUF;
2948                 break;
2949         case TARGET_SO_RCVBUFFORCE:
2950                 optname = SO_RCVBUFFORCE;
2951                 break;
2952         case TARGET_SO_KEEPALIVE:
2953                 optname = SO_KEEPALIVE;
2954                 break;
2955         case TARGET_SO_OOBINLINE:
2956                 optname = SO_OOBINLINE;
2957                 break;
2958         case TARGET_SO_NO_CHECK:
2959                 optname = SO_NO_CHECK;
2960                 break;
2961         case TARGET_SO_PRIORITY:
2962                 optname = SO_PRIORITY;
2963                 break;
2964 #ifdef SO_BSDCOMPAT
2965         case TARGET_SO_BSDCOMPAT:
2966                 optname = SO_BSDCOMPAT;
2967                 break;
2968 #endif
2969         case TARGET_SO_PASSCRED:
2970                 optname = SO_PASSCRED;
2971                 break;
2972         case TARGET_SO_PASSSEC:
2973                 optname = SO_PASSSEC;
2974                 break;
2975         case TARGET_SO_TIMESTAMP:
2976                 optname = SO_TIMESTAMP;
2977                 break;
2978         case TARGET_SO_RCVLOWAT:
2979                 optname = SO_RCVLOWAT;
2980                 break;
2981             break;
2982         default:
2983             goto unimplemented;
2984         }
2985         if (optlen < sizeof(uint32_t))
2986             return -TARGET_EINVAL;
2987
2988         if (get_user_u32(val, optval_addr))
2989             return -TARGET_EFAULT;
2990         ret = get_errno(setsockopt(sockfd, SOL_SOCKET, optname, &val, sizeof(val)));
2991         break;
2992     default:
2993     unimplemented:
2994         gemu_log("Unsupported setsockopt level=%d optname=%d\n", level, optname);
2995         ret = -TARGET_ENOPROTOOPT;
2996     }
2997     return ret;
2998 }
2999
3000 /* do_getsockopt() Must return target values and target errnos. */
3001 static abi_long do_getsockopt(int sockfd, int level, int optname,
3002                               abi_ulong optval_addr, abi_ulong optlen)
3003 {
3004     abi_long ret;
3005     int len, val;
3006     socklen_t lv;
3007
3008     switch(level) {
3009     case TARGET_SOL_SOCKET:
3010         level = SOL_SOCKET;
3011         switch (optname) {
3012         /* These don't just return a single integer */
3013         case TARGET_SO_LINGER:
3014         case TARGET_SO_RCVTIMEO:
3015         case TARGET_SO_SNDTIMEO:
3016         case TARGET_SO_PEERNAME:
3017             goto unimplemented;
3018         case TARGET_SO_PEERCRED: {
3019             struct ucred cr;
3020             socklen_t crlen;
3021             struct target_ucred *tcr;
3022
3023             if (get_user_u32(len, optlen)) {
3024                 return -TARGET_EFAULT;
3025             }
3026             if (len < 0) {
3027                 return -TARGET_EINVAL;
3028             }
3029
3030             crlen = sizeof(cr);
3031             ret = get_errno(getsockopt(sockfd, level, SO_PEERCRED,
3032                                        &cr, &crlen));
3033             if (ret < 0) {
3034                 return ret;
3035             }
3036             if (len > crlen) {
3037                 len = crlen;
3038             }
3039             if (!lock_user_struct(VERIFY_WRITE, tcr, optval_addr, 0)) {
3040                 return -TARGET_EFAULT;
3041             }
3042             __put_user(cr.pid, &tcr->pid);
3043             __put_user(cr.uid, &tcr->uid);
3044             __put_user(cr.gid, &tcr->gid);
3045             unlock_user_struct(tcr, optval_addr, 1);
3046             if (put_user_u32(len, optlen)) {
3047                 return -TARGET_EFAULT;
3048             }
3049             break;
3050         }
3051         /* Options with 'int' argument.  */
3052         case TARGET_SO_DEBUG:
3053             optname = SO_DEBUG;
3054             goto int_case;
3055         case TARGET_SO_REUSEADDR:
3056             optname = SO_REUSEADDR;
3057             goto int_case;
3058         case TARGET_SO_TYPE:
3059             optname = SO_TYPE;
3060             goto int_case;
3061         case TARGET_SO_ERROR:
3062             optname = SO_ERROR;
3063             goto int_case;
3064         case TARGET_SO_DONTROUTE:
3065             optname = SO_DONTROUTE;
3066             goto int_case;
3067         case TARGET_SO_BROADCAST:
3068             optname = SO_BROADCAST;
3069             goto int_case;
3070         case TARGET_SO_SNDBUF:
3071             optname = SO_SNDBUF;
3072             goto int_case;
3073         case TARGET_SO_RCVBUF:
3074             optname = SO_RCVBUF;
3075             goto int_case;
3076         case TARGET_SO_KEEPALIVE:
3077             optname = SO_KEEPALIVE;
3078             goto int_case;
3079         case TARGET_SO_OOBINLINE:
3080             optname = SO_OOBINLINE;
3081             goto int_case;
3082         case TARGET_SO_NO_CHECK:
3083             optname = SO_NO_CHECK;
3084             goto int_case;
3085         case TARGET_SO_PRIORITY:
3086             optname = SO_PRIORITY;
3087             goto int_case;
3088 #ifdef SO_BSDCOMPAT
3089         case TARGET_SO_BSDCOMPAT:
3090             optname = SO_BSDCOMPAT;
3091             goto int_case;
3092 #endif
3093         case TARGET_SO_PASSCRED:
3094             optname = SO_PASSCRED;
3095             goto int_case;
3096         case TARGET_SO_TIMESTAMP:
3097             optname = SO_TIMESTAMP;
3098             goto int_case;
3099         case TARGET_SO_RCVLOWAT:
3100             optname = SO_RCVLOWAT;
3101             goto int_case;
3102         case TARGET_SO_ACCEPTCONN:
3103             optname = SO_ACCEPTCONN;
3104             goto int_case;
3105         default:
3106             goto int_case;
3107         }
3108         break;
3109     case SOL_TCP:
3110         /* TCP options all take an 'int' value.  */
3111     int_case:
3112         if (get_user_u32(len, optlen))
3113             return -TARGET_EFAULT;
3114         if (len < 0)
3115             return -TARGET_EINVAL;
3116         lv = sizeof(lv);
3117         ret = get_errno(getsockopt(sockfd, level, optname, &val, &lv));
3118         if (ret < 0)
3119             return ret;
3120         if (optname == SO_TYPE) {
3121             val = host_to_target_sock_type(val);
3122         }
3123         if (len > lv)
3124             len = lv;
3125         if (len == 4) {
3126             if (put_user_u32(val, optval_addr))
3127                 return -TARGET_EFAULT;
3128         } else {
3129             if (put_user_u8(val, optval_addr))
3130                 return -TARGET_EFAULT;
3131         }
3132         if (put_user_u32(len, optlen))
3133             return -TARGET_EFAULT;
3134         break;
3135     case SOL_IP:
3136         switch(optname) {
3137         case IP_TOS:
3138         case IP_TTL:
3139         case IP_HDRINCL:
3140         case IP_ROUTER_ALERT:
3141         case IP_RECVOPTS:
3142         case IP_RETOPTS:
3143         case IP_PKTINFO:
3144         case IP_MTU_DISCOVER:
3145         case IP_RECVERR:
3146         case IP_RECVTOS:
3147 #ifdef IP_FREEBIND
3148         case IP_FREEBIND:
3149 #endif
3150         case IP_MULTICAST_TTL:
3151         case IP_MULTICAST_LOOP:
3152             if (get_user_u32(len, optlen))
3153                 return -TARGET_EFAULT;
3154             if (len < 0)
3155                 return -TARGET_EINVAL;
3156             lv = sizeof(lv);
3157             ret = get_errno(getsockopt(sockfd, level, optname, &val, &lv));
3158             if (ret < 0)
3159                 return ret;
3160             if (len < sizeof(int) && len > 0 && val >= 0 && val < 255) {
3161                 len = 1;
3162                 if (put_user_u32(len, optlen)
3163                     || put_user_u8(val, optval_addr))
3164                     return -TARGET_EFAULT;
3165             } else {
3166                 if (len > sizeof(int))
3167                     len = sizeof(int);
3168                 if (put_user_u32(len, optlen)
3169                     || put_user_u32(val, optval_addr))
3170                     return -TARGET_EFAULT;
3171             }
3172             break;
3173         default:
3174             ret = -TARGET_ENOPROTOOPT;
3175             break;
3176         }
3177         break;
3178     default:
3179     unimplemented:
3180         gemu_log("getsockopt level=%d optname=%d not yet supported\n",
3181                  level, optname);
3182         ret = -TARGET_EOPNOTSUPP;
3183         break;
3184     }
3185     return ret;
3186 }
3187
3188 static struct iovec *lock_iovec(int type, abi_ulong target_addr,
3189                                 abi_ulong count, int copy)
3190 {
3191     struct target_iovec *target_vec;
3192     struct iovec *vec;
3193     abi_ulong total_len, max_len;
3194     int i;
3195     int err = 0;
3196     bool bad_address = false;
3197
3198     if (count == 0) {
3199         errno = 0;
3200         return NULL;
3201     }
3202     if (count > IOV_MAX) {
3203         errno = EINVAL;
3204         return NULL;
3205     }
3206
3207     vec = g_try_new0(struct iovec, count);
3208     if (vec == NULL) {
3209         errno = ENOMEM;
3210         return NULL;
3211     }
3212
3213     target_vec = lock_user(VERIFY_READ, target_addr,
3214                            count * sizeof(struct target_iovec), 1);
3215     if (target_vec == NULL) {
3216         err = EFAULT;
3217         goto fail2;
3218     }
3219
3220     /* ??? If host page size > target page size, this will result in a
3221        value larger than what we can actually support.  */
3222     max_len = 0x7fffffff & TARGET_PAGE_MASK;
3223     total_len = 0;
3224
3225     for (i = 0; i < count; i++) {
3226         abi_ulong base = tswapal(target_vec[i].iov_base);
3227         abi_long len = tswapal(target_vec[i].iov_len);
3228
3229         if (len < 0) {
3230             err = EINVAL;
3231             goto fail;
3232         } else if (len == 0) {
3233             /* Zero length pointer is ignored.  */
3234             vec[i].iov_base = 0;
3235         } else {
3236             vec[i].iov_base = lock_user(type, base, len, copy);
3237             /* If the first buffer pointer is bad, this is a fault.  But
3238              * subsequent bad buffers will result in a partial write; this
3239              * is realized by filling the vector with null pointers and
3240              * zero lengths. */
3241             if (!vec[i].iov_base) {
3242                 if (i == 0) {
3243                     err = EFAULT;
3244                     goto fail;
3245                 } else {
3246                     bad_address = true;
3247                 }
3248             }
3249             if (bad_address) {
3250                 len = 0;
3251             }
3252             if (len > max_len - total_len) {
3253                 len = max_len - total_len;
3254             }
3255         }
3256         vec[i].iov_len = len;
3257         total_len += len;
3258     }
3259
3260     unlock_user(target_vec, target_addr, 0);
3261     return vec;
3262
3263  fail:
3264     while (--i >= 0) {
3265         if (tswapal(target_vec[i].iov_len) > 0) {
3266             unlock_user(vec[i].iov_base, tswapal(target_vec[i].iov_base), 0);
3267         }
3268     }
3269     unlock_user(target_vec, target_addr, 0);
3270  fail2:
3271     g_free(vec);
3272     errno = err;
3273     return NULL;
3274 }
3275
3276 static void unlock_iovec(struct iovec *vec, abi_ulong target_addr,
3277                          abi_ulong count, int copy)
3278 {
3279     struct target_iovec *target_vec;
3280     int i;
3281
3282     target_vec = lock_user(VERIFY_READ, target_addr,
3283                            count * sizeof(struct target_iovec), 1);
3284     if (target_vec) {
3285         for (i = 0; i < count; i++) {
3286             abi_ulong base = tswapal(target_vec[i].iov_base);
3287             abi_long len = tswapal(target_vec[i].iov_len);
3288             if (len < 0) {
3289                 break;
3290             }
3291             unlock_user(vec[i].iov_base, base, copy ? vec[i].iov_len : 0);
3292         }
3293         unlock_user(target_vec, target_addr, 0);
3294     }
3295
3296     g_free(vec);
3297 }
3298
3299 static inline int target_to_host_sock_type(int *type)
3300 {
3301     int host_type = 0;
3302     int target_type = *type;
3303
3304     switch (target_type & TARGET_SOCK_TYPE_MASK) {
3305     case TARGET_SOCK_DGRAM:
3306         host_type = SOCK_DGRAM;
3307         break;
3308     case TARGET_SOCK_STREAM:
3309         host_type = SOCK_STREAM;
3310         break;
3311     default:
3312         host_type = target_type & TARGET_SOCK_TYPE_MASK;
3313         break;
3314     }
3315     if (target_type & TARGET_SOCK_CLOEXEC) {
3316 #if defined(SOCK_CLOEXEC)
3317         host_type |= SOCK_CLOEXEC;
3318 #else
3319         return -TARGET_EINVAL;
3320 #endif
3321     }
3322     if (target_type & TARGET_SOCK_NONBLOCK) {
3323 #if defined(SOCK_NONBLOCK)
3324         host_type |= SOCK_NONBLOCK;
3325 #elif !defined(O_NONBLOCK)
3326         return -TARGET_EINVAL;
3327 #endif
3328     }
3329     *type = host_type;
3330     return 0;
3331 }
3332
3333 /* Try to emulate socket type flags after socket creation.  */
3334 static int sock_flags_fixup(int fd, int target_type)
3335 {
3336 #if !defined(SOCK_NONBLOCK) && defined(O_NONBLOCK)
3337     if (target_type & TARGET_SOCK_NONBLOCK) {
3338         int flags = fcntl(fd, F_GETFL);
3339         if (fcntl(fd, F_SETFL, O_NONBLOCK | flags) == -1) {
3340             close(fd);
3341             return -TARGET_EINVAL;
3342         }
3343     }
3344 #endif
3345     return fd;
3346 }
3347
3348 static abi_long packet_target_to_host_sockaddr(void *host_addr,
3349                                                abi_ulong target_addr,
3350                                                socklen_t len)
3351 {
3352     struct sockaddr *addr = host_addr;
3353     struct target_sockaddr *target_saddr;
3354
3355     target_saddr = lock_user(VERIFY_READ, target_addr, len, 1);
3356     if (!target_saddr) {
3357         return -TARGET_EFAULT;
3358     }
3359
3360     memcpy(addr, target_saddr, len);
3361     addr->sa_family = tswap16(target_saddr->sa_family);
3362     /* spkt_protocol is big-endian */
3363
3364     unlock_user(target_saddr, target_addr, 0);
3365     return 0;
3366 }
3367
3368 static TargetFdTrans target_packet_trans = {
3369     .target_to_host_addr = packet_target_to_host_sockaddr,
3370 };
3371
3372 #ifdef CONFIG_RTNETLINK
3373 static abi_long netlink_route_target_to_host(void *buf, size_t len)
3374 {
3375     abi_long ret;
3376
3377     ret = target_to_host_nlmsg_route(buf, len);
3378     if (ret < 0) {
3379         return ret;
3380     }
3381
3382     return len;
3383 }
3384
3385 static abi_long netlink_route_host_to_target(void *buf, size_t len)
3386 {
3387     abi_long ret;
3388
3389     ret = host_to_target_nlmsg_route(buf, len);
3390     if (ret < 0) {
3391         return ret;
3392     }
3393
3394     return len;
3395 }
3396
3397 static TargetFdTrans target_netlink_route_trans = {
3398     .target_to_host_data = netlink_route_target_to_host,
3399     .host_to_target_data = netlink_route_host_to_target,
3400 };
3401 #endif /* CONFIG_RTNETLINK */
3402
3403 static abi_long netlink_audit_target_to_host(void *buf, size_t len)
3404 {
3405     abi_long ret;
3406
3407     ret = target_to_host_nlmsg_audit(buf, len);
3408     if (ret < 0) {
3409         return ret;
3410     }
3411
3412     return len;
3413 }
3414
3415 static abi_long netlink_audit_host_to_target(void *buf, size_t len)
3416 {
3417     abi_long ret;
3418
3419     ret = host_to_target_nlmsg_audit(buf, len);
3420     if (ret < 0) {
3421         return ret;
3422     }
3423
3424     return len;
3425 }
3426
3427 static TargetFdTrans target_netlink_audit_trans = {
3428     .target_to_host_data = netlink_audit_target_to_host,
3429     .host_to_target_data = netlink_audit_host_to_target,
3430 };
3431
3432 /* do_socket() Must return target values and target errnos. */
3433 static abi_long do_socket(int domain, int type, int protocol)
3434 {
3435     int target_type = type;
3436     int ret;
3437
3438     ret = target_to_host_sock_type(&type);
3439     if (ret) {
3440         return ret;
3441     }
3442
3443     if (domain == PF_NETLINK && !(
3444 #ifdef CONFIG_RTNETLINK
3445          protocol == NETLINK_ROUTE ||
3446 #endif
3447          protocol == NETLINK_KOBJECT_UEVENT ||
3448          protocol == NETLINK_AUDIT)) {
3449         return -EPFNOSUPPORT;
3450     }
3451
3452     if (domain == AF_PACKET ||
3453         (domain == AF_INET && type == SOCK_PACKET)) {
3454         protocol = tswap16(protocol);
3455     }
3456
3457     ret = get_errno(socket(domain, type, protocol));
3458     if (ret >= 0) {
3459         ret = sock_flags_fixup(ret, target_type);
3460         if (type == SOCK_PACKET) {
3461             /* Manage an obsolete case :
3462              * if socket type is SOCK_PACKET, bind by name
3463              */
3464             fd_trans_register(ret, &target_packet_trans);
3465         } else if (domain == PF_NETLINK) {
3466             switch (protocol) {
3467 #ifdef CONFIG_RTNETLINK
3468             case NETLINK_ROUTE:
3469                 fd_trans_register(ret, &target_netlink_route_trans);
3470                 break;
3471 #endif
3472             case NETLINK_KOBJECT_UEVENT:
3473                 /* nothing to do: messages are strings */
3474                 break;
3475             case NETLINK_AUDIT:
3476                 fd_trans_register(ret, &target_netlink_audit_trans);
3477                 break;
3478             default:
3479                 g_assert_not_reached();
3480             }
3481         }
3482     }
3483     return ret;
3484 }
3485
3486 /* do_bind() Must return target values and target errnos. */
3487 static abi_long do_bind(int sockfd, abi_ulong target_addr,
3488                         socklen_t addrlen)
3489 {
3490     void *addr;
3491     abi_long ret;
3492
3493     if ((int)addrlen < 0) {
3494         return -TARGET_EINVAL;
3495     }
3496
3497     addr = alloca(addrlen+1);
3498
3499     ret = target_to_host_sockaddr(sockfd, addr, target_addr, addrlen);
3500     if (ret)
3501         return ret;
3502
3503     return get_errno(bind(sockfd, addr, addrlen));
3504 }
3505
3506 /* do_connect() Must return target values and target errnos. */
3507 static abi_long do_connect(int sockfd, abi_ulong target_addr,
3508                            socklen_t addrlen)
3509 {
3510     void *addr;
3511     abi_long ret;
3512
3513     if ((int)addrlen < 0) {
3514         return -TARGET_EINVAL;
3515     }
3516
3517     addr = alloca(addrlen+1);
3518
3519     ret = target_to_host_sockaddr(sockfd, addr, target_addr, addrlen);
3520     if (ret)
3521         return ret;
3522
3523     return get_errno(safe_connect(sockfd, addr, addrlen));
3524 }
3525
3526 /* do_sendrecvmsg_locked() Must return target values and target errnos. */
3527 static abi_long do_sendrecvmsg_locked(int fd, struct target_msghdr *msgp,
3528                                       int flags, int send)
3529 {
3530     abi_long ret, len;
3531     struct msghdr msg;
3532     abi_ulong count;
3533     struct iovec *vec;
3534     abi_ulong target_vec;
3535
3536     if (msgp->msg_name) {
3537         msg.msg_namelen = tswap32(msgp->msg_namelen);
3538         msg.msg_name = alloca(msg.msg_namelen+1);
3539         ret = target_to_host_sockaddr(fd, msg.msg_name,
3540                                       tswapal(msgp->msg_name),
3541                                       msg.msg_namelen);
3542         if (ret == -TARGET_EFAULT) {
3543             /* For connected sockets msg_name and msg_namelen must
3544              * be ignored, so returning EFAULT immediately is wrong.
3545              * Instead, pass a bad msg_name to the host kernel, and
3546              * let it decide whether to return EFAULT or not.
3547              */
3548             msg.msg_name = (void *)-1;
3549         } else if (ret) {
3550             goto out2;
3551         }
3552     } else {
3553         msg.msg_name = NULL;
3554         msg.msg_namelen = 0;
3555     }
3556     msg.msg_controllen = 2 * tswapal(msgp->msg_controllen);
3557     msg.msg_control = alloca(msg.msg_controllen);
3558     msg.msg_flags = tswap32(msgp->msg_flags);
3559
3560     count = tswapal(msgp->msg_iovlen);
3561     target_vec = tswapal(msgp->msg_iov);
3562
3563     if (count > IOV_MAX) {
3564         /* sendrcvmsg returns a different errno for this condition than
3565          * readv/writev, so we must catch it here before lock_iovec() does.
3566          */
3567         ret = -TARGET_EMSGSIZE;
3568         goto out2;
3569     }
3570
3571     vec = lock_iovec(send ? VERIFY_READ : VERIFY_WRITE,
3572                      target_vec, count, send);
3573     if (vec == NULL) {
3574         ret = -host_to_target_errno(errno);
3575         goto out2;
3576     }
3577     msg.msg_iovlen = count;
3578     msg.msg_iov = vec;
3579
3580     if (send) {
3581         if (fd_trans_target_to_host_data(fd)) {
3582             void *host_msg;
3583
3584             host_msg = g_malloc(msg.msg_iov->iov_len);
3585             memcpy(host_msg, msg.msg_iov->iov_base, msg.msg_iov->iov_len);
3586             ret = fd_trans_target_to_host_data(fd)(host_msg,
3587                                                    msg.msg_iov->iov_len);
3588             if (ret >= 0) {
3589                 msg.msg_iov->iov_base = host_msg;
3590                 ret = get_errno(safe_sendmsg(fd, &msg, flags));
3591             }
3592             g_free(host_msg);
3593         } else {
3594             ret = target_to_host_cmsg(&msg, msgp);
3595             if (ret == 0) {
3596                 ret = get_errno(safe_sendmsg(fd, &msg, flags));
3597             }
3598         }
3599     } else {
3600         ret = get_errno(safe_recvmsg(fd, &msg, flags));
3601         if (!is_error(ret)) {
3602             len = ret;
3603             if (fd_trans_host_to_target_data(fd)) {
3604                 ret = fd_trans_host_to_target_data(fd)(msg.msg_iov->iov_base,
3605                                                        len);
3606             } else {
3607                 ret = host_to_target_cmsg(msgp, &msg);
3608             }
3609             if (!is_error(ret)) {
3610                 msgp->msg_namelen = tswap32(msg.msg_namelen);
3611                 if (msg.msg_name != NULL && msg.msg_name != (void *)-1) {
3612                     ret = host_to_target_sockaddr(tswapal(msgp->msg_name),
3613                                     msg.msg_name, msg.msg_namelen);
3614                     if (ret) {
3615                         goto out;
3616                     }
3617                 }
3618
3619                 ret = len;
3620             }
3621         }
3622     }
3623
3624 out:
3625     unlock_iovec(vec, target_vec, count, !send);
3626 out2:
3627     return ret;
3628 }
3629
3630 static abi_long do_sendrecvmsg(int fd, abi_ulong target_msg,
3631                                int flags, int send)
3632 {
3633     abi_long ret;
3634     struct target_msghdr *msgp;
3635
3636     if (!lock_user_struct(send ? VERIFY_READ : VERIFY_WRITE,
3637                           msgp,
3638                           target_msg,
3639                           send ? 1 : 0)) {
3640         return -TARGET_EFAULT;
3641     }
3642     ret = do_sendrecvmsg_locked(fd, msgp, flags, send);
3643     unlock_user_struct(msgp, target_msg, send ? 0 : 1);
3644     return ret;
3645 }
3646
3647 /* We don't rely on the C library to have sendmmsg/recvmmsg support,
3648  * so it might not have this *mmsg-specific flag either.
3649  */
3650 #ifndef MSG_WAITFORONE
3651 #define MSG_WAITFORONE 0x10000
3652 #endif
3653
3654 static abi_long do_sendrecvmmsg(int fd, abi_ulong target_msgvec,
3655                                 unsigned int vlen, unsigned int flags,
3656                                 int send)
3657 {
3658     struct target_mmsghdr *mmsgp;
3659     abi_long ret = 0;
3660     int i;
3661
3662     if (vlen > UIO_MAXIOV) {
3663         vlen = UIO_MAXIOV;
3664     }
3665
3666     mmsgp = lock_user(VERIFY_WRITE, target_msgvec, sizeof(*mmsgp) * vlen, 1);
3667     if (!mmsgp) {
3668         return -TARGET_EFAULT;
3669     }
3670
3671     for (i = 0; i < vlen; i++) {
3672         ret = do_sendrecvmsg_locked(fd, &mmsgp[i].msg_hdr, flags, send);
3673         if (is_error(ret)) {
3674             break;
3675         }
3676         mmsgp[i].msg_len = tswap32(ret);
3677         /* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */
3678         if (flags & MSG_WAITFORONE) {
3679             flags |= MSG_DONTWAIT;
3680         }
3681     }
3682
3683     unlock_user(mmsgp, target_msgvec, sizeof(*mmsgp) * i);
3684
3685     /* Return number of datagrams sent if we sent any at all;
3686      * otherwise return the error.
3687      */
3688     if (i) {
3689         return i;
3690     }
3691     return ret;
3692 }
3693
3694 /* do_accept4() Must return target values and target errnos. */
3695 static abi_long do_accept4(int fd, abi_ulong target_addr,
3696                            abi_ulong target_addrlen_addr, int flags)
3697 {
3698     socklen_t addrlen;
3699     void *addr;
3700     abi_long ret;
3701     int host_flags;
3702
3703     host_flags = target_to_host_bitmask(flags, fcntl_flags_tbl);
3704
3705     if (target_addr == 0) {
3706         return get_errno(safe_accept4(fd, NULL, NULL, host_flags));
3707     }
3708
3709     /* linux returns EINVAL if addrlen pointer is invalid */
3710     if (get_user_u32(addrlen, target_addrlen_addr))
3711         return -TARGET_EINVAL;
3712
3713     if ((int)addrlen < 0) {
3714         return -TARGET_EINVAL;
3715     }
3716
3717     if (!access_ok(VERIFY_WRITE, target_addr, addrlen))
3718         return -TARGET_EINVAL;
3719
3720     addr = alloca(addrlen);
3721
3722     ret = get_errno(safe_accept4(fd, addr, &addrlen, host_flags));
3723     if (!is_error(ret)) {
3724         host_to_target_sockaddr(target_addr, addr, addrlen);
3725         if (put_user_u32(addrlen, target_addrlen_addr))
3726             ret = -TARGET_EFAULT;
3727     }
3728     return ret;
3729 }
3730
3731 /* do_getpeername() Must return target values and target errnos. */
3732 static abi_long do_getpeername(int fd, abi_ulong target_addr,
3733                                abi_ulong target_addrlen_addr)
3734 {
3735     socklen_t addrlen;
3736     void *addr;
3737     abi_long ret;
3738
3739     if (get_user_u32(addrlen, target_addrlen_addr))
3740         return -TARGET_EFAULT;
3741
3742     if ((int)addrlen < 0) {
3743         return -TARGET_EINVAL;
3744     }
3745
3746     if (!access_ok(VERIFY_WRITE, target_addr, addrlen))
3747         return -TARGET_EFAULT;
3748
3749     addr = alloca(addrlen);
3750
3751     ret = get_errno(getpeername(fd, addr, &addrlen));
3752     if (!is_error(ret)) {
3753         host_to_target_sockaddr(target_addr, addr, addrlen);
3754         if (put_user_u32(addrlen, target_addrlen_addr))
3755             ret = -TARGET_EFAULT;
3756     }
3757     return ret;
3758 }
3759
3760 /* do_getsockname() Must return target values and target errnos. */
3761 static abi_long do_getsockname(int fd, abi_ulong target_addr,
3762                                abi_ulong target_addrlen_addr)
3763 {
3764     socklen_t addrlen;
3765     void *addr;
3766     abi_long ret;
3767
3768     if (get_user_u32(addrlen, target_addrlen_addr))
3769         return -TARGET_EFAULT;
3770
3771     if ((int)addrlen < 0) {
3772         return -TARGET_EINVAL;
3773     }
3774
3775     if (!access_ok(VERIFY_WRITE, target_addr, addrlen))
3776         return -TARGET_EFAULT;
3777
3778     addr = alloca(addrlen);
3779
3780     ret = get_errno(getsockname(fd, addr, &addrlen));
3781     if (!is_error(ret)) {
3782         host_to_target_sockaddr(target_addr, addr, addrlen);
3783         if (put_user_u32(addrlen, target_addrlen_addr))
3784             ret = -TARGET_EFAULT;
3785     }
3786     return ret;
3787 }
3788
3789 /* do_socketpair() Must return target values and target errnos. */
3790 static abi_long do_socketpair(int domain, int type, int protocol,
3791                               abi_ulong target_tab_addr)
3792 {
3793     int tab[2];
3794     abi_long ret;
3795
3796     target_to_host_sock_type(&type);
3797
3798     ret = get_errno(socketpair(domain, type, protocol, tab));
3799     if (!is_error(ret)) {
3800         if (put_user_s32(tab[0], target_tab_addr)
3801             || put_user_s32(tab[1], target_tab_addr + sizeof(tab[0])))
3802             ret = -TARGET_EFAULT;
3803     }
3804     return ret;
3805 }
3806
3807 /* do_sendto() Must return target values and target errnos. */
3808 static abi_long do_sendto(int fd, abi_ulong msg, size_t len, int flags,
3809                           abi_ulong target_addr, socklen_t addrlen)
3810 {
3811     void *addr;
3812     void *host_msg;
3813     void *copy_msg = NULL;
3814     abi_long ret;
3815
3816     if ((int)addrlen < 0) {
3817         return -TARGET_EINVAL;
3818     }
3819
3820     host_msg = lock_user(VERIFY_READ, msg, len, 1);
3821     if (!host_msg)
3822         return -TARGET_EFAULT;
3823     if (fd_trans_target_to_host_data(fd)) {
3824         copy_msg = host_msg;
3825         host_msg = g_malloc(len);
3826         memcpy(host_msg, copy_msg, len);
3827         ret = fd_trans_target_to_host_data(fd)(host_msg, len);
3828         if (ret < 0) {
3829             goto fail;
3830         }
3831     }
3832     if (target_addr) {
3833         addr = alloca(addrlen+1);
3834         ret = target_to_host_sockaddr(fd, addr, target_addr, addrlen);
3835         if (ret) {
3836             goto fail;
3837         }
3838         ret = get_errno(safe_sendto(fd, host_msg, len, flags, addr, addrlen));
3839     } else {
3840         ret = get_errno(safe_sendto(fd, host_msg, len, flags, NULL, 0));
3841     }
3842 fail:
3843     if (copy_msg) {
3844         g_free(host_msg);
3845         host_msg = copy_msg;
3846     }
3847     unlock_user(host_msg, msg, 0);
3848     return ret;
3849 }
3850
3851 /* do_recvfrom() Must return target values and target errnos. */
3852 static abi_long do_recvfrom(int fd, abi_ulong msg, size_t len, int flags,
3853                             abi_ulong target_addr,
3854                             abi_ulong target_addrlen)
3855 {
3856     socklen_t addrlen;
3857     void *addr;
3858     void *host_msg;
3859     abi_long ret;
3860
3861     host_msg = lock_user(VERIFY_WRITE, msg, len, 0);
3862     if (!host_msg)
3863         return -TARGET_EFAULT;
3864     if (target_addr) {
3865         if (get_user_u32(addrlen, target_addrlen)) {
3866             ret = -TARGET_EFAULT;
3867             goto fail;
3868         }
3869         if ((int)addrlen < 0) {
3870             ret = -TARGET_EINVAL;
3871             goto fail;
3872         }
3873         addr = alloca(addrlen);
3874         ret = get_errno(safe_recvfrom(fd, host_msg, len, flags,
3875                                       addr, &addrlen));
3876     } else {
3877         addr = NULL; /* To keep compiler quiet.  */
3878         ret = get_errno(safe_recvfrom(fd, host_msg, len, flags, NULL, 0));
3879     }
3880     if (!is_error(ret)) {
3881         if (fd_trans_host_to_target_data(fd)) {
3882             ret = fd_trans_host_to_target_data(fd)(host_msg, ret);
3883         }
3884         if (target_addr) {
3885             host_to_target_sockaddr(target_addr, addr, addrlen);
3886             if (put_user_u32(addrlen, target_addrlen)) {
3887                 ret = -TARGET_EFAULT;
3888                 goto fail;
3889             }
3890         }
3891         unlock_user(host_msg, msg, len);
3892     } else {
3893 fail:
3894         unlock_user(host_msg, msg, 0);
3895     }
3896     return ret;
3897 }
3898
3899 #ifdef TARGET_NR_socketcall
3900 /* do_socketcall() must return target values and target errnos. */
3901 static abi_long do_socketcall(int num, abi_ulong vptr)
3902 {
3903     static const unsigned nargs[] = { /* number of arguments per operation */
3904         [TARGET_SYS_SOCKET] = 3,      /* domain, type, protocol */
3905         [TARGET_SYS_BIND] = 3,        /* fd, addr, addrlen */
3906         [TARGET_SYS_CONNECT] = 3,     /* fd, addr, addrlen */
3907         [TARGET_SYS_LISTEN] = 2,      /* fd, backlog */
3908         [TARGET_SYS_ACCEPT] = 3,      /* fd, addr, addrlen */
3909         [TARGET_SYS_GETSOCKNAME] = 3, /* fd, addr, addrlen */
3910         [TARGET_SYS_GETPEERNAME] = 3, /* fd, addr, addrlen */
3911         [TARGET_SYS_SOCKETPAIR] = 4,  /* domain, type, protocol, tab */
3912         [TARGET_SYS_SEND] = 4,        /* fd, msg, len, flags */
3913         [TARGET_SYS_RECV] = 4,        /* fd, msg, len, flags */
3914         [TARGET_SYS_SENDTO] = 6,      /* fd, msg, len, flags, addr, addrlen */
3915         [TARGET_SYS_RECVFROM] = 6,    /* fd, msg, len, flags, addr, addrlen */
3916         [TARGET_SYS_SHUTDOWN] = 2,    /* fd, how */
3917         [TARGET_SYS_SETSOCKOPT] = 5,  /* fd, level, optname, optval, optlen */
3918         [TARGET_SYS_GETSOCKOPT] = 5,  /* fd, level, optname, optval, optlen */
3919         [TARGET_SYS_SENDMSG] = 3,     /* fd, msg, flags */
3920         [TARGET_SYS_RECVMSG] = 3,     /* fd, msg, flags */
3921         [TARGET_SYS_ACCEPT4] = 4,     /* fd, addr, addrlen, flags */
3922         [TARGET_SYS_RECVMMSG] = 4,    /* fd, msgvec, vlen, flags */
3923         [TARGET_SYS_SENDMMSG] = 4,    /* fd, msgvec, vlen, flags */
3924     };
3925     abi_long a[6]; /* max 6 args */
3926     unsigned i;
3927
3928     /* check the range of the first argument num */
3929     /* (TARGET_SYS_SENDMMSG is the highest among TARGET_SYS_xxx) */
3930     if (num < 1 || num > TARGET_SYS_SENDMMSG) {
3931         return -TARGET_EINVAL;
3932     }
3933     /* ensure we have space for args */
3934     if (nargs[num] > ARRAY_SIZE(a)) {
3935         return -TARGET_EINVAL;
3936     }
3937     /* collect the arguments in a[] according to nargs[] */
3938     for (i = 0; i < nargs[num]; ++i) {
3939         if (get_user_ual(a[i], vptr + i * sizeof(abi_long)) != 0) {
3940             return -TARGET_EFAULT;
3941         }
3942     }
3943     /* now when we have the args, invoke the appropriate underlying function */
3944     switch (num) {
3945     case TARGET_SYS_SOCKET: /* domain, type, protocol */
3946         return do_socket(a[0], a[1], a[2]);
3947     case TARGET_SYS_BIND: /* sockfd, addr, addrlen */
3948         return do_bind(a[0], a[1], a[2]);
3949     case TARGET_SYS_CONNECT: /* sockfd, addr, addrlen */
3950         return do_connect(a[0], a[1], a[2]);
3951     case TARGET_SYS_LISTEN: /* sockfd, backlog */
3952         return get_errno(listen(a[0], a[1]));
3953     case TARGET_SYS_ACCEPT: /* sockfd, addr, addrlen */
3954         return do_accept4(a[0], a[1], a[2], 0);
3955     case TARGET_SYS_GETSOCKNAME: /* sockfd, addr, addrlen */
3956         return do_getsockname(a[0], a[1], a[2]);
3957     case TARGET_SYS_GETPEERNAME: /* sockfd, addr, addrlen */
3958         return do_getpeername(a[0], a[1], a[2]);
3959     case TARGET_SYS_SOCKETPAIR: /* domain, type, protocol, tab */
3960         return do_socketpair(a[0], a[1], a[2], a[3]);
3961     case TARGET_SYS_SEND: /* sockfd, msg, len, flags */
3962         return do_sendto(a[0], a[1], a[2], a[3], 0, 0);
3963     case TARGET_SYS_RECV: /* sockfd, msg, len, flags */
3964         return do_recvfrom(a[0], a[1], a[2], a[3], 0, 0);
3965     case TARGET_SYS_SENDTO: /* sockfd, msg, len, flags, addr, addrlen */
3966         return do_sendto(a[0], a[1], a[2], a[3], a[4], a[5]);
3967     case TARGET_SYS_RECVFROM: /* sockfd, msg, len, flags, addr, addrlen */
3968         return do_recvfrom(a[0], a[1], a[2], a[3], a[4], a[5]);
3969     case TARGET_SYS_SHUTDOWN: /* sockfd, how */
3970         return get_errno(shutdown(a[0], a[1]));
3971     case TARGET_SYS_SETSOCKOPT: /* sockfd, level, optname, optval, optlen */
3972         return do_setsockopt(a[0], a[1], a[2], a[3], a[4]);
3973     case TARGET_SYS_GETSOCKOPT: /* sockfd, level, optname, optval, optlen */
3974         return do_getsockopt(a[0], a[1], a[2], a[3], a[4]);
3975     case TARGET_SYS_SENDMSG: /* sockfd, msg, flags */
3976         return do_sendrecvmsg(a[0], a[1], a[2], 1);
3977     case TARGET_SYS_RECVMSG: /* sockfd, msg, flags */
3978         return do_sendrecvmsg(a[0], a[1], a[2], 0);
3979     case TARGET_SYS_ACCEPT4: /* sockfd, addr, addrlen, flags */
3980         return do_accept4(a[0], a[1], a[2], a[3]);
3981     case TARGET_SYS_RECVMMSG: /* sockfd, msgvec, vlen, flags */
3982         return do_sendrecvmmsg(a[0], a[1], a[2], a[3], 0);
3983     case TARGET_SYS_SENDMMSG: /* sockfd, msgvec, vlen, flags */
3984         return do_sendrecvmmsg(a[0], a[1], a[2], a[3], 1);
3985     default:
3986         gemu_log("Unsupported socketcall: %d\n", num);
3987         return -TARGET_EINVAL;
3988     }
3989 }
3990 #endif
3991
3992 #define N_SHM_REGIONS   32
3993
3994 static struct shm_region {
3995     abi_ulong start;
3996     abi_ulong size;
3997     bool in_use;
3998 } shm_regions[N_SHM_REGIONS];
3999
4000 #ifndef TARGET_SEMID64_DS
4001 /* asm-generic version of this struct */
4002 struct target_semid64_ds
4003 {
4004   struct target_ipc_perm sem_perm;
4005   abi_ulong sem_otime;
4006 #if TARGET_ABI_BITS == 32
4007   abi_ulong __unused1;
4008 #endif
4009   abi_ulong sem_ctime;
4010 #if TARGET_ABI_BITS == 32
4011   abi_ulong __unused2;
4012 #endif
4013   abi_ulong sem_nsems;
4014   abi_ulong __unused3;
4015   abi_ulong __unused4;
4016 };
4017 #endif
4018
4019 static inline abi_long target_to_host_ipc_perm(struct ipc_perm *host_ip,
4020                                                abi_ulong target_addr)
4021 {
4022     struct target_ipc_perm *target_ip;
4023     struct target_semid64_ds *target_sd;
4024
4025     if (!lock_user_struct(VERIFY_READ, target_sd, target_addr, 1))
4026         return -TARGET_EFAULT;
4027     target_ip = &(target_sd->sem_perm);
4028     host_ip->__key = tswap32(target_ip->__key);
4029     host_ip->uid = tswap32(target_ip->uid);
4030     host_ip->gid = tswap32(target_ip->gid);
4031     host_ip->cuid = tswap32(target_ip->cuid);
4032     host_ip->cgid = tswap32(target_ip->cgid);
4033 #if defined(TARGET_ALPHA) || defined(TARGET_MIPS) || defined(TARGET_PPC)
4034     host_ip->mode = tswap32(target_ip->mode);
4035 #else
4036     host_ip->mode = tswap16(target_ip->mode);
4037 #endif
4038 #if defined(TARGET_PPC)
4039     host_ip->__seq = tswap32(target_ip->__seq);
4040 #else
4041     host_ip->__seq = tswap16(target_ip->__seq);
4042 #endif
4043     unlock_user_struct(target_sd, target_addr, 0);
4044     return 0;
4045 }
4046
4047 static inline abi_long host_to_target_ipc_perm(abi_ulong target_addr,
4048                                                struct ipc_perm *host_ip)
4049 {
4050     struct target_ipc_perm *target_ip;
4051     struct target_semid64_ds *target_sd;
4052
4053     if (!lock_user_struct(VERIFY_WRITE, target_sd, target_addr, 0))
4054         return -TARGET_EFAULT;
4055     target_ip = &(target_sd->sem_perm);
4056     target_ip->__key = tswap32(host_ip->__key);
4057     target_ip->uid = tswap32(host_ip->uid);
4058     target_ip->gid = tswap32(host_ip->gid);
4059     target_ip->cuid = tswap32(host_ip->cuid);
4060     target_ip->cgid = tswap32(host_ip->cgid);
4061 #if defined(TARGET_ALPHA) || defined(TARGET_MIPS) || defined(TARGET_PPC)
4062     target_ip->mode = tswap32(host_ip->mode);
4063 #else
4064     target_ip->mode = tswap16(host_ip->mode);
4065 #endif
4066 #if defined(TARGET_PPC)
4067     target_ip->__seq = tswap32(host_ip->__seq);
4068 #else
4069     target_ip->__seq = tswap16(host_ip->__seq);
4070 #endif
4071     unlock_user_struct(target_sd, target_addr, 1);
4072     return 0;
4073 }
4074
4075 static inline abi_long target_to_host_semid_ds(struct semid_ds *host_sd,
4076                                                abi_ulong target_addr)
4077 {
4078     struct target_semid64_ds *target_sd;
4079
4080     if (!lock_user_struct(VERIFY_READ, target_sd, target_addr, 1))
4081         return -TARGET_EFAULT;
4082     if (target_to_host_ipc_perm(&(host_sd->sem_perm),target_addr))
4083         return -TARGET_EFAULT;
4084     host_sd->sem_nsems = tswapal(target_sd->sem_nsems);
4085     host_sd->sem_otime = tswapal(target_sd->sem_otime);
4086     host_sd->sem_ctime = tswapal(target_sd->sem_ctime);
4087     unlock_user_struct(target_sd, target_addr, 0);
4088     return 0;
4089 }
4090
4091 static inline abi_long host_to_target_semid_ds(abi_ulong target_addr,
4092                                                struct semid_ds *host_sd)
4093 {
4094     struct target_semid64_ds *target_sd;
4095
4096     if (!lock_user_struct(VERIFY_WRITE, target_sd, target_addr, 0))
4097         return -TARGET_EFAULT;
4098     if (host_to_target_ipc_perm(target_addr,&(host_sd->sem_perm)))
4099         return -TARGET_EFAULT;
4100     target_sd->sem_nsems = tswapal(host_sd->sem_nsems);
4101     target_sd->sem_otime = tswapal(host_sd->sem_otime);
4102     target_sd->sem_ctime = tswapal(host_sd->sem_ctime);
4103     unlock_user_struct(target_sd, target_addr, 1);
4104     return 0;
4105 }
4106
4107 struct target_seminfo {
4108     int semmap;
4109     int semmni;
4110     int semmns;
4111     int semmnu;
4112     int semmsl;
4113     int semopm;
4114     int semume;
4115     int semusz;
4116     int semvmx;
4117     int semaem;
4118 };
4119
4120 static inline abi_long host_to_target_seminfo(abi_ulong target_addr,
4121                                               struct seminfo *host_seminfo)
4122 {
4123     struct target_seminfo *target_seminfo;
4124     if (!lock_user_struct(VERIFY_WRITE, target_seminfo, target_addr, 0))
4125         return -TARGET_EFAULT;
4126     __put_user(host_seminfo->semmap, &target_seminfo->semmap);
4127     __put_user(host_seminfo->semmni, &target_seminfo->semmni);
4128     __put_user(host_seminfo->semmns, &target_seminfo->semmns);
4129     __put_user(host_seminfo->semmnu, &target_seminfo->semmnu);
4130     __put_user(host_seminfo->semmsl, &target_seminfo->semmsl);
4131     __put_user(host_seminfo->semopm, &target_seminfo->semopm);
4132     __put_user(host_seminfo->semume, &target_seminfo->semume);
4133     __put_user(host_seminfo->semusz, &target_seminfo->semusz);
4134     __put_user(host_seminfo->semvmx, &target_seminfo->semvmx);
4135     __put_user(host_seminfo->semaem, &target_seminfo->semaem);
4136     unlock_user_struct(target_seminfo, target_addr, 1);
4137     return 0;
4138 }
4139
4140 union semun {
4141         int val;
4142         struct semid_ds *buf;
4143         unsigned short *array;
4144         struct seminfo *__buf;
4145 };
4146
4147 union target_semun {
4148         int val;
4149         abi_ulong buf;
4150         abi_ulong array;
4151         abi_ulong __buf;
4152 };
4153
4154 static inline abi_long target_to_host_semarray(int semid, unsigned short **host_array,
4155                                                abi_ulong target_addr)
4156 {
4157     int nsems;
4158     unsigned short *array;
4159     union semun semun;
4160     struct semid_ds semid_ds;
4161     int i, ret;
4162
4163     semun.buf = &semid_ds;
4164
4165     ret = semctl(semid, 0, IPC_STAT, semun);
4166     if (ret == -1)
4167         return get_errno(ret);
4168
4169     nsems = semid_ds.sem_nsems;
4170
4171     *host_array = g_try_new(unsigned short, nsems);
4172     if (!*host_array) {
4173         return -TARGET_ENOMEM;
4174     }
4175     array = lock_user(VERIFY_READ, target_addr,
4176                       nsems*sizeof(unsigned short), 1);
4177     if (!array) {
4178         g_free(*host_array);
4179         return -TARGET_EFAULT;
4180     }
4181
4182     for(i=0; i<nsems; i++) {
4183         __get_user((*host_array)[i], &array[i]);
4184     }
4185     unlock_user(array, target_addr, 0);
4186
4187     return 0;
4188 }
4189
4190 static inline abi_long host_to_target_semarray(int semid, abi_ulong target_addr,
4191                                                unsigned short **host_array)
4192 {
4193     int nsems;
4194     unsigned short *array;
4195     union semun semun;
4196     struct semid_ds semid_ds;
4197     int i, ret;
4198
4199     semun.buf = &semid_ds;
4200
4201     ret = semctl(semid, 0, IPC_STAT, semun);
4202     if (ret == -1)
4203         return get_errno(ret);
4204
4205     nsems = semid_ds.sem_nsems;
4206
4207     array = lock_user(VERIFY_WRITE, target_addr,
4208                       nsems*sizeof(unsigned short), 0);
4209     if (!array)
4210         return -TARGET_EFAULT;
4211
4212     for(i=0; i<nsems; i++) {
4213         __put_user((*host_array)[i], &array[i]);
4214     }
4215     g_free(*host_array);
4216     unlock_user(array, target_addr, 1);
4217
4218     return 0;
4219 }
4220
4221 static inline abi_long do_semctl(int semid, int semnum, int cmd,
4222                                  abi_ulong target_arg)
4223 {
4224     union target_semun target_su = { .buf = target_arg };
4225     union semun arg;
4226     struct semid_ds dsarg;
4227     unsigned short *array = NULL;
4228     struct seminfo seminfo;
4229     abi_long ret = -TARGET_EINVAL;
4230     abi_long err;
4231     cmd &= 0xff;
4232
4233     switch( cmd ) {
4234         case GETVAL:
4235         case SETVAL:
4236             /* In 64 bit cross-endian situations, we will erroneously pick up
4237              * the wrong half of the union for the "val" element.  To rectify
4238              * this, the entire 8-byte structure is byteswapped, followed by
4239              * a swap of the 4 byte val field. In other cases, the data is
4240              * already in proper host byte order. */
4241             if (sizeof(target_su.val) != (sizeof(target_su.buf))) {
4242                 target_su.buf = tswapal(target_su.buf);
4243                 arg.val = tswap32(target_su.val);
4244             } else {
4245                 arg.val = target_su.val;
4246             }
4247             ret = get_errno(semctl(semid, semnum, cmd, arg));
4248             break;
4249         case GETALL:
4250         case SETALL:
4251             err = target_to_host_semarray(semid, &array, target_su.array);
4252             if (err)
4253                 return err;
4254             arg.array = array;
4255             ret = get_errno(semctl(semid, semnum, cmd, arg));
4256             err = host_to_target_semarray(semid, target_su.array, &array);
4257             if (err)
4258                 return err;
4259             break;
4260         case IPC_STAT:
4261         case IPC_SET:
4262         case SEM_STAT:
4263             err = target_to_host_semid_ds(&dsarg, target_su.buf);
4264             if (err)
4265                 return err;
4266             arg.buf = &dsarg;
4267             ret = get_errno(semctl(semid, semnum, cmd, arg));
4268             err = host_to_target_semid_ds(target_su.buf, &dsarg);
4269             if (err)
4270                 return err;
4271             break;
4272         case IPC_INFO:
4273         case SEM_INFO:
4274             arg.__buf = &seminfo;
4275             ret = get_errno(semctl(semid, semnum, cmd, arg));
4276             err = host_to_target_seminfo(target_su.__buf, &seminfo);
4277             if (err)
4278                 return err;
4279             break;
4280         case IPC_RMID:
4281         case GETPID:
4282         case GETNCNT:
4283         case GETZCNT:
4284             ret = get_errno(semctl(semid, semnum, cmd, NULL));
4285             break;
4286     }
4287
4288     return ret;
4289 }
4290
4291 struct target_sembuf {
4292     unsigned short sem_num;
4293     short sem_op;
4294     short sem_flg;
4295 };
4296
4297 static inline abi_long target_to_host_sembuf(struct sembuf *host_sembuf,
4298                                              abi_ulong target_addr,
4299                                              unsigned nsops)
4300 {
4301     struct target_sembuf *target_sembuf;
4302     int i;
4303
4304     target_sembuf = lock_user(VERIFY_READ, target_addr,
4305                               nsops*sizeof(struct target_sembuf), 1);
4306     if (!target_sembuf)
4307         return -TARGET_EFAULT;
4308
4309     for(i=0; i<nsops; i++) {
4310         __get_user(host_sembuf[i].sem_num, &target_sembuf[i].sem_num);
4311         __get_user(host_sembuf[i].sem_op, &target_sembuf[i].sem_op);
4312         __get_user(host_sembuf[i].sem_flg, &target_sembuf[i].sem_flg);
4313     }
4314
4315     unlock_user(target_sembuf, target_addr, 0);
4316
4317     return 0;
4318 }
4319
4320 static inline abi_long do_semop(int semid, abi_long ptr, unsigned nsops)
4321 {
4322     struct sembuf sops[nsops];
4323
4324     if (target_to_host_sembuf(sops, ptr, nsops))
4325         return -TARGET_EFAULT;
4326
4327     return get_errno(safe_semtimedop(semid, sops, nsops, NULL));
4328 }
4329
4330 struct target_msqid_ds
4331 {
4332     struct target_ipc_perm msg_perm;
4333     abi_ulong msg_stime;
4334 #if TARGET_ABI_BITS == 32
4335     abi_ulong __unused1;
4336 #endif
4337     abi_ulong msg_rtime;
4338 #if TARGET_ABI_BITS == 32
4339     abi_ulong __unused2;
4340 #endif
4341     abi_ulong msg_ctime;
4342 #if TARGET_ABI_BITS == 32
4343     abi_ulong __unused3;
4344 #endif
4345     abi_ulong __msg_cbytes;
4346     abi_ulong msg_qnum;
4347     abi_ulong msg_qbytes;
4348     abi_ulong msg_lspid;
4349     abi_ulong msg_lrpid;
4350     abi_ulong __unused4;
4351     abi_ulong __unused5;
4352 };
4353
4354 static inline abi_long target_to_host_msqid_ds(struct msqid_ds *host_md,
4355                                                abi_ulong target_addr)
4356 {
4357     struct target_msqid_ds *target_md;
4358
4359     if (!lock_user_struct(VERIFY_READ, target_md, target_addr, 1))
4360         return -TARGET_EFAULT;
4361     if (target_to_host_ipc_perm(&(host_md->msg_perm),target_addr))
4362         return -TARGET_EFAULT;
4363     host_md->msg_stime = tswapal(target_md->msg_stime);
4364     host_md->msg_rtime = tswapal(target_md->msg_rtime);
4365     host_md->msg_ctime = tswapal(target_md->msg_ctime);
4366     host_md->__msg_cbytes = tswapal(target_md->__msg_cbytes);
4367     host_md->msg_qnum = tswapal(target_md->msg_qnum);
4368     host_md->msg_qbytes = tswapal(target_md->msg_qbytes);
4369     host_md->msg_lspid = tswapal(target_md->msg_lspid);
4370     host_md->msg_lrpid = tswapal(target_md->msg_lrpid);
4371     unlock_user_struct(target_md, target_addr, 0);
4372     return 0;
4373 }
4374
4375 static inline abi_long host_to_target_msqid_ds(abi_ulong target_addr,
4376                                                struct msqid_ds *host_md)
4377 {
4378     struct target_msqid_ds *target_md;
4379
4380     if (!lock_user_struct(VERIFY_WRITE, target_md, target_addr, 0))
4381         return -TARGET_EFAULT;
4382     if (host_to_target_ipc_perm(target_addr,&(host_md->msg_perm)))
4383         return -TARGET_EFAULT;
4384     target_md->msg_stime = tswapal(host_md->msg_stime);
4385     target_md->msg_rtime = tswapal(host_md->msg_rtime);
4386     target_md->msg_ctime = tswapal(host_md->msg_ctime);
4387     target_md->__msg_cbytes = tswapal(host_md->__msg_cbytes);
4388     target_md->msg_qnum = tswapal(host_md->msg_qnum);
4389     target_md->msg_qbytes = tswapal(host_md->msg_qbytes);
4390     target_md->msg_lspid = tswapal(host_md->msg_lspid);
4391     target_md->msg_lrpid = tswapal(host_md->msg_lrpid);
4392     unlock_user_struct(target_md, target_addr, 1);
4393     return 0;
4394 }
4395
4396 struct target_msginfo {
4397     int msgpool;
4398     int msgmap;
4399     int msgmax;
4400     int msgmnb;
4401     int msgmni;
4402     int msgssz;
4403     int msgtql;
4404     unsigned short int msgseg;
4405 };
4406
4407 static inline abi_long host_to_target_msginfo(abi_ulong target_addr,
4408                                               struct msginfo *host_msginfo)
4409 {
4410     struct target_msginfo *target_msginfo;
4411     if (!lock_user_struct(VERIFY_WRITE, target_msginfo, target_addr, 0))
4412         return -TARGET_EFAULT;
4413     __put_user(host_msginfo->msgpool, &target_msginfo->msgpool);
4414     __put_user(host_msginfo->msgmap, &target_msginfo->msgmap);
4415     __put_user(host_msginfo->msgmax, &target_msginfo->msgmax);
4416     __put_user(host_msginfo->msgmnb, &target_msginfo->msgmnb);
4417     __put_user(host_msginfo->msgmni, &target_msginfo->msgmni);
4418     __put_user(host_msginfo->msgssz, &target_msginfo->msgssz);
4419     __put_user(host_msginfo->msgtql, &target_msginfo->msgtql);
4420     __put_user(host_msginfo->msgseg, &target_msginfo->msgseg);
4421     unlock_user_struct(target_msginfo, target_addr, 1);
4422     return 0;
4423 }
4424
4425 static inline abi_long do_msgctl(int msgid, int cmd, abi_long ptr)
4426 {
4427     struct msqid_ds dsarg;
4428     struct msginfo msginfo;
4429     abi_long ret = -TARGET_EINVAL;
4430
4431     cmd &= 0xff;
4432
4433     switch (cmd) {
4434     case IPC_STAT:
4435     case IPC_SET:
4436     case MSG_STAT:
4437         if (target_to_host_msqid_ds(&dsarg,ptr))
4438             return -TARGET_EFAULT;
4439         ret = get_errno(msgctl(msgid, cmd, &dsarg));
4440         if (host_to_target_msqid_ds(ptr,&dsarg))
4441             return -TARGET_EFAULT;
4442         break;
4443     case IPC_RMID:
4444         ret = get_errno(msgctl(msgid, cmd, NULL));
4445         break;
4446     case IPC_INFO:
4447     case MSG_INFO:
4448         ret = get_errno(msgctl(msgid, cmd, (struct msqid_ds *)&msginfo));
4449         if (host_to_target_msginfo(ptr, &msginfo))
4450             return -TARGET_EFAULT;
4451         break;
4452     }
4453
4454     return ret;
4455 }
4456
4457 struct target_msgbuf {
4458     abi_long mtype;
4459     char        mtext[1];
4460 };
4461
4462 static inline abi_long do_msgsnd(int msqid, abi_long msgp,
4463                                  ssize_t msgsz, int msgflg)
4464 {
4465     struct target_msgbuf *target_mb;
4466     struct msgbuf *host_mb;
4467     abi_long ret = 0;
4468
4469     if (msgsz < 0) {
4470         return -TARGET_EINVAL;
4471     }
4472
4473     if (!lock_user_struct(VERIFY_READ, target_mb, msgp, 0))
4474         return -TARGET_EFAULT;
4475     host_mb = g_try_malloc(msgsz + sizeof(long));
4476     if (!host_mb) {
4477         unlock_user_struct(target_mb, msgp, 0);
4478         return -TARGET_ENOMEM;
4479     }
4480     host_mb->mtype = (abi_long) tswapal(target_mb->mtype);
4481     memcpy(host_mb->mtext, target_mb->mtext, msgsz);
4482     ret = get_errno(safe_msgsnd(msqid, host_mb, msgsz, msgflg));
4483     g_free(host_mb);
4484     unlock_user_struct(target_mb, msgp, 0);
4485
4486     return ret;
4487 }
4488
4489 static inline abi_long do_msgrcv(int msqid, abi_long msgp,
4490                                  ssize_t msgsz, abi_long msgtyp,
4491                                  int msgflg)
4492 {
4493     struct target_msgbuf *target_mb;
4494     char *target_mtext;
4495     struct msgbuf *host_mb;
4496     abi_long ret = 0;
4497
4498     if (msgsz < 0) {
4499         return -TARGET_EINVAL;
4500     }
4501
4502     if (!lock_user_struct(VERIFY_WRITE, target_mb, msgp, 0))
4503         return -TARGET_EFAULT;
4504
4505     host_mb = g_try_malloc(msgsz + sizeof(long));
4506     if (!host_mb) {
4507         ret = -TARGET_ENOMEM;
4508         goto end;
4509     }
4510     ret = get_errno(safe_msgrcv(msqid, host_mb, msgsz, msgtyp, msgflg));
4511
4512     if (ret > 0) {
4513         abi_ulong target_mtext_addr = msgp + sizeof(abi_ulong);
4514         target_mtext = lock_user(VERIFY_WRITE, target_mtext_addr, ret, 0);
4515         if (!target_mtext) {
4516             ret = -TARGET_EFAULT;
4517             goto end;
4518         }
4519         memcpy(target_mb->mtext, host_mb->mtext, ret);
4520         unlock_user(target_mtext, target_mtext_addr, ret);
4521     }
4522
4523     target_mb->mtype = tswapal(host_mb->mtype);
4524
4525 end:
4526     if (target_mb)
4527         unlock_user_struct(target_mb, msgp, 1);
4528     g_free(host_mb);
4529     return ret;
4530 }
4531
4532 static inline abi_long target_to_host_shmid_ds(struct shmid_ds *host_sd,
4533                                                abi_ulong target_addr)
4534 {
4535     struct target_shmid_ds *target_sd;
4536
4537     if (!lock_user_struct(VERIFY_READ, target_sd, target_addr, 1))
4538         return -TARGET_EFAULT;
4539     if (target_to_host_ipc_perm(&(host_sd->shm_perm), target_addr))
4540         return -TARGET_EFAULT;
4541     __get_user(host_sd->shm_segsz, &target_sd->shm_segsz);
4542     __get_user(host_sd->shm_atime, &target_sd->shm_atime);
4543     __get_user(host_sd->shm_dtime, &target_sd->shm_dtime);
4544     __get_user(host_sd->shm_ctime, &target_sd->shm_ctime);
4545     __get_user(host_sd->shm_cpid, &target_sd->shm_cpid);
4546     __get_user(host_sd->shm_lpid, &target_sd->shm_lpid);
4547     __get_user(host_sd->shm_nattch, &target_sd->shm_nattch);
4548     unlock_user_struct(target_sd, target_addr, 0);
4549     return 0;
4550 }
4551
4552 static inline abi_long host_to_target_shmid_ds(abi_ulong target_addr,
4553                                                struct shmid_ds *host_sd)
4554 {
4555     struct target_shmid_ds *target_sd;
4556
4557     if (!lock_user_struct(VERIFY_WRITE, target_sd, target_addr, 0))
4558         return -TARGET_EFAULT;
4559     if (host_to_target_ipc_perm(target_addr, &(host_sd->shm_perm)))
4560         return -TARGET_EFAULT;
4561     __put_user(host_sd->shm_segsz, &target_sd->shm_segsz);
4562     __put_user(host_sd->shm_atime, &target_sd->shm_atime);
4563     __put_user(host_sd->shm_dtime, &target_sd->shm_dtime);
4564     __put_user(host_sd->shm_ctime, &target_sd->shm_ctime);
4565     __put_user(host_sd->shm_cpid, &target_sd->shm_cpid);
4566     __put_user(host_sd->shm_lpid, &target_sd->shm_lpid);
4567     __put_user(host_sd->shm_nattch, &target_sd->shm_nattch);
4568     unlock_user_struct(target_sd, target_addr, 1);
4569     return 0;
4570 }
4571
4572 struct  target_shminfo {
4573     abi_ulong shmmax;
4574     abi_ulong shmmin;
4575     abi_ulong shmmni;
4576     abi_ulong shmseg;
4577     abi_ulong shmall;
4578 };
4579
4580 static inline abi_long host_to_target_shminfo(abi_ulong target_addr,
4581                                               struct shminfo *host_shminfo)
4582 {
4583     struct target_shminfo *target_shminfo;
4584     if (!lock_user_struct(VERIFY_WRITE, target_shminfo, target_addr, 0))
4585         return -TARGET_EFAULT;
4586     __put_user(host_shminfo->shmmax, &target_shminfo->shmmax);
4587     __put_user(host_shminfo->shmmin, &target_shminfo->shmmin);
4588     __put_user(host_shminfo->shmmni, &target_shminfo->shmmni);
4589     __put_user(host_shminfo->shmseg, &target_shminfo->shmseg);
4590     __put_user(host_shminfo->shmall, &target_shminfo->shmall);
4591     unlock_user_struct(target_shminfo, target_addr, 1);
4592     return 0;
4593 }
4594
4595 struct target_shm_info {
4596     int used_ids;
4597     abi_ulong shm_tot;
4598     abi_ulong shm_rss;
4599     abi_ulong shm_swp;
4600     abi_ulong swap_attempts;
4601     abi_ulong swap_successes;
4602 };
4603
4604 static inline abi_long host_to_target_shm_info(abi_ulong target_addr,
4605                                                struct shm_info *host_shm_info)
4606 {
4607     struct target_shm_info *target_shm_info;
4608     if (!lock_user_struct(VERIFY_WRITE, target_shm_info, target_addr, 0))
4609         return -TARGET_EFAULT;
4610     __put_user(host_shm_info->used_ids, &target_shm_info->used_ids);
4611     __put_user(host_shm_info->shm_tot, &target_shm_info->shm_tot);
4612     __put_user(host_shm_info->shm_rss, &target_shm_info->shm_rss);
4613     __put_user(host_shm_info->shm_swp, &target_shm_info->shm_swp);
4614     __put_user(host_shm_info->swap_attempts, &target_shm_info->swap_attempts);
4615     __put_user(host_shm_info->swap_successes, &target_shm_info->swap_successes);
4616     unlock_user_struct(target_shm_info, target_addr, 1);
4617     return 0;
4618 }
4619
4620 static inline abi_long do_shmctl(int shmid, int cmd, abi_long buf)
4621 {
4622     struct shmid_ds dsarg;
4623     struct shminfo shminfo;
4624     struct shm_info shm_info;
4625     abi_long ret = -TARGET_EINVAL;
4626
4627     cmd &= 0xff;
4628
4629     switch(cmd) {
4630     case IPC_STAT:
4631     case IPC_SET:
4632     case SHM_STAT:
4633         if (target_to_host_shmid_ds(&dsarg, buf))
4634             return -TARGET_EFAULT;
4635         ret = get_errno(shmctl(shmid, cmd, &dsarg));
4636         if (host_to_target_shmid_ds(buf, &dsarg))
4637             return -TARGET_EFAULT;
4638         break;
4639     case IPC_INFO:
4640         ret = get_errno(shmctl(shmid, cmd, (struct shmid_ds *)&shminfo));
4641         if (host_to_target_shminfo(buf, &shminfo))
4642             return -TARGET_EFAULT;
4643         break;
4644     case SHM_INFO:
4645         ret = get_errno(shmctl(shmid, cmd, (struct shmid_ds *)&shm_info));
4646         if (host_to_target_shm_info(buf, &shm_info))
4647             return -TARGET_EFAULT;
4648         break;
4649     case IPC_RMID:
4650     case SHM_LOCK:
4651     case SHM_UNLOCK:
4652         ret = get_errno(shmctl(shmid, cmd, NULL));
4653         break;
4654     }
4655
4656     return ret;
4657 }
4658
4659 #ifndef TARGET_FORCE_SHMLBA
4660 /* For most architectures, SHMLBA is the same as the page size;
4661  * some architectures have larger values, in which case they should
4662  * define TARGET_FORCE_SHMLBA and provide a target_shmlba() function.
4663  * This corresponds to the kernel arch code defining __ARCH_FORCE_SHMLBA
4664  * and defining its own value for SHMLBA.
4665  *
4666  * The kernel also permits SHMLBA to be set by the architecture to a
4667  * value larger than the page size without setting __ARCH_FORCE_SHMLBA;
4668  * this means that addresses are rounded to the large size if
4669  * SHM_RND is set but addresses not aligned to that size are not rejected
4670  * as long as they are at least page-aligned. Since the only architecture
4671  * which uses this is ia64 this code doesn't provide for that oddity.
4672  */
4673 static inline abi_ulong target_shmlba(CPUArchState *cpu_env)
4674 {
4675     return TARGET_PAGE_SIZE;
4676 }
4677 #endif
4678
4679 static inline abi_ulong do_shmat(CPUArchState *cpu_env,
4680                                  int shmid, abi_ulong shmaddr, int shmflg)
4681 {
4682     abi_long raddr;
4683     void *host_raddr;
4684     struct shmid_ds shm_info;
4685     int i,ret;
4686     abi_ulong shmlba;
4687
4688     /* find out the length of the shared memory segment */
4689     ret = get_errno(shmctl(shmid, IPC_STAT, &shm_info));
4690     if (is_error(ret)) {
4691         /* can't get length, bail out */
4692         return ret;
4693     }
4694
4695     shmlba = target_shmlba(cpu_env);
4696
4697     if (shmaddr & (shmlba - 1)) {
4698         if (shmflg & SHM_RND) {
4699             shmaddr &= ~(shmlba - 1);
4700         } else {
4701             return -TARGET_EINVAL;
4702         }
4703     }
4704
4705     mmap_lock();
4706
4707     if (shmaddr)
4708         host_raddr = shmat(shmid, (void *)g2h(shmaddr), shmflg);
4709     else {
4710         abi_ulong mmap_start;
4711
4712         mmap_start = mmap_find_vma(0, shm_info.shm_segsz);
4713
4714         if (mmap_start == -1) {
4715             errno = ENOMEM;
4716             host_raddr = (void *)-1;
4717         } else
4718             host_raddr = shmat(shmid, g2h(mmap_start), shmflg | SHM_REMAP);
4719     }
4720
4721     if (host_raddr == (void *)-1) {
4722         mmap_unlock();
4723         return get_errno((long)host_raddr);
4724     }
4725     raddr=h2g((unsigned long)host_raddr);
4726
4727     page_set_flags(raddr, raddr + shm_info.shm_segsz,
4728                    PAGE_VALID | PAGE_READ |
4729                    ((shmflg & SHM_RDONLY)? 0 : PAGE_WRITE));
4730
4731     for (i = 0; i < N_SHM_REGIONS; i++) {
4732         if (!shm_regions[i].in_use) {
4733             shm_regions[i].in_use = true;
4734             shm_regions[i].start = raddr;
4735             shm_regions[i].size = shm_info.shm_segsz;
4736             break;
4737         }
4738     }
4739
4740     mmap_unlock();
4741     return raddr;
4742
4743 }
4744
4745 static inline abi_long do_shmdt(abi_ulong shmaddr)
4746 {
4747     int i;
4748
4749     for (i = 0; i < N_SHM_REGIONS; ++i) {
4750         if (shm_regions[i].in_use && shm_regions[i].start == shmaddr) {
4751             shm_regions[i].in_use = false;
4752             page_set_flags(shmaddr, shmaddr + shm_regions[i].size, 0);
4753             break;
4754         }
4755     }
4756
4757     return get_errno(shmdt(g2h(shmaddr)));
4758 }
4759
4760 #ifdef TARGET_NR_ipc
4761 /* ??? This only works with linear mappings.  */
4762 /* do_ipc() must return target values and target errnos. */
4763 static abi_long do_ipc(CPUArchState *cpu_env,
4764                        unsigned int call, abi_long first,
4765                        abi_long second, abi_long third,
4766                        abi_long ptr, abi_long fifth)
4767 {
4768     int version;
4769     abi_long ret = 0;
4770
4771     version = call >> 16;
4772     call &= 0xffff;
4773
4774     switch (call) {
4775     case IPCOP_semop:
4776         ret = do_semop(first, ptr, second);
4777         break;
4778
4779     case IPCOP_semget:
4780         ret = get_errno(semget(first, second, third));
4781         break;
4782
4783     case IPCOP_semctl: {
4784         /* The semun argument to semctl is passed by value, so dereference the
4785          * ptr argument. */
4786         abi_ulong atptr;
4787         get_user_ual(atptr, ptr);
4788         ret = do_semctl(first, second, third, atptr);
4789         break;
4790     }
4791
4792     case IPCOP_msgget:
4793         ret = get_errno(msgget(first, second));
4794         break;
4795
4796     case IPCOP_msgsnd:
4797         ret = do_msgsnd(first, ptr, second, third);
4798         break;
4799
4800     case IPCOP_msgctl:
4801         ret = do_msgctl(first, second, ptr);
4802         break;
4803
4804     case IPCOP_msgrcv:
4805         switch (version) {
4806         case 0:
4807             {
4808                 struct target_ipc_kludge {
4809                     abi_long msgp;
4810                     abi_long msgtyp;
4811                 } *tmp;
4812
4813                 if (!lock_user_struct(VERIFY_READ, tmp, ptr, 1)) {
4814                     ret = -TARGET_EFAULT;
4815                     break;
4816                 }
4817
4818                 ret = do_msgrcv(first, tswapal(tmp->msgp), second, tswapal(tmp->msgtyp), third);
4819
4820                 unlock_user_struct(tmp, ptr, 0);
4821                 break;
4822             }
4823         default:
4824             ret = do_msgrcv(first, ptr, second, fifth, third);
4825         }
4826         break;
4827
4828     case IPCOP_shmat:
4829         switch (version) {
4830         default:
4831         {
4832             abi_ulong raddr;
4833             raddr = do_shmat(cpu_env, first, ptr, second);
4834             if (is_error(raddr))
4835                 return get_errno(raddr);
4836             if (put_user_ual(raddr, third))
4837                 return -TARGET_EFAULT;
4838             break;
4839         }
4840         case 1:
4841             ret = -TARGET_EINVAL;
4842             break;
4843         }
4844         break;
4845     case IPCOP_shmdt:
4846         ret = do_shmdt(ptr);
4847         break;
4848
4849     case IPCOP_shmget:
4850         /* IPC_* flag values are the same on all linux platforms */
4851         ret = get_errno(shmget(first, second, third));
4852         break;
4853
4854         /* IPC_* and SHM_* command values are the same on all linux platforms */
4855     case IPCOP_shmctl:
4856         ret = do_shmctl(first, second, ptr);
4857         break;
4858     default:
4859         gemu_log("Unsupported ipc call: %d (version %d)\n", call, version);
4860         ret = -TARGET_ENOSYS;
4861         break;
4862     }
4863     return ret;
4864 }
4865 #endif
4866
4867 /* kernel structure types definitions */
4868
4869 #define STRUCT(name, ...) STRUCT_ ## name,
4870 #define STRUCT_SPECIAL(name) STRUCT_ ## name,
4871 enum {
4872 #include "syscall_types.h"
4873 STRUCT_MAX
4874 };
4875 #undef STRUCT
4876 #undef STRUCT_SPECIAL
4877
4878 #define STRUCT(name, ...) static const argtype struct_ ## name ## _def[] = {  __VA_ARGS__, TYPE_NULL };
4879 #define STRUCT_SPECIAL(name)
4880 #include "syscall_types.h"
4881 #undef STRUCT
4882 #undef STRUCT_SPECIAL
4883
4884 typedef struct IOCTLEntry IOCTLEntry;
4885
4886 typedef abi_long do_ioctl_fn(const IOCTLEntry *ie, uint8_t *buf_temp,
4887                              int fd, int cmd, abi_long arg);
4888
4889 struct IOCTLEntry {
4890     int target_cmd;
4891     unsigned int host_cmd;
4892     const char *name;
4893     int access;
4894     do_ioctl_fn *do_ioctl;
4895     const argtype arg_type[5];
4896 };
4897
4898 #define IOC_R 0x0001
4899 #define IOC_W 0x0002
4900 #define IOC_RW (IOC_R | IOC_W)
4901
4902 #define MAX_STRUCT_SIZE 4096
4903
4904 #ifdef CONFIG_FIEMAP
4905 /* So fiemap access checks don't overflow on 32 bit systems.
4906  * This is very slightly smaller than the limit imposed by
4907  * the underlying kernel.
4908  */
4909 #define FIEMAP_MAX_EXTENTS ((UINT_MAX - sizeof(struct fiemap))  \
4910                             / sizeof(struct fiemap_extent))
4911
4912 static abi_long do_ioctl_fs_ioc_fiemap(const IOCTLEntry *ie, uint8_t *buf_temp,
4913                                        int fd, int cmd, abi_long arg)
4914 {
4915     /* The parameter for this ioctl is a struct fiemap followed
4916      * by an array of struct fiemap_extent whose size is set
4917      * in fiemap->fm_extent_count. The array is filled in by the
4918      * ioctl.
4919      */
4920     int target_size_in, target_size_out;
4921     struct fiemap *fm;
4922     const argtype *arg_type = ie->arg_type;
4923     const argtype extent_arg_type[] = { MK_STRUCT(STRUCT_fiemap_extent) };
4924     void *argptr, *p;
4925     abi_long ret;
4926     int i, extent_size = thunk_type_size(extent_arg_type, 0);
4927     uint32_t outbufsz;
4928     int free_fm = 0;
4929
4930     assert(arg_type[0] == TYPE_PTR);
4931     assert(ie->access == IOC_RW);
4932     arg_type++;
4933     target_size_in = thunk_type_size(arg_type, 0);
4934     argptr = lock_user(VERIFY_READ, arg, target_size_in, 1);
4935     if (!argptr) {
4936         return -TARGET_EFAULT;
4937     }
4938     thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
4939     unlock_user(argptr, arg, 0);
4940     fm = (struct fiemap *)buf_temp;
4941     if (fm->fm_extent_count > FIEMAP_MAX_EXTENTS) {
4942         return -TARGET_EINVAL;
4943     }
4944
4945     outbufsz = sizeof (*fm) +
4946         (sizeof(struct fiemap_extent) * fm->fm_extent_count);
4947
4948     if (outbufsz > MAX_STRUCT_SIZE) {
4949         /* We can't fit all the extents into the fixed size buffer.
4950          * Allocate one that is large enough and use it instead.
4951          */
4952         fm = g_try_malloc(outbufsz);
4953         if (!fm) {
4954             return -TARGET_ENOMEM;
4955         }
4956         memcpy(fm, buf_temp, sizeof(struct fiemap));
4957         free_fm = 1;
4958     }
4959     ret = get_errno(safe_ioctl(fd, ie->host_cmd, fm));
4960     if (!is_error(ret)) {
4961         target_size_out = target_size_in;
4962         /* An extent_count of 0 means we were only counting the extents
4963          * so there are no structs to copy
4964          */
4965         if (fm->fm_extent_count != 0) {
4966             target_size_out += fm->fm_mapped_extents * extent_size;
4967         }
4968         argptr = lock_user(VERIFY_WRITE, arg, target_size_out, 0);
4969         if (!argptr) {
4970             ret = -TARGET_EFAULT;
4971         } else {
4972             /* Convert the struct fiemap */
4973             thunk_convert(argptr, fm, arg_type, THUNK_TARGET);
4974             if (fm->fm_extent_count != 0) {
4975                 p = argptr + target_size_in;
4976                 /* ...and then all the struct fiemap_extents */
4977                 for (i = 0; i < fm->fm_mapped_extents; i++) {
4978                     thunk_convert(p, &fm->fm_extents[i], extent_arg_type,
4979                                   THUNK_TARGET);
4980                     p += extent_size;
4981                 }
4982             }
4983             unlock_user(argptr, arg, target_size_out);
4984         }
4985     }
4986     if (free_fm) {
4987         g_free(fm);
4988     }
4989     return ret;
4990 }
4991 #endif
4992
4993 static abi_long do_ioctl_ifconf(const IOCTLEntry *ie, uint8_t *buf_temp,
4994                                 int fd, int cmd, abi_long arg)
4995 {
4996     const argtype *arg_type = ie->arg_type;
4997     int target_size;
4998     void *argptr;
4999     int ret;
5000     struct ifconf *host_ifconf;
5001     uint32_t outbufsz;
5002     const argtype ifreq_arg_type[] = { MK_STRUCT(STRUCT_sockaddr_ifreq) };
5003     int target_ifreq_size;
5004     int nb_ifreq;
5005     int free_buf = 0;
5006     int i;
5007     int target_ifc_len;
5008     abi_long target_ifc_buf;
5009     int host_ifc_len;
5010     char *host_ifc_buf;
5011
5012     assert(arg_type[0] == TYPE_PTR);
5013     assert(ie->access == IOC_RW);
5014
5015     arg_type++;
5016     target_size = thunk_type_size(arg_type, 0);
5017
5018     argptr = lock_user(VERIFY_READ, arg, target_size, 1);
5019     if (!argptr)
5020         return -TARGET_EFAULT;
5021     thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
5022     unlock_user(argptr, arg, 0);
5023
5024     host_ifconf = (struct ifconf *)(unsigned long)buf_temp;
5025     target_ifc_len = host_ifconf->ifc_len;
5026     target_ifc_buf = (abi_long)(unsigned long)host_ifconf->ifc_buf;
5027
5028     target_ifreq_size = thunk_type_size(ifreq_arg_type, 0);
5029     nb_ifreq = target_ifc_len / target_ifreq_size;
5030     host_ifc_len = nb_ifreq * sizeof(struct ifreq);
5031
5032     outbufsz = sizeof(*host_ifconf) + host_ifc_len;
5033     if (outbufsz > MAX_STRUCT_SIZE) {
5034         /* We can't fit all the extents into the fixed size buffer.
5035          * Allocate one that is large enough and use it instead.
5036          */
5037         host_ifconf = malloc(outbufsz);
5038         if (!host_ifconf) {
5039             return -TARGET_ENOMEM;
5040         }
5041         memcpy(host_ifconf, buf_temp, sizeof(*host_ifconf));
5042         free_buf = 1;
5043     }
5044     host_ifc_buf = (char*)host_ifconf + sizeof(*host_ifconf);
5045
5046     host_ifconf->ifc_len = host_ifc_len;
5047     host_ifconf->ifc_buf = host_ifc_buf;
5048
5049     ret = get_errno(safe_ioctl(fd, ie->host_cmd, host_ifconf));
5050     if (!is_error(ret)) {
5051         /* convert host ifc_len to target ifc_len */
5052
5053         nb_ifreq = host_ifconf->ifc_len / sizeof(struct ifreq);
5054         target_ifc_len = nb_ifreq * target_ifreq_size;
5055         host_ifconf->ifc_len = target_ifc_len;
5056
5057         /* restore target ifc_buf */
5058
5059         host_ifconf->ifc_buf = (char *)(unsigned long)target_ifc_buf;
5060
5061         /* copy struct ifconf to target user */
5062
5063         argptr = lock_user(VERIFY_WRITE, arg, target_size, 0);
5064         if (!argptr)
5065             return -TARGET_EFAULT;
5066         thunk_convert(argptr, host_ifconf, arg_type, THUNK_TARGET);
5067         unlock_user(argptr, arg, target_size);
5068
5069         /* copy ifreq[] to target user */
5070
5071         argptr = lock_user(VERIFY_WRITE, target_ifc_buf, target_ifc_len, 0);
5072         for (i = 0; i < nb_ifreq ; i++) {
5073             thunk_convert(argptr + i * target_ifreq_size,
5074                           host_ifc_buf + i * sizeof(struct ifreq),
5075                           ifreq_arg_type, THUNK_TARGET);
5076         }
5077         unlock_user(argptr, target_ifc_buf, target_ifc_len);
5078     }
5079
5080     if (free_buf) {
5081         free(host_ifconf);
5082     }
5083
5084     return ret;
5085 }
5086
5087 static abi_long do_ioctl_dm(const IOCTLEntry *ie, uint8_t *buf_temp, int fd,
5088                             int cmd, abi_long arg)
5089 {
5090     void *argptr;
5091     struct dm_ioctl *host_dm;
5092     abi_long guest_data;
5093     uint32_t guest_data_size;
5094     int target_size;
5095     const argtype *arg_type = ie->arg_type;
5096     abi_long ret;
5097     void *big_buf = NULL;
5098     char *host_data;
5099
5100     arg_type++;
5101     target_size = thunk_type_size(arg_type, 0);
5102     argptr = lock_user(VERIFY_READ, arg, target_size, 1);
5103     if (!argptr) {
5104         ret = -TARGET_EFAULT;
5105         goto out;
5106     }
5107     thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
5108     unlock_user(argptr, arg, 0);
5109
5110     /* buf_temp is too small, so fetch things into a bigger buffer */
5111     big_buf = g_malloc0(((struct dm_ioctl*)buf_temp)->data_size * 2);
5112     memcpy(big_buf, buf_temp, target_size);
5113     buf_temp = big_buf;
5114     host_dm = big_buf;
5115
5116     guest_data = arg + host_dm->data_start;
5117     if ((guest_data - arg) < 0) {
5118         ret = -TARGET_EINVAL;
5119         goto out;
5120     }
5121     guest_data_size = host_dm->data_size - host_dm->data_start;
5122     host_data = (char*)host_dm + host_dm->data_start;
5123
5124     argptr = lock_user(VERIFY_READ, guest_data, guest_data_size, 1);
5125     if (!argptr) {
5126         ret = -TARGET_EFAULT;
5127         goto out;
5128     }
5129
5130     switch (ie->host_cmd) {
5131     case DM_REMOVE_ALL:
5132     case DM_LIST_DEVICES:
5133     case DM_DEV_CREATE:
5134     case DM_DEV_REMOVE:
5135     case DM_DEV_SUSPEND:
5136     case DM_DEV_STATUS:
5137     case DM_DEV_WAIT:
5138     case DM_TABLE_STATUS:
5139     case DM_TABLE_CLEAR:
5140     case DM_TABLE_DEPS:
5141     case DM_LIST_VERSIONS:
5142         /* no input data */
5143         break;
5144     case DM_DEV_RENAME:
5145     case DM_DEV_SET_GEOMETRY:
5146         /* data contains only strings */
5147         memcpy(host_data, argptr, guest_data_size);
5148         break;
5149     case DM_TARGET_MSG:
5150         memcpy(host_data, argptr, guest_data_size);
5151         *(uint64_t*)host_data = tswap64(*(uint64_t*)argptr);
5152         break;
5153     case DM_TABLE_LOAD:
5154     {
5155         void *gspec = argptr;
5156         void *cur_data = host_data;
5157         const argtype arg_type[] = { MK_STRUCT(STRUCT_dm_target_spec) };
5158         int spec_size = thunk_type_size(arg_type, 0);
5159         int i;
5160
5161         for (i = 0; i < host_dm->target_count; i++) {
5162             struct dm_target_spec *spec = cur_data;
5163             uint32_t next;
5164             int slen;
5165
5166             thunk_convert(spec, gspec, arg_type, THUNK_HOST);
5167             slen = strlen((char*)gspec + spec_size) + 1;
5168             next = spec->next;
5169             spec->next = sizeof(*spec) + slen;
5170             strcpy((char*)&spec[1], gspec + spec_size);
5171             gspec += next;
5172             cur_data += spec->next;
5173         }
5174         break;
5175     }
5176     default:
5177         ret = -TARGET_EINVAL;
5178         unlock_user(argptr, guest_data, 0);
5179         goto out;
5180     }
5181     unlock_user(argptr, guest_data, 0);
5182
5183     ret = get_errno(safe_ioctl(fd, ie->host_cmd, buf_temp));
5184     if (!is_error(ret)) {
5185         guest_data = arg + host_dm->data_start;
5186         guest_data_size = host_dm->data_size - host_dm->data_start;
5187         argptr = lock_user(VERIFY_WRITE, guest_data, guest_data_size, 0);
5188         switch (ie->host_cmd) {
5189         case DM_REMOVE_ALL:
5190         case DM_DEV_CREATE:
5191         case DM_DEV_REMOVE:
5192         case DM_DEV_RENAME:
5193         case DM_DEV_SUSPEND:
5194         case DM_DEV_STATUS:
5195         case DM_TABLE_LOAD:
5196         case DM_TABLE_CLEAR:
5197         case DM_TARGET_MSG:
5198         case DM_DEV_SET_GEOMETRY:
5199             /* no return data */
5200             break;
5201         case DM_LIST_DEVICES:
5202         {
5203             struct dm_name_list *nl = (void*)host_dm + host_dm->data_start;
5204             uint32_t remaining_data = guest_data_size;
5205             void *cur_data = argptr;
5206             const argtype arg_type[] = { MK_STRUCT(STRUCT_dm_name_list) };
5207             int nl_size = 12; /* can't use thunk_size due to alignment */
5208
5209             while (1) {
5210                 uint32_t next = nl->next;
5211                 if (next) {
5212                     nl->next = nl_size + (strlen(nl->name) + 1);
5213                 }
5214                 if (remaining_data < nl->next) {
5215                     host_dm->flags |= DM_BUFFER_FULL_FLAG;
5216                     break;
5217                 }
5218                 thunk_convert(cur_data, nl, arg_type, THUNK_TARGET);
5219                 strcpy(cur_data + nl_size, nl->name);
5220                 cur_data += nl->next;
5221                 remaining_data -= nl->next;
5222                 if (!next) {
5223                     break;
5224                 }
5225                 nl = (void*)nl + next;
5226             }
5227             break;
5228         }
5229         case DM_DEV_WAIT:
5230         case DM_TABLE_STATUS:
5231         {
5232             struct dm_target_spec *spec = (void*)host_dm + host_dm->data_start;
5233             void *cur_data = argptr;
5234             const argtype arg_type[] = { MK_STRUCT(STRUCT_dm_target_spec) };
5235             int spec_size = thunk_type_size(arg_type, 0);
5236             int i;
5237
5238             for (i = 0; i < host_dm->target_count; i++) {
5239                 uint32_t next = spec->next;
5240                 int slen = strlen((char*)&spec[1]) + 1;
5241                 spec->next = (cur_data - argptr) + spec_size + slen;
5242                 if (guest_data_size < spec->next) {
5243                     host_dm->flags |= DM_BUFFER_FULL_FLAG;
5244                     break;
5245                 }
5246                 thunk_convert(cur_data, spec, arg_type, THUNK_TARGET);
5247                 strcpy(cur_data + spec_size, (char*)&spec[1]);
5248                 cur_data = argptr + spec->next;
5249                 spec = (void*)host_dm + host_dm->data_start + next;
5250             }
5251             break;
5252         }
5253         case DM_TABLE_DEPS:
5254         {
5255             void *hdata = (void*)host_dm + host_dm->data_start;
5256             int count = *(uint32_t*)hdata;
5257             uint64_t *hdev = hdata + 8;
5258             uint64_t *gdev = argptr + 8;
5259             int i;
5260
5261             *(uint32_t*)argptr = tswap32(count);
5262             for (i = 0; i < count; i++) {
5263                 *gdev = tswap64(*hdev);
5264                 gdev++;
5265                 hdev++;
5266             }
5267             break;
5268         }
5269         case DM_LIST_VERSIONS:
5270         {
5271             struct dm_target_versions *vers = (void*)host_dm + host_dm->data_start;
5272             uint32_t remaining_data = guest_data_size;
5273             void *cur_data = argptr;
5274             const argtype arg_type[] = { MK_STRUCT(STRUCT_dm_target_versions) };
5275             int vers_size = thunk_type_size(arg_type, 0);
5276
5277             while (1) {
5278                 uint32_t next = vers->next;
5279                 if (next) {
5280                     vers->next = vers_size + (strlen(vers->name) + 1);
5281                 }
5282                 if (remaining_data < vers->next) {
5283                     host_dm->flags |= DM_BUFFER_FULL_FLAG;
5284                     break;
5285                 }
5286                 thunk_convert(cur_data, vers, arg_type, THUNK_TARGET);
5287                 strcpy(cur_data + vers_size, vers->name);
5288                 cur_data += vers->next;
5289                 remaining_data -= vers->next;
5290                 if (!next) {
5291                     break;
5292                 }
5293                 vers = (void*)vers + next;
5294             }
5295             break;
5296         }
5297         default:
5298             unlock_user(argptr, guest_data, 0);
5299             ret = -TARGET_EINVAL;
5300             goto out;
5301         }
5302         unlock_user(argptr, guest_data, guest_data_size);
5303
5304         argptr = lock_user(VERIFY_WRITE, arg, target_size, 0);
5305         if (!argptr) {
5306             ret = -TARGET_EFAULT;
5307             goto out;
5308         }
5309         thunk_convert(argptr, buf_temp, arg_type, THUNK_TARGET);
5310         unlock_user(argptr, arg, target_size);
5311     }
5312 out:
5313     g_free(big_buf);
5314     return ret;
5315 }
5316
5317 static abi_long do_ioctl_blkpg(const IOCTLEntry *ie, uint8_t *buf_temp, int fd,
5318                                int cmd, abi_long arg)
5319 {
5320     void *argptr;
5321     int target_size;
5322     const argtype *arg_type = ie->arg_type;
5323     const argtype part_arg_type[] = { MK_STRUCT(STRUCT_blkpg_partition) };
5324     abi_long ret;
5325
5326     struct blkpg_ioctl_arg *host_blkpg = (void*)buf_temp;
5327     struct blkpg_partition host_part;
5328
5329     /* Read and convert blkpg */
5330     arg_type++;
5331     target_size = thunk_type_size(arg_type, 0);
5332     argptr = lock_user(VERIFY_READ, arg, target_size, 1);
5333     if (!argptr) {
5334         ret = -TARGET_EFAULT;
5335         goto out;
5336     }
5337     thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
5338     unlock_user(argptr, arg, 0);
5339
5340     switch (host_blkpg->op) {
5341     case BLKPG_ADD_PARTITION:
5342     case BLKPG_DEL_PARTITION:
5343         /* payload is struct blkpg_partition */
5344         break;
5345     default:
5346         /* Unknown opcode */
5347         ret = -TARGET_EINVAL;
5348         goto out;
5349     }
5350
5351     /* Read and convert blkpg->data */
5352     arg = (abi_long)(uintptr_t)host_blkpg->data;
5353     target_size = thunk_type_size(part_arg_type, 0);
5354     argptr = lock_user(VERIFY_READ, arg, target_size, 1);
5355     if (!argptr) {
5356         ret = -TARGET_EFAULT;
5357         goto out;
5358     }
5359     thunk_convert(&host_part, argptr, part_arg_type, THUNK_HOST);
5360     unlock_user(argptr, arg, 0);
5361
5362     /* Swizzle the data pointer to our local copy and call! */
5363     host_blkpg->data = &host_part;
5364     ret = get_errno(safe_ioctl(fd, ie->host_cmd, host_blkpg));
5365
5366 out:
5367     return ret;
5368 }
5369
5370 static abi_long do_ioctl_rt(const IOCTLEntry *ie, uint8_t *buf_temp,
5371                                 int fd, int cmd, abi_long arg)
5372 {
5373     const argtype *arg_type = ie->arg_type;
5374     const StructEntry *se;
5375     const argtype *field_types;
5376     const int *dst_offsets, *src_offsets;
5377     int target_size;
5378     void *argptr;
5379     abi_ulong *target_rt_dev_ptr;
5380     unsigned long *host_rt_dev_ptr;
5381     abi_long ret;
5382     int i;
5383
5384     assert(ie->access == IOC_W);
5385     assert(*arg_type == TYPE_PTR);
5386     arg_type++;
5387     assert(*arg_type == TYPE_STRUCT);
5388     target_size = thunk_type_size(arg_type, 0);
5389     argptr = lock_user(VERIFY_READ, arg, target_size, 1);
5390     if (!argptr) {
5391         return -TARGET_EFAULT;
5392     }
5393     arg_type++;
5394     assert(*arg_type == (int)STRUCT_rtentry);
5395     se = struct_entries + *arg_type++;
5396     assert(se->convert[0] == NULL);
5397     /* convert struct here to be able to catch rt_dev string */
5398     field_types = se->field_types;
5399     dst_offsets = se->field_offsets[THUNK_HOST];
5400     src_offsets = se->field_offsets[THUNK_TARGET];
5401     for (i = 0; i < se->nb_fields; i++) {
5402         if (dst_offsets[i] == offsetof(struct rtentry, rt_dev)) {
5403             assert(*field_types == TYPE_PTRVOID);
5404             target_rt_dev_ptr = (abi_ulong *)(argptr + src_offsets[i]);
5405             host_rt_dev_ptr = (unsigned long *)(buf_temp + dst_offsets[i]);
5406             if (*target_rt_dev_ptr != 0) {
5407                 *host_rt_dev_ptr = (unsigned long)lock_user_string(
5408                                                   tswapal(*target_rt_dev_ptr));
5409                 if (!*host_rt_dev_ptr) {
5410                     unlock_user(argptr, arg, 0);
5411                     return -TARGET_EFAULT;
5412                 }
5413             } else {
5414                 *host_rt_dev_ptr = 0;
5415             }
5416             field_types++;
5417             continue;
5418         }
5419         field_types = thunk_convert(buf_temp + dst_offsets[i],
5420                                     argptr + src_offsets[i],
5421                                     field_types, THUNK_HOST);
5422     }
5423     unlock_user(argptr, arg, 0);
5424
5425     ret = get_errno(safe_ioctl(fd, ie->host_cmd, buf_temp));
5426     if (*host_rt_dev_ptr != 0) {
5427         unlock_user((void *)*host_rt_dev_ptr,
5428                     *target_rt_dev_ptr, 0);
5429     }
5430     return ret;
5431 }
5432
5433 static abi_long do_ioctl_kdsigaccept(const IOCTLEntry *ie, uint8_t *buf_temp,
5434                                      int fd, int cmd, abi_long arg)
5435 {
5436     int sig = target_to_host_signal(arg);
5437     return get_errno(safe_ioctl(fd, ie->host_cmd, sig));
5438 }
5439
5440 static IOCTLEntry ioctl_entries[] = {
5441 #define IOCTL(cmd, access, ...) \
5442     { TARGET_ ## cmd, cmd, #cmd, access, 0, {  __VA_ARGS__ } },
5443 #define IOCTL_SPECIAL(cmd, access, dofn, ...)                      \
5444     { TARGET_ ## cmd, cmd, #cmd, access, dofn, {  __VA_ARGS__ } },
5445 #include "ioctls.h"
5446     { 0, 0, },
5447 };
5448
5449 /* ??? Implement proper locking for ioctls.  */
5450 /* do_ioctl() Must return target values and target errnos. */
5451 static abi_long do_ioctl(int fd, int cmd, abi_long arg)
5452 {
5453     const IOCTLEntry *ie;
5454     const argtype *arg_type;
5455     abi_long ret;
5456     uint8_t buf_temp[MAX_STRUCT_SIZE];
5457     int target_size;
5458     void *argptr;
5459
5460     ie = ioctl_entries;
5461     for(;;) {
5462         if (ie->target_cmd == 0) {
5463             gemu_log("Unsupported ioctl: cmd=0x%04lx\n", (long)cmd);
5464             return -TARGET_ENOSYS;
5465         }
5466         if (ie->target_cmd == cmd)
5467             break;
5468         ie++;
5469     }
5470     arg_type = ie->arg_type;
5471 #if defined(DEBUG)
5472     gemu_log("ioctl: cmd=0x%04lx (%s)\n", (long)cmd, ie->name);
5473 #endif
5474     if (ie->do_ioctl) {
5475         return ie->do_ioctl(ie, buf_temp, fd, cmd, arg);
5476     }
5477
5478     switch(arg_type[0]) {
5479     case TYPE_NULL:
5480         /* no argument */
5481         ret = get_errno(safe_ioctl(fd, ie->host_cmd));
5482         break;
5483     case TYPE_PTRVOID:
5484     case TYPE_INT:
5485         ret = get_errno(safe_ioctl(fd, ie->host_cmd, arg));
5486         break;
5487     case TYPE_PTR:
5488         arg_type++;
5489         target_size = thunk_type_size(arg_type, 0);
5490         switch(ie->access) {
5491         case IOC_R:
5492             ret = get_errno(safe_ioctl(fd, ie->host_cmd, buf_temp));
5493             if (!is_error(ret)) {
5494                 argptr = lock_user(VERIFY_WRITE, arg, target_size, 0);
5495                 if (!argptr)
5496                     return -TARGET_EFAULT;
5497                 thunk_convert(argptr, buf_temp, arg_type, THUNK_TARGET);
5498                 unlock_user(argptr, arg, target_size);
5499             }
5500             break;
5501         case IOC_W:
5502             argptr = lock_user(VERIFY_READ, arg, target_size, 1);
5503             if (!argptr)
5504                 return -TARGET_EFAULT;
5505             thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
5506             unlock_user(argptr, arg, 0);
5507             ret = get_errno(safe_ioctl(fd, ie->host_cmd, buf_temp));
5508             break;
5509         default:
5510         case IOC_RW:
5511             argptr = lock_user(VERIFY_READ, arg, target_size, 1);
5512             if (!argptr)
5513                 return -TARGET_EFAULT;
5514             thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
5515             unlock_user(argptr, arg, 0);
5516             ret = get_errno(safe_ioctl(fd, ie->host_cmd, buf_temp));
5517             if (!is_error(ret)) {
5518                 argptr = lock_user(VERIFY_WRITE, arg, target_size, 0);
5519                 if (!argptr)
5520                     return -TARGET_EFAULT;
5521                 thunk_convert(argptr, buf_temp, arg_type, THUNK_TARGET);
5522                 unlock_user(argptr, arg, target_size);
5523             }
5524             break;
5525         }
5526         break;
5527     default:
5528         gemu_log("Unsupported ioctl type: cmd=0x%04lx type=%d\n",
5529                  (long)cmd, arg_type[0]);
5530         ret = -TARGET_ENOSYS;
5531         break;
5532     }
5533     return ret;
5534 }
5535
5536 static const bitmask_transtbl iflag_tbl[] = {
5537         { TARGET_IGNBRK, TARGET_IGNBRK, IGNBRK, IGNBRK },
5538         { TARGET_BRKINT, TARGET_BRKINT, BRKINT, BRKINT },
5539         { TARGET_IGNPAR, TARGET_IGNPAR, IGNPAR, IGNPAR },
5540         { TARGET_PARMRK, TARGET_PARMRK, PARMRK, PARMRK },
5541         { TARGET_INPCK, TARGET_INPCK, INPCK, INPCK },
5542         { TARGET_ISTRIP, TARGET_ISTRIP, ISTRIP, ISTRIP },
5543         { TARGET_INLCR, TARGET_INLCR, INLCR, INLCR },
5544         { TARGET_IGNCR, TARGET_IGNCR, IGNCR, IGNCR },
5545         { TARGET_ICRNL, TARGET_ICRNL, ICRNL, ICRNL },
5546         { TARGET_IUCLC, TARGET_IUCLC, IUCLC, IUCLC },
5547         { TARGET_IXON, TARGET_IXON, IXON, IXON },
5548         { TARGET_IXANY, TARGET_IXANY, IXANY, IXANY },
5549         { TARGET_IXOFF, TARGET_IXOFF, IXOFF, IXOFF },
5550         { TARGET_IMAXBEL, TARGET_IMAXBEL, IMAXBEL, IMAXBEL },
5551         { 0, 0, 0, 0 }
5552 };
5553
5554 static const bitmask_transtbl oflag_tbl[] = {
5555         { TARGET_OPOST, TARGET_OPOST, OPOST, OPOST },
5556         { TARGET_OLCUC, TARGET_OLCUC, OLCUC, OLCUC },
5557         { TARGET_ONLCR, TARGET_ONLCR, ONLCR, ONLCR },
5558         { TARGET_OCRNL, TARGET_OCRNL, OCRNL, OCRNL },
5559         { TARGET_ONOCR, TARGET_ONOCR, ONOCR, ONOCR },
5560         { TARGET_ONLRET, TARGET_ONLRET, ONLRET, ONLRET },
5561         { TARGET_OFILL, TARGET_OFILL, OFILL, OFILL },
5562         { TARGET_OFDEL, TARGET_OFDEL, OFDEL, OFDEL },
5563         { TARGET_NLDLY, TARGET_NL0, NLDLY, NL0 },
5564         { TARGET_NLDLY, TARGET_NL1, NLDLY, NL1 },
5565         { TARGET_CRDLY, TARGET_CR0, CRDLY, CR0 },
5566         { TARGET_CRDLY, TARGET_CR1, CRDLY, CR1 },
5567         { TARGET_CRDLY, TARGET_CR2, CRDLY, CR2 },
5568         { TARGET_CRDLY, TARGET_CR3, CRDLY, CR3 },
5569         { TARGET_TABDLY, TARGET_TAB0, TABDLY, TAB0 },
5570         { TARGET_TABDLY, TARGET_TAB1, TABDLY, TAB1 },
5571         { TARGET_TABDLY, TARGET_TAB2, TABDLY, TAB2 },
5572         { TARGET_TABDLY, TARGET_TAB3, TABDLY, TAB3 },
5573         { TARGET_BSDLY, TARGET_BS0, BSDLY, BS0 },
5574         { TARGET_BSDLY, TARGET_BS1, BSDLY, BS1 },
5575         { TARGET_VTDLY, TARGET_VT0, VTDLY, VT0 },
5576         { TARGET_VTDLY, TARGET_VT1, VTDLY, VT1 },
5577         { TARGET_FFDLY, TARGET_FF0, FFDLY, FF0 },
5578         { TARGET_FFDLY, TARGET_FF1, FFDLY, FF1 },
5579         { 0, 0, 0, 0 }
5580 };
5581
5582 static const bitmask_transtbl cflag_tbl[] = {
5583         { TARGET_CBAUD, TARGET_B0, CBAUD, B0 },
5584         { TARGET_CBAUD, TARGET_B50, CBAUD, B50 },
5585         { TARGET_CBAUD, TARGET_B75, CBAUD, B75 },
5586         { TARGET_CBAUD, TARGET_B110, CBAUD, B110 },
5587         { TARGET_CBAUD, TARGET_B134, CBAUD, B134 },
5588         { TARGET_CBAUD, TARGET_B150, CBAUD, B150 },
5589         { TARGET_CBAUD, TARGET_B200, CBAUD, B200 },
5590         { TARGET_CBAUD, TARGET_B300, CBAUD, B300 },
5591         { TARGET_CBAUD, TARGET_B600, CBAUD, B600 },
5592         { TARGET_CBAUD, TARGET_B1200, CBAUD, B1200 },
5593         { TARGET_CBAUD, TARGET_B1800, CBAUD, B1800 },
5594         { TARGET_CBAUD, TARGET_B2400, CBAUD, B2400 },
5595         { TARGET_CBAUD, TARGET_B4800, CBAUD, B4800 },
5596         { TARGET_CBAUD, TARGET_B9600, CBAUD, B9600 },
5597         { TARGET_CBAUD, TARGET_B19200, CBAUD, B19200 },
5598         { TARGET_CBAUD, TARGET_B38400, CBAUD, B38400 },
5599         { TARGET_CBAUD, TARGET_B57600, CBAUD, B57600 },
5600         { TARGET_CBAUD, TARGET_B115200, CBAUD, B115200 },
5601         { TARGET_CBAUD, TARGET_B230400, CBAUD, B230400 },
5602         { TARGET_CBAUD, TARGET_B460800, CBAUD, B460800 },
5603         { TARGET_CSIZE, TARGET_CS5, CSIZE, CS5 },
5604         { TARGET_CSIZE, TARGET_CS6, CSIZE, CS6 },
5605         { TARGET_CSIZE, TARGET_CS7, CSIZE, CS7 },
5606         { TARGET_CSIZE, TARGET_CS8, CSIZE, CS8 },
5607         { TARGET_CSTOPB, TARGET_CSTOPB, CSTOPB, CSTOPB },
5608         { TARGET_CREAD, TARGET_CREAD, CREAD, CREAD },
5609         { TARGET_PARENB, TARGET_PARENB, PARENB, PARENB },
5610         { TARGET_PARODD, TARGET_PARODD, PARODD, PARODD },
5611         { TARGET_HUPCL, TARGET_HUPCL, HUPCL, HUPCL },
5612         { TARGET_CLOCAL, TARGET_CLOCAL, CLOCAL, CLOCAL },
5613         { TARGET_CRTSCTS, TARGET_CRTSCTS, CRTSCTS, CRTSCTS },
5614         { 0, 0, 0, 0 }
5615 };
5616
5617 static const bitmask_transtbl lflag_tbl[] = {
5618         { TARGET_ISIG, TARGET_ISIG, ISIG, ISIG },
5619         { TARGET_ICANON, TARGET_ICANON, ICANON, ICANON },
5620         { TARGET_XCASE, TARGET_XCASE, XCASE, XCASE },
5621         { TARGET_ECHO, TARGET_ECHO, ECHO, ECHO },
5622         { TARGET_ECHOE, TARGET_ECHOE, ECHOE, ECHOE },
5623         { TARGET_ECHOK, TARGET_ECHOK, ECHOK, ECHOK },
5624         { TARGET_ECHONL, TARGET_ECHONL, ECHONL, ECHONL },
5625         { TARGET_NOFLSH, TARGET_NOFLSH, NOFLSH, NOFLSH },
5626         { TARGET_TOSTOP, TARGET_TOSTOP, TOSTOP, TOSTOP },
5627         { TARGET_ECHOCTL, TARGET_ECHOCTL, ECHOCTL, ECHOCTL },
5628         { TARGET_ECHOPRT, TARGET_ECHOPRT, ECHOPRT, ECHOPRT },
5629         { TARGET_ECHOKE, TARGET_ECHOKE, ECHOKE, ECHOKE },
5630         { TARGET_FLUSHO, TARGET_FLUSHO, FLUSHO, FLUSHO },
5631         { TARGET_PENDIN, TARGET_PENDIN, PENDIN, PENDIN },
5632         { TARGET_IEXTEN, TARGET_IEXTEN, IEXTEN, IEXTEN },
5633         { 0, 0, 0, 0 }
5634 };
5635
5636 static void target_to_host_termios (void *dst, const void *src)
5637 {
5638     struct host_termios *host = dst;
5639     const struct target_termios *target = src;
5640
5641     host->c_iflag =
5642         target_to_host_bitmask(tswap32(target->c_iflag), iflag_tbl);
5643     host->c_oflag =
5644         target_to_host_bitmask(tswap32(target->c_oflag), oflag_tbl);
5645     host->c_cflag =
5646         target_to_host_bitmask(tswap32(target->c_cflag), cflag_tbl);
5647     host->c_lflag =
5648         target_to_host_bitmask(tswap32(target->c_lflag), lflag_tbl);
5649     host->c_line = target->c_line;
5650
5651     memset(host->c_cc, 0, sizeof(host->c_cc));
5652     host->c_cc[VINTR] = target->c_cc[TARGET_VINTR];
5653     host->c_cc[VQUIT] = target->c_cc[TARGET_VQUIT];
5654     host->c_cc[VERASE] = target->c_cc[TARGET_VERASE];
5655     host->c_cc[VKILL] = target->c_cc[TARGET_VKILL];
5656     host->c_cc[VEOF] = target->c_cc[TARGET_VEOF];
5657     host->c_cc[VTIME] = target->c_cc[TARGET_VTIME];
5658     host->c_cc[VMIN] = target->c_cc[TARGET_VMIN];
5659     host->c_cc[VSWTC] = target->c_cc[TARGET_VSWTC];
5660     host->c_cc[VSTART] = target->c_cc[TARGET_VSTART];
5661     host->c_cc[VSTOP] = target->c_cc[TARGET_VSTOP];
5662     host->c_cc[VSUSP] = target->c_cc[TARGET_VSUSP];
5663     host->c_cc[VEOL] = target->c_cc[TARGET_VEOL];
5664     host->c_cc[VREPRINT] = target->c_cc[TARGET_VREPRINT];
5665     host->c_cc[VDISCARD] = target->c_cc[TARGET_VDISCARD];
5666     host->c_cc[VWERASE] = target->c_cc[TARGET_VWERASE];
5667     host->c_cc[VLNEXT] = target->c_cc[TARGET_VLNEXT];
5668     host->c_cc[VEOL2] = target->c_cc[TARGET_VEOL2];
5669 }
5670
5671 static void host_to_target_termios (void *dst, const void *src)
5672 {
5673     struct target_termios *target = dst;
5674     const struct host_termios *host = src;
5675
5676     target->c_iflag =
5677         tswap32(host_to_target_bitmask(host->c_iflag, iflag_tbl));
5678     target->c_oflag =
5679         tswap32(host_to_target_bitmask(host->c_oflag, oflag_tbl));
5680     target->c_cflag =
5681         tswap32(host_to_target_bitmask(host->c_cflag, cflag_tbl));
5682     target->c_lflag =
5683         tswap32(host_to_target_bitmask(host->c_lflag, lflag_tbl));
5684     target->c_line = host->c_line;
5685
5686     memset(target->c_cc, 0, sizeof(target->c_cc));
5687     target->c_cc[TARGET_VINTR] = host->c_cc[VINTR];
5688     target->c_cc[TARGET_VQUIT] = host->c_cc[VQUIT];
5689     target->c_cc[TARGET_VERASE] = host->c_cc[VERASE];
5690     target->c_cc[TARGET_VKILL] = host->c_cc[VKILL];
5691     target->c_cc[TARGET_VEOF] = host->c_cc[VEOF];
5692     target->c_cc[TARGET_VTIME] = host->c_cc[VTIME];
5693     target->c_cc[TARGET_VMIN] = host->c_cc[VMIN];
5694     target->c_cc[TARGET_VSWTC] = host->c_cc[VSWTC];
5695     target->c_cc[TARGET_VSTART] = host->c_cc[VSTART];
5696     target->c_cc[TARGET_VSTOP] = host->c_cc[VSTOP];
5697     target->c_cc[TARGET_VSUSP] = host->c_cc[VSUSP];
5698     target->c_cc[TARGET_VEOL] = host->c_cc[VEOL];
5699     target->c_cc[TARGET_VREPRINT] = host->c_cc[VREPRINT];
5700     target->c_cc[TARGET_VDISCARD] = host->c_cc[VDISCARD];
5701     target->c_cc[TARGET_VWERASE] = host->c_cc[VWERASE];
5702     target->c_cc[TARGET_VLNEXT] = host->c_cc[VLNEXT];
5703     target->c_cc[TARGET_VEOL2] = host->c_cc[VEOL2];
5704 }
5705
5706 static const StructEntry struct_termios_def = {
5707     .convert = { host_to_target_termios, target_to_host_termios },
5708     .size = { sizeof(struct target_termios), sizeof(struct host_termios) },
5709     .align = { __alignof__(struct target_termios), __alignof__(struct host_termios) },
5710 };
5711
5712 static bitmask_transtbl mmap_flags_tbl[] = {
5713         { TARGET_MAP_SHARED, TARGET_MAP_SHARED, MAP_SHARED, MAP_SHARED },
5714         { TARGET_MAP_PRIVATE, TARGET_MAP_PRIVATE, MAP_PRIVATE, MAP_PRIVATE },
5715         { TARGET_MAP_FIXED, TARGET_MAP_FIXED, MAP_FIXED, MAP_FIXED },
5716         { TARGET_MAP_ANONYMOUS, TARGET_MAP_ANONYMOUS, MAP_ANONYMOUS, MAP_ANONYMOUS },
5717         { TARGET_MAP_GROWSDOWN, TARGET_MAP_GROWSDOWN, MAP_GROWSDOWN, MAP_GROWSDOWN },
5718         { TARGET_MAP_DENYWRITE, TARGET_MAP_DENYWRITE, MAP_DENYWRITE, MAP_DENYWRITE },
5719         { TARGET_MAP_EXECUTABLE, TARGET_MAP_EXECUTABLE, MAP_EXECUTABLE, MAP_EXECUTABLE },
5720         { TARGET_MAP_LOCKED, TARGET_MAP_LOCKED, MAP_LOCKED, MAP_LOCKED },
5721         { TARGET_MAP_NORESERVE, TARGET_MAP_NORESERVE, MAP_NORESERVE,
5722           MAP_NORESERVE },
5723         { 0, 0, 0, 0 }
5724 };
5725
5726 #if defined(TARGET_I386)
5727
5728 /* NOTE: there is really one LDT for all the threads */
5729 static uint8_t *ldt_table;
5730
5731 static abi_long read_ldt(abi_ulong ptr, unsigned long bytecount)
5732 {
5733     int size;
5734     void *p;
5735
5736     if (!ldt_table)
5737         return 0;
5738     size = TARGET_LDT_ENTRIES * TARGET_LDT_ENTRY_SIZE;
5739     if (size > bytecount)
5740         size = bytecount;
5741     p = lock_user(VERIFY_WRITE, ptr, size, 0);
5742     if (!p)
5743         return -TARGET_EFAULT;
5744     /* ??? Should this by byteswapped?  */
5745     memcpy(p, ldt_table, size);
5746     unlock_user(p, ptr, size);
5747     return size;
5748 }
5749
5750 /* XXX: add locking support */
5751 static abi_long write_ldt(CPUX86State *env,
5752                           abi_ulong ptr, unsigned long bytecount, int oldmode)
5753 {
5754     struct target_modify_ldt_ldt_s ldt_info;
5755     struct target_modify_ldt_ldt_s *target_ldt_info;
5756     int seg_32bit, contents, read_exec_only, limit_in_pages;
5757     int seg_not_present, useable, lm;
5758     uint32_t *lp, entry_1, entry_2;
5759
5760     if (bytecount != sizeof(ldt_info))
5761         return -TARGET_EINVAL;
5762     if (!lock_user_struct(VERIFY_READ, target_ldt_info, ptr, 1))
5763         return -TARGET_EFAULT;
5764     ldt_info.entry_number = tswap32(target_ldt_info->entry_number);
5765     ldt_info.base_addr = tswapal(target_ldt_info->base_addr);
5766     ldt_info.limit = tswap32(target_ldt_info->limit);
5767     ldt_info.flags = tswap32(target_ldt_info->flags);
5768     unlock_user_struct(target_ldt_info, ptr, 0);
5769
5770     if (ldt_info.entry_number >= TARGET_LDT_ENTRIES)
5771         return -TARGET_EINVAL;
5772     seg_32bit = ldt_info.flags & 1;
5773     contents = (ldt_info.flags >> 1) & 3;
5774     read_exec_only = (ldt_info.flags >> 3) & 1;
5775     limit_in_pages = (ldt_info.flags >> 4) & 1;
5776     seg_not_present = (ldt_info.flags >> 5) & 1;
5777     useable = (ldt_info.flags >> 6) & 1;
5778 #ifdef TARGET_ABI32
5779     lm = 0;
5780 #else
5781     lm = (ldt_info.flags >> 7) & 1;
5782 #endif
5783     if (contents == 3) {
5784         if (oldmode)
5785             return -TARGET_EINVAL;
5786         if (seg_not_present == 0)
5787             return -TARGET_EINVAL;
5788     }
5789     /* allocate the LDT */
5790     if (!ldt_table) {
5791         env->ldt.base = target_mmap(0,
5792                                     TARGET_LDT_ENTRIES * TARGET_LDT_ENTRY_SIZE,
5793                                     PROT_READ|PROT_WRITE,
5794                                     MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
5795         if (env->ldt.base == -1)
5796             return -TARGET_ENOMEM;
5797         memset(g2h(env->ldt.base), 0,
5798                TARGET_LDT_ENTRIES * TARGET_LDT_ENTRY_SIZE);
5799         env->ldt.limit = 0xffff;
5800         ldt_table = g2h(env->ldt.base);
5801     }
5802
5803     /* NOTE: same code as Linux kernel */
5804     /* Allow LDTs to be cleared by the user. */
5805     if (ldt_info.base_addr == 0 && ldt_info.limit == 0) {
5806         if (oldmode ||
5807             (contents == 0              &&
5808              read_exec_only == 1        &&
5809              seg_32bit == 0             &&
5810              limit_in_pages == 0        &&
5811              seg_not_present == 1       &&
5812              useable == 0 )) {
5813             entry_1 = 0;
5814             entry_2 = 0;
5815             goto install;
5816         }
5817     }
5818
5819     entry_1 = ((ldt_info.base_addr & 0x0000ffff) << 16) |
5820         (ldt_info.limit & 0x0ffff);
5821     entry_2 = (ldt_info.base_addr & 0xff000000) |
5822         ((ldt_info.base_addr & 0x00ff0000) >> 16) |
5823         (ldt_info.limit & 0xf0000) |
5824         ((read_exec_only ^ 1) << 9) |
5825         (contents << 10) |
5826         ((seg_not_present ^ 1) << 15) |
5827         (seg_32bit << 22) |
5828         (limit_in_pages << 23) |
5829         (lm << 21) |
5830         0x7000;
5831     if (!oldmode)
5832         entry_2 |= (useable << 20);
5833
5834     /* Install the new entry ...  */
5835 install:
5836     lp = (uint32_t *)(ldt_table + (ldt_info.entry_number << 3));
5837     lp[0] = tswap32(entry_1);
5838     lp[1] = tswap32(entry_2);
5839     return 0;
5840 }
5841
5842 /* specific and weird i386 syscalls */
5843 static abi_long do_modify_ldt(CPUX86State *env, int func, abi_ulong ptr,
5844                               unsigned long bytecount)
5845 {
5846     abi_long ret;
5847
5848     switch (func) {
5849     case 0:
5850         ret = read_ldt(ptr, bytecount);
5851         break;
5852     case 1:
5853         ret = write_ldt(env, ptr, bytecount, 1);
5854         break;
5855     case 0x11:
5856         ret = write_ldt(env, ptr, bytecount, 0);
5857         break;
5858     default:
5859         ret = -TARGET_ENOSYS;
5860         break;
5861     }
5862     return ret;
5863 }
5864
5865 #if defined(TARGET_I386) && defined(TARGET_ABI32)
5866 abi_long do_set_thread_area(CPUX86State *env, abi_ulong ptr)
5867 {
5868     uint64_t *gdt_table = g2h(env->gdt.base);
5869     struct target_modify_ldt_ldt_s ldt_info;
5870     struct target_modify_ldt_ldt_s *target_ldt_info;
5871     int seg_32bit, contents, read_exec_only, limit_in_pages;
5872     int seg_not_present, useable, lm;
5873     uint32_t *lp, entry_1, entry_2;
5874     int i;
5875
5876     lock_user_struct(VERIFY_WRITE, target_ldt_info, ptr, 1);
5877     if (!target_ldt_info)
5878         return -TARGET_EFAULT;
5879     ldt_info.entry_number = tswap32(target_ldt_info->entry_number);
5880     ldt_info.base_addr = tswapal(target_ldt_info->base_addr);
5881     ldt_info.limit = tswap32(target_ldt_info->limit);
5882     ldt_info.flags = tswap32(target_ldt_info->flags);
5883     if (ldt_info.entry_number == -1) {
5884         for (i=TARGET_GDT_ENTRY_TLS_MIN; i<=TARGET_GDT_ENTRY_TLS_MAX; i++) {
5885             if (gdt_table[i] == 0) {
5886                 ldt_info.entry_number = i;
5887                 target_ldt_info->entry_number = tswap32(i);
5888                 break;
5889             }
5890         }
5891     }
5892     unlock_user_struct(target_ldt_info, ptr, 1);
5893
5894     if (ldt_info.entry_number < TARGET_GDT_ENTRY_TLS_MIN || 
5895         ldt_info.entry_number > TARGET_GDT_ENTRY_TLS_MAX)
5896            return -TARGET_EINVAL;
5897     seg_32bit = ldt_info.flags & 1;
5898     contents = (ldt_info.flags >> 1) & 3;
5899     read_exec_only = (ldt_info.flags >> 3) & 1;
5900     limit_in_pages = (ldt_info.flags >> 4) & 1;
5901     seg_not_present = (ldt_info.flags >> 5) & 1;
5902     useable = (ldt_info.flags >> 6) & 1;
5903 #ifdef TARGET_ABI32
5904     lm = 0;
5905 #else
5906     lm = (ldt_info.flags >> 7) & 1;
5907 #endif
5908
5909     if (contents == 3) {
5910         if (seg_not_present == 0)
5911             return -TARGET_EINVAL;
5912     }
5913
5914     /* NOTE: same code as Linux kernel */
5915     /* Allow LDTs to be cleared by the user. */
5916     if (ldt_info.base_addr == 0 && ldt_info.limit == 0) {
5917         if ((contents == 0             &&
5918              read_exec_only == 1       &&
5919              seg_32bit == 0            &&
5920              limit_in_pages == 0       &&
5921              seg_not_present == 1      &&
5922              useable == 0 )) {
5923             entry_1 = 0;
5924             entry_2 = 0;
5925             goto install;
5926         }
5927     }
5928
5929     entry_1 = ((ldt_info.base_addr & 0x0000ffff) << 16) |
5930         (ldt_info.limit & 0x0ffff);
5931     entry_2 = (ldt_info.base_addr & 0xff000000) |
5932         ((ldt_info.base_addr & 0x00ff0000) >> 16) |
5933         (ldt_info.limit & 0xf0000) |
5934         ((read_exec_only ^ 1) << 9) |
5935         (contents << 10) |
5936         ((seg_not_present ^ 1) << 15) |
5937         (seg_32bit << 22) |
5938         (limit_in_pages << 23) |
5939         (useable << 20) |
5940         (lm << 21) |
5941         0x7000;
5942
5943     /* Install the new entry ...  */
5944 install:
5945     lp = (uint32_t *)(gdt_table + ldt_info.entry_number);
5946     lp[0] = tswap32(entry_1);
5947     lp[1] = tswap32(entry_2);
5948     return 0;
5949 }
5950
5951 static abi_long do_get_thread_area(CPUX86State *env, abi_ulong ptr)
5952 {
5953     struct target_modify_ldt_ldt_s *target_ldt_info;
5954     uint64_t *gdt_table = g2h(env->gdt.base);
5955     uint32_t base_addr, limit, flags;
5956     int seg_32bit, contents, read_exec_only, limit_in_pages, idx;
5957     int seg_not_present, useable, lm;
5958     uint32_t *lp, entry_1, entry_2;
5959
5960     lock_user_struct(VERIFY_WRITE, target_ldt_info, ptr, 1);
5961     if (!target_ldt_info)
5962         return -TARGET_EFAULT;
5963     idx = tswap32(target_ldt_info->entry_number);
5964     if (idx < TARGET_GDT_ENTRY_TLS_MIN ||
5965         idx > TARGET_GDT_ENTRY_TLS_MAX) {
5966         unlock_user_struct(target_ldt_info, ptr, 1);
5967         return -TARGET_EINVAL;
5968     }
5969     lp = (uint32_t *)(gdt_table + idx);
5970     entry_1 = tswap32(lp[0]);
5971     entry_2 = tswap32(lp[1]);
5972     
5973     read_exec_only = ((entry_2 >> 9) & 1) ^ 1;
5974     contents = (entry_2 >> 10) & 3;
5975     seg_not_present = ((entry_2 >> 15) & 1) ^ 1;
5976     seg_32bit = (entry_2 >> 22) & 1;
5977     limit_in_pages = (entry_2 >> 23) & 1;
5978     useable = (entry_2 >> 20) & 1;
5979 #ifdef TARGET_ABI32
5980     lm = 0;
5981 #else
5982     lm = (entry_2 >> 21) & 1;
5983 #endif
5984     flags = (seg_32bit << 0) | (contents << 1) |
5985         (read_exec_only << 3) | (limit_in_pages << 4) |
5986         (seg_not_present << 5) | (useable << 6) | (lm << 7);
5987     limit = (entry_1 & 0xffff) | (entry_2  & 0xf0000);
5988     base_addr = (entry_1 >> 16) | 
5989         (entry_2 & 0xff000000) | 
5990         ((entry_2 & 0xff) << 16);
5991     target_ldt_info->base_addr = tswapal(base_addr);
5992     target_ldt_info->limit = tswap32(limit);
5993     target_ldt_info->flags = tswap32(flags);
5994     unlock_user_struct(target_ldt_info, ptr, 1);
5995     return 0;
5996 }
5997 #endif /* TARGET_I386 && TARGET_ABI32 */
5998
5999 #ifndef TARGET_ABI32
6000 abi_long do_arch_prctl(CPUX86State *env, int code, abi_ulong addr)
6001 {
6002     abi_long ret = 0;
6003     abi_ulong val;
6004     int idx;
6005
6006     switch(code) {
6007     case TARGET_ARCH_SET_GS:
6008     case TARGET_ARCH_SET_FS:
6009         if (code == TARGET_ARCH_SET_GS)
6010             idx = R_GS;
6011         else
6012             idx = R_FS;
6013         cpu_x86_load_seg(env, idx, 0);
6014         env->segs[idx].base = addr;
6015         break;
6016     case TARGET_ARCH_GET_GS:
6017     case TARGET_ARCH_GET_FS:
6018         if (code == TARGET_ARCH_GET_GS)
6019             idx = R_GS;
6020         else
6021             idx = R_FS;
6022         val = env->segs[idx].base;
6023         if (put_user(val, addr, abi_ulong))
6024             ret = -TARGET_EFAULT;
6025         break;
6026     default:
6027         ret = -TARGET_EINVAL;
6028         break;
6029     }
6030     return ret;
6031 }
6032 #endif
6033
6034 #endif /* defined(TARGET_I386) */
6035
6036 #define NEW_STACK_SIZE 0x40000
6037
6038
6039 static pthread_mutex_t clone_lock = PTHREAD_MUTEX_INITIALIZER;
6040 typedef struct {
6041     CPUArchState *env;
6042     pthread_mutex_t mutex;
6043     pthread_cond_t cond;
6044     pthread_t thread;
6045     uint32_t tid;
6046     abi_ulong child_tidptr;
6047     abi_ulong parent_tidptr;
6048     sigset_t sigmask;
6049 } new_thread_info;
6050
6051 static void *clone_func(void *arg)
6052 {
6053     new_thread_info *info = arg;
6054     CPUArchState *env;
6055     CPUState *cpu;
6056     TaskState *ts;
6057
6058     rcu_register_thread();
6059     env = info->env;
6060     cpu = ENV_GET_CPU(env);
6061     thread_cpu = cpu;
6062     ts = (TaskState *)cpu->opaque;
6063     info->tid = gettid();
6064     cpu->host_tid = info->tid;
6065     task_settid(ts);
6066     if (info->child_tidptr)
6067         put_user_u32(info->tid, info->child_tidptr);
6068     if (info->parent_tidptr)
6069         put_user_u32(info->tid, info->parent_tidptr);
6070     /* Enable signals.  */
6071     sigprocmask(SIG_SETMASK, &info->sigmask, NULL);
6072     /* Signal to the parent that we're ready.  */
6073     pthread_mutex_lock(&info->mutex);
6074     pthread_cond_broadcast(&info->cond);
6075     pthread_mutex_unlock(&info->mutex);
6076     /* Wait until the parent has finshed initializing the tls state.  */
6077     pthread_mutex_lock(&clone_lock);
6078     pthread_mutex_unlock(&clone_lock);
6079     cpu_loop(env);
6080     /* never exits */
6081     return NULL;
6082 }
6083
6084 /* do_fork() Must return host values and target errnos (unlike most
6085    do_*() functions). */
6086 static int do_fork(CPUArchState *env, unsigned int flags, abi_ulong newsp,
6087                    abi_ulong parent_tidptr, target_ulong newtls,
6088                    abi_ulong child_tidptr)
6089 {
6090     CPUState *cpu = ENV_GET_CPU(env);
6091     int ret;
6092     TaskState *ts;
6093     CPUState *new_cpu;
6094     CPUArchState *new_env;
6095     sigset_t sigmask;
6096
6097     flags &= ~CLONE_IGNORED_FLAGS;
6098
6099     /* Emulate vfork() with fork() */
6100     if (flags & CLONE_VFORK)
6101         flags &= ~(CLONE_VFORK | CLONE_VM);
6102
6103     if (flags & CLONE_VM) {
6104         TaskState *parent_ts = (TaskState *)cpu->opaque;
6105         new_thread_info info;
6106         pthread_attr_t attr;
6107
6108         if (((flags & CLONE_THREAD_FLAGS) != CLONE_THREAD_FLAGS) ||
6109             (flags & CLONE_INVALID_THREAD_FLAGS)) {
6110             return -TARGET_EINVAL;
6111         }
6112
6113         ts = g_new0(TaskState, 1);
6114         init_task_state(ts);
6115         /* we create a new CPU instance. */
6116         new_env = cpu_copy(env);
6117         /* Init regs that differ from the parent.  */
6118         cpu_clone_regs(new_env, newsp);
6119         new_cpu = ENV_GET_CPU(new_env);
6120         new_cpu->opaque = ts;
6121         ts->bprm = parent_ts->bprm;
6122         ts->info = parent_ts->info;
6123         ts->signal_mask = parent_ts->signal_mask;
6124
6125         if (flags & CLONE_CHILD_CLEARTID) {
6126             ts->child_tidptr = child_tidptr;
6127         }
6128
6129         if (flags & CLONE_SETTLS) {
6130             cpu_set_tls (new_env, newtls);
6131         }
6132
6133         /* Grab a mutex so that thread setup appears atomic.  */
6134         pthread_mutex_lock(&clone_lock);
6135
6136         memset(&info, 0, sizeof(info));
6137         pthread_mutex_init(&info.mutex, NULL);
6138         pthread_mutex_lock(&info.mutex);
6139         pthread_cond_init(&info.cond, NULL);
6140         info.env = new_env;
6141         if (flags & CLONE_CHILD_SETTID) {
6142             info.child_tidptr = child_tidptr;
6143         }
6144         if (flags & CLONE_PARENT_SETTID) {
6145             info.parent_tidptr = parent_tidptr;
6146         }
6147
6148         ret = pthread_attr_init(&attr);
6149         ret = pthread_attr_setstacksize(&attr, NEW_STACK_SIZE);
6150         ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
6151         /* It is not safe to deliver signals until the child has finished
6152            initializing, so temporarily block all signals.  */
6153         sigfillset(&sigmask);
6154         sigprocmask(SIG_BLOCK, &sigmask, &info.sigmask);
6155
6156         ret = pthread_create(&info.thread, &attr, clone_func, &info);
6157         /* TODO: Free new CPU state if thread creation failed.  */
6158
6159         sigprocmask(SIG_SETMASK, &info.sigmask, NULL);
6160         pthread_attr_destroy(&attr);
6161         if (ret == 0) {
6162             /* Wait for the child to initialize.  */
6163             pthread_cond_wait(&info.cond, &info.mutex);
6164             ret = info.tid;
6165         } else {
6166             ret = -1;
6167         }
6168         pthread_mutex_unlock(&info.mutex);
6169         pthread_cond_destroy(&info.cond);
6170         pthread_mutex_destroy(&info.mutex);
6171         pthread_mutex_unlock(&clone_lock);
6172     } else {
6173         /* if no CLONE_VM, we consider it is a fork */
6174         if (flags & CLONE_INVALID_FORK_FLAGS) {
6175             return -TARGET_EINVAL;
6176         }
6177
6178         /* We can't support custom termination signals */
6179         if ((flags & CSIGNAL) != TARGET_SIGCHLD) {
6180             return -TARGET_EINVAL;
6181         }
6182
6183         if (block_signals()) {
6184             return -TARGET_ERESTARTSYS;
6185         }
6186
6187         fork_start();
6188         ret = fork();
6189         if (ret == 0) {
6190             /* Child Process.  */
6191             rcu_after_fork();
6192             cpu_clone_regs(env, newsp);
6193             fork_end(1);
6194             /* There is a race condition here.  The parent process could
6195                theoretically read the TID in the child process before the child
6196                tid is set.  This would require using either ptrace
6197                (not implemented) or having *_tidptr to point at a shared memory
6198                mapping.  We can't repeat the spinlock hack used above because
6199                the child process gets its own copy of the lock.  */
6200             if (flags & CLONE_CHILD_SETTID)
6201                 put_user_u32(gettid(), child_tidptr);
6202             if (flags & CLONE_PARENT_SETTID)
6203                 put_user_u32(gettid(), parent_tidptr);
6204             ts = (TaskState *)cpu->opaque;
6205             if (flags & CLONE_SETTLS)
6206                 cpu_set_tls (env, newtls);
6207             if (flags & CLONE_CHILD_CLEARTID)
6208                 ts->child_tidptr = child_tidptr;
6209         } else {
6210             fork_end(0);
6211         }
6212     }
6213     return ret;
6214 }
6215
6216 /* warning : doesn't handle linux specific flags... */
6217 static int target_to_host_fcntl_cmd(int cmd)
6218 {
6219     switch(cmd) {
6220         case TARGET_F_DUPFD:
6221         case TARGET_F_GETFD:
6222         case TARGET_F_SETFD:
6223         case TARGET_F_GETFL:
6224         case TARGET_F_SETFL:
6225             return cmd;
6226         case TARGET_F_GETLK:
6227             return F_GETLK64;
6228         case TARGET_F_SETLK:
6229             return F_SETLK64;
6230         case TARGET_F_SETLKW:
6231             return F_SETLKW64;
6232         case TARGET_F_GETOWN:
6233             return F_GETOWN;
6234         case TARGET_F_SETOWN:
6235             return F_SETOWN;
6236         case TARGET_F_GETSIG:
6237             return F_GETSIG;
6238         case TARGET_F_SETSIG:
6239             return F_SETSIG;
6240 #if TARGET_ABI_BITS == 32
6241         case TARGET_F_GETLK64:
6242             return F_GETLK64;
6243         case TARGET_F_SETLK64:
6244             return F_SETLK64;
6245         case TARGET_F_SETLKW64:
6246             return F_SETLKW64;
6247 #endif
6248         case TARGET_F_SETLEASE:
6249             return F_SETLEASE;
6250         case TARGET_F_GETLEASE:
6251             return F_GETLEASE;
6252 #ifdef F_DUPFD_CLOEXEC
6253         case TARGET_F_DUPFD_CLOEXEC:
6254             return F_DUPFD_CLOEXEC;
6255 #endif
6256         case TARGET_F_NOTIFY:
6257             return F_NOTIFY;
6258 #ifdef F_GETOWN_EX
6259         case TARGET_F_GETOWN_EX:
6260             return F_GETOWN_EX;
6261 #endif
6262 #ifdef F_SETOWN_EX
6263         case TARGET_F_SETOWN_EX:
6264             return F_SETOWN_EX;
6265 #endif
6266 #ifdef F_SETPIPE_SZ
6267         case TARGET_F_SETPIPE_SZ:
6268             return F_SETPIPE_SZ;
6269         case TARGET_F_GETPIPE_SZ:
6270             return F_GETPIPE_SZ;
6271 #endif
6272         default:
6273             return -TARGET_EINVAL;
6274     }
6275     return -TARGET_EINVAL;
6276 }
6277
6278 #define TRANSTBL_CONVERT(a) { -1, TARGET_##a, -1, a }
6279 static const bitmask_transtbl flock_tbl[] = {
6280     TRANSTBL_CONVERT(F_RDLCK),
6281     TRANSTBL_CONVERT(F_WRLCK),
6282     TRANSTBL_CONVERT(F_UNLCK),
6283     TRANSTBL_CONVERT(F_EXLCK),
6284     TRANSTBL_CONVERT(F_SHLCK),
6285     { 0, 0, 0, 0 }
6286 };
6287
6288 static inline abi_long copy_from_user_flock(struct flock64 *fl,
6289                                             abi_ulong target_flock_addr)
6290 {
6291     struct target_flock *target_fl;
6292     short l_type;
6293
6294     if (!lock_user_struct(VERIFY_READ, target_fl, target_flock_addr, 1)) {
6295         return -TARGET_EFAULT;
6296     }
6297
6298     __get_user(l_type, &target_fl->l_type);
6299     fl->l_type = target_to_host_bitmask(l_type, flock_tbl);
6300     __get_user(fl->l_whence, &target_fl->l_whence);
6301     __get_user(fl->l_start, &target_fl->l_start);
6302     __get_user(fl->l_len, &target_fl->l_len);
6303     __get_user(fl->l_pid, &target_fl->l_pid);
6304     unlock_user_struct(target_fl, target_flock_addr, 0);
6305     return 0;
6306 }
6307
6308 static inline abi_long copy_to_user_flock(abi_ulong target_flock_addr,
6309                                           const struct flock64 *fl)
6310 {
6311     struct target_flock *target_fl;
6312     short l_type;
6313
6314     if (!lock_user_struct(VERIFY_WRITE, target_fl, target_flock_addr, 0)) {
6315         return -TARGET_EFAULT;
6316     }
6317
6318     l_type = host_to_target_bitmask(fl->l_type, flock_tbl);
6319     __put_user(l_type, &target_fl->l_type);
6320     __put_user(fl->l_whence, &target_fl->l_whence);
6321     __put_user(fl->l_start, &target_fl->l_start);
6322     __put_user(fl->l_len, &target_fl->l_len);
6323     __put_user(fl->l_pid, &target_fl->l_pid);
6324     unlock_user_struct(target_fl, target_flock_addr, 1);
6325     return 0;
6326 }
6327
6328 typedef abi_long from_flock64_fn(struct flock64 *fl, abi_ulong target_addr);
6329 typedef abi_long to_flock64_fn(abi_ulong target_addr, const struct flock64 *fl);
6330
6331 #if defined(TARGET_ARM) && TARGET_ABI_BITS == 32
6332 static inline abi_long copy_from_user_eabi_flock64(struct flock64 *fl,
6333                                                    abi_ulong target_flock_addr)
6334 {
6335     struct target_eabi_flock64 *target_fl;
6336     short l_type;
6337
6338     if (!lock_user_struct(VERIFY_READ, target_fl, target_flock_addr, 1)) {
6339         return -TARGET_EFAULT;
6340     }
6341
6342     __get_user(l_type, &target_fl->l_type);
6343     fl->l_type = target_to_host_bitmask(l_type, flock_tbl);
6344     __get_user(fl->l_whence, &target_fl->l_whence);
6345     __get_user(fl->l_start, &target_fl->l_start);
6346     __get_user(fl->l_len, &target_fl->l_len);
6347     __get_user(fl->l_pid, &target_fl->l_pid);
6348     unlock_user_struct(target_fl, target_flock_addr, 0);
6349     return 0;
6350 }
6351
6352 static inline abi_long copy_to_user_eabi_flock64(abi_ulong target_flock_addr,
6353                                                  const struct flock64 *fl)
6354 {
6355     struct target_eabi_flock64 *target_fl;
6356     short l_type;
6357
6358     if (!lock_user_struct(VERIFY_WRITE, target_fl, target_flock_addr, 0)) {
6359         return -TARGET_EFAULT;
6360     }
6361
6362     l_type = host_to_target_bitmask(fl->l_type, flock_tbl);
6363     __put_user(l_type, &target_fl->l_type);
6364     __put_user(fl->l_whence, &target_fl->l_whence);
6365     __put_user(fl->l_start, &target_fl->l_start);
6366     __put_user(fl->l_len, &target_fl->l_len);
6367     __put_user(fl->l_pid, &target_fl->l_pid);
6368     unlock_user_struct(target_fl, target_flock_addr, 1);
6369     return 0;
6370 }
6371 #endif
6372
6373 static inline abi_long copy_from_user_flock64(struct flock64 *fl,
6374                                               abi_ulong target_flock_addr)
6375 {
6376     struct target_flock64 *target_fl;
6377     short l_type;
6378
6379     if (!lock_user_struct(VERIFY_READ, target_fl, target_flock_addr, 1)) {
6380         return -TARGET_EFAULT;
6381     }
6382
6383     __get_user(l_type, &target_fl->l_type);
6384     fl->l_type = target_to_host_bitmask(l_type, flock_tbl);
6385     __get_user(fl->l_whence, &target_fl->l_whence);
6386     __get_user(fl->l_start, &target_fl->l_start);
6387     __get_user(fl->l_len, &target_fl->l_len);
6388     __get_user(fl->l_pid, &target_fl->l_pid);
6389     unlock_user_struct(target_fl, target_flock_addr, 0);
6390     return 0;
6391 }
6392
6393 static inline abi_long copy_to_user_flock64(abi_ulong target_flock_addr,
6394                                             const struct flock64 *fl)
6395 {
6396     struct target_flock64 *target_fl;
6397     short l_type;
6398
6399     if (!lock_user_struct(VERIFY_WRITE, target_fl, target_flock_addr, 0)) {
6400         return -TARGET_EFAULT;
6401     }
6402
6403     l_type = host_to_target_bitmask(fl->l_type, flock_tbl);
6404     __put_user(l_type, &target_fl->l_type);
6405     __put_user(fl->l_whence, &target_fl->l_whence);
6406     __put_user(fl->l_start, &target_fl->l_start);
6407     __put_user(fl->l_len, &target_fl->l_len);
6408     __put_user(fl->l_pid, &target_fl->l_pid);
6409     unlock_user_struct(target_fl, target_flock_addr, 1);
6410     return 0;
6411 }
6412
6413 static abi_long do_fcntl(int fd, int cmd, abi_ulong arg)
6414 {
6415     struct flock64 fl64;
6416 #ifdef F_GETOWN_EX
6417     struct f_owner_ex fox;
6418     struct target_f_owner_ex *target_fox;
6419 #endif
6420     abi_long ret;
6421     int host_cmd = target_to_host_fcntl_cmd(cmd);
6422
6423     if (host_cmd == -TARGET_EINVAL)
6424             return host_cmd;
6425
6426     switch(cmd) {
6427     case TARGET_F_GETLK:
6428         ret = copy_from_user_flock(&fl64, arg);
6429         if (ret) {
6430             return ret;
6431         }
6432         ret = get_errno(safe_fcntl(fd, host_cmd, &fl64));
6433         if (ret == 0) {
6434             ret = copy_to_user_flock(arg, &fl64);
6435         }
6436         break;
6437
6438     case TARGET_F_SETLK:
6439     case TARGET_F_SETLKW:
6440         ret = copy_from_user_flock(&fl64, arg);
6441         if (ret) {
6442             return ret;
6443         }
6444         ret = get_errno(safe_fcntl(fd, host_cmd, &fl64));
6445         break;
6446
6447     case TARGET_F_GETLK64:
6448         ret = copy_from_user_flock64(&fl64, arg);
6449         if (ret) {
6450             return ret;
6451         }
6452         ret = get_errno(safe_fcntl(fd, host_cmd, &fl64));
6453         if (ret == 0) {
6454             ret = copy_to_user_flock64(arg, &fl64);
6455         }
6456         break;
6457     case TARGET_F_SETLK64:
6458     case TARGET_F_SETLKW64:
6459         ret = copy_from_user_flock64(&fl64, arg);
6460         if (ret) {
6461             return ret;
6462         }
6463         ret = get_errno(safe_fcntl(fd, host_cmd, &fl64));
6464         break;
6465
6466     case TARGET_F_GETFL:
6467         ret = get_errno(safe_fcntl(fd, host_cmd, arg));
6468         if (ret >= 0) {
6469             ret = host_to_target_bitmask(ret, fcntl_flags_tbl);
6470         }
6471         break;
6472
6473     case TARGET_F_SETFL:
6474         ret = get_errno(safe_fcntl(fd, host_cmd,
6475                                    target_to_host_bitmask(arg,
6476                                                           fcntl_flags_tbl)));
6477         break;
6478
6479 #ifdef F_GETOWN_EX
6480     case TARGET_F_GETOWN_EX:
6481         ret = get_errno(safe_fcntl(fd, host_cmd, &fox));
6482         if (ret >= 0) {
6483             if (!lock_user_struct(VERIFY_WRITE, target_fox, arg, 0))
6484                 return -TARGET_EFAULT;
6485             target_fox->type = tswap32(fox.type);
6486             target_fox->pid = tswap32(fox.pid);
6487             unlock_user_struct(target_fox, arg, 1);
6488         }
6489         break;
6490 #endif
6491
6492 #ifdef F_SETOWN_EX
6493     case TARGET_F_SETOWN_EX:
6494         if (!lock_user_struct(VERIFY_READ, target_fox, arg, 1))
6495             return -TARGET_EFAULT;
6496         fox.type = tswap32(target_fox->type);
6497         fox.pid = tswap32(target_fox->pid);
6498         unlock_user_struct(target_fox, arg, 0);
6499         ret = get_errno(safe_fcntl(fd, host_cmd, &fox));
6500         break;
6501 #endif
6502
6503     case TARGET_F_SETOWN:
6504     case TARGET_F_GETOWN:
6505     case TARGET_F_SETSIG:
6506     case TARGET_F_GETSIG:
6507     case TARGET_F_SETLEASE:
6508     case TARGET_F_GETLEASE:
6509     case TARGET_F_SETPIPE_SZ:
6510     case TARGET_F_GETPIPE_SZ:
6511         ret = get_errno(safe_fcntl(fd, host_cmd, arg));
6512         break;
6513
6514     default:
6515         ret = get_errno(safe_fcntl(fd, cmd, arg));
6516         break;
6517     }
6518     return ret;
6519 }
6520
6521 #ifdef USE_UID16
6522
6523 static inline int high2lowuid(int uid)
6524 {
6525     if (uid > 65535)
6526         return 65534;
6527     else
6528         return uid;
6529 }
6530
6531 static inline int high2lowgid(int gid)
6532 {
6533     if (gid > 65535)
6534         return 65534;
6535     else
6536         return gid;
6537 }
6538
6539 static inline int low2highuid(int uid)
6540 {
6541     if ((int16_t)uid == -1)
6542         return -1;
6543     else
6544         return uid;
6545 }
6546
6547 static inline int low2highgid(int gid)
6548 {
6549     if ((int16_t)gid == -1)
6550         return -1;
6551     else
6552         return gid;
6553 }
6554 static inline int tswapid(int id)
6555 {
6556     return tswap16(id);
6557 }
6558
6559 #define put_user_id(x, gaddr) put_user_u16(x, gaddr)
6560
6561 #else /* !USE_UID16 */
6562 static inline int high2lowuid(int uid)
6563 {
6564     return uid;
6565 }
6566 static inline int high2lowgid(int gid)
6567 {
6568     return gid;
6569 }
6570 static inline int low2highuid(int uid)
6571 {
6572     return uid;
6573 }
6574 static inline int low2highgid(int gid)
6575 {
6576     return gid;
6577 }
6578 static inline int tswapid(int id)
6579 {
6580     return tswap32(id);
6581 }
6582
6583 #define put_user_id(x, gaddr) put_user_u32(x, gaddr)
6584
6585 #endif /* USE_UID16 */
6586
6587 /* We must do direct syscalls for setting UID/GID, because we want to
6588  * implement the Linux system call semantics of "change only for this thread",
6589  * not the libc/POSIX semantics of "change for all threads in process".
6590  * (See http://ewontfix.com/17/ for more details.)
6591  * We use the 32-bit version of the syscalls if present; if it is not
6592  * then either the host architecture supports 32-bit UIDs natively with
6593  * the standard syscall, or the 16-bit UID is the best we can do.
6594  */
6595 #ifdef __NR_setuid32
6596 #define __NR_sys_setuid __NR_setuid32
6597 #else
6598 #define __NR_sys_setuid __NR_setuid
6599 #endif
6600 #ifdef __NR_setgid32
6601 #define __NR_sys_setgid __NR_setgid32
6602 #else
6603 #define __NR_sys_setgid __NR_setgid
6604 #endif
6605 #ifdef __NR_setresuid32
6606 #define __NR_sys_setresuid __NR_setresuid32
6607 #else
6608 #define __NR_sys_setresuid __NR_setresuid
6609 #endif
6610 #ifdef __NR_setresgid32
6611 #define __NR_sys_setresgid __NR_setresgid32
6612 #else
6613 #define __NR_sys_setresgid __NR_setresgid
6614 #endif
6615
6616 _syscall1(int, sys_setuid, uid_t, uid)
6617 _syscall1(int, sys_setgid, gid_t, gid)
6618 _syscall3(int, sys_setresuid, uid_t, ruid, uid_t, euid, uid_t, suid)
6619 _syscall3(int, sys_setresgid, gid_t, rgid, gid_t, egid, gid_t, sgid)
6620
6621 void syscall_init(void)
6622 {
6623     IOCTLEntry *ie;
6624     const argtype *arg_type;
6625     int size;
6626     int i;
6627
6628     thunk_init(STRUCT_MAX);
6629
6630 #define STRUCT(name, ...) thunk_register_struct(STRUCT_ ## name, #name, struct_ ## name ## _def);
6631 #define STRUCT_SPECIAL(name) thunk_register_struct_direct(STRUCT_ ## name, #name, &struct_ ## name ## _def);
6632 #include "syscall_types.h"
6633 #undef STRUCT
6634 #undef STRUCT_SPECIAL
6635
6636     /* Build target_to_host_errno_table[] table from
6637      * host_to_target_errno_table[]. */
6638     for (i = 0; i < ERRNO_TABLE_SIZE; i++) {
6639         target_to_host_errno_table[host_to_target_errno_table[i]] = i;
6640     }
6641
6642     /* we patch the ioctl size if necessary. We rely on the fact that
6643        no ioctl has all the bits at '1' in the size field */
6644     ie = ioctl_entries;
6645     while (ie->target_cmd != 0) {
6646         if (((ie->target_cmd >> TARGET_IOC_SIZESHIFT) & TARGET_IOC_SIZEMASK) ==
6647             TARGET_IOC_SIZEMASK) {
6648             arg_type = ie->arg_type;
6649             if (arg_type[0] != TYPE_PTR) {
6650                 fprintf(stderr, "cannot patch size for ioctl 0x%x\n",
6651                         ie->target_cmd);
6652                 exit(1);
6653             }
6654             arg_type++;
6655             size = thunk_type_size(arg_type, 0);
6656             ie->target_cmd = (ie->target_cmd &
6657                               ~(TARGET_IOC_SIZEMASK << TARGET_IOC_SIZESHIFT)) |
6658                 (size << TARGET_IOC_SIZESHIFT);
6659         }
6660
6661         /* automatic consistency check if same arch */
6662 #if (defined(__i386__) && defined(TARGET_I386) && defined(TARGET_ABI32)) || \
6663     (defined(__x86_64__) && defined(TARGET_X86_64))
6664         if (unlikely(ie->target_cmd != ie->host_cmd)) {
6665             fprintf(stderr, "ERROR: ioctl(%s): target=0x%x host=0x%x\n",
6666                     ie->name, ie->target_cmd, ie->host_cmd);
6667         }
6668 #endif
6669         ie++;
6670     }
6671 }
6672
6673 #if TARGET_ABI_BITS == 32
6674 static inline uint64_t target_offset64(uint32_t word0, uint32_t word1)
6675 {
6676 #ifdef TARGET_WORDS_BIGENDIAN
6677     return ((uint64_t)word0 << 32) | word1;
6678 #else
6679     return ((uint64_t)word1 << 32) | word0;
6680 #endif
6681 }
6682 #else /* TARGET_ABI_BITS == 32 */
6683 static inline uint64_t target_offset64(uint64_t word0, uint64_t word1)
6684 {
6685     return word0;
6686 }
6687 #endif /* TARGET_ABI_BITS != 32 */
6688
6689 #ifdef TARGET_NR_truncate64
6690 static inline abi_long target_truncate64(void *cpu_env, const char *arg1,
6691                                          abi_long arg2,
6692                                          abi_long arg3,
6693                                          abi_long arg4)
6694 {
6695     if (regpairs_aligned(cpu_env)) {
6696         arg2 = arg3;
6697         arg3 = arg4;
6698     }
6699     return get_errno(truncate64(arg1, target_offset64(arg2, arg3)));
6700 }
6701 #endif
6702
6703 #ifdef TARGET_NR_ftruncate64
6704 static inline abi_long target_ftruncate64(void *cpu_env, abi_long arg1,
6705                                           abi_long arg2,
6706                                           abi_long arg3,
6707                                           abi_long arg4)
6708 {
6709     if (regpairs_aligned(cpu_env)) {
6710         arg2 = arg3;
6711         arg3 = arg4;
6712     }
6713     return get_errno(ftruncate64(arg1, target_offset64(arg2, arg3)));
6714 }
6715 #endif
6716
6717 static inline abi_long target_to_host_timespec(struct timespec *host_ts,
6718                                                abi_ulong target_addr)
6719 {
6720     struct target_timespec *target_ts;
6721
6722     if (!lock_user_struct(VERIFY_READ, target_ts, target_addr, 1))
6723         return -TARGET_EFAULT;
6724     __get_user(host_ts->tv_sec, &target_ts->tv_sec);
6725     __get_user(host_ts->tv_nsec, &target_ts->tv_nsec);
6726     unlock_user_struct(target_ts, target_addr, 0);
6727     return 0;
6728 }
6729
6730 static inline abi_long host_to_target_timespec(abi_ulong target_addr,
6731                                                struct timespec *host_ts)
6732 {
6733     struct target_timespec *target_ts;
6734
6735     if (!lock_user_struct(VERIFY_WRITE, target_ts, target_addr, 0))
6736         return -TARGET_EFAULT;
6737     __put_user(host_ts->tv_sec, &target_ts->tv_sec);
6738     __put_user(host_ts->tv_nsec, &target_ts->tv_nsec);
6739     unlock_user_struct(target_ts, target_addr, 1);
6740     return 0;
6741 }
6742
6743 static inline abi_long target_to_host_itimerspec(struct itimerspec *host_itspec,
6744                                                  abi_ulong target_addr)
6745 {
6746     struct target_itimerspec *target_itspec;
6747
6748     if (!lock_user_struct(VERIFY_READ, target_itspec, target_addr, 1)) {
6749         return -TARGET_EFAULT;
6750     }
6751
6752     host_itspec->it_interval.tv_sec =
6753                             tswapal(target_itspec->it_interval.tv_sec);
6754     host_itspec->it_interval.tv_nsec =
6755                             tswapal(target_itspec->it_interval.tv_nsec);
6756     host_itspec->it_value.tv_sec = tswapal(target_itspec->it_value.tv_sec);
6757     host_itspec->it_value.tv_nsec = tswapal(target_itspec->it_value.tv_nsec);
6758
6759     unlock_user_struct(target_itspec, target_addr, 1);
6760     return 0;
6761 }
6762
6763 static inline abi_long host_to_target_itimerspec(abi_ulong target_addr,
6764                                                struct itimerspec *host_its)
6765 {
6766     struct target_itimerspec *target_itspec;
6767
6768     if (!lock_user_struct(VERIFY_WRITE, target_itspec, target_addr, 0)) {
6769         return -TARGET_EFAULT;
6770     }
6771
6772     target_itspec->it_interval.tv_sec = tswapal(host_its->it_interval.tv_sec);
6773     target_itspec->it_interval.tv_nsec = tswapal(host_its->it_interval.tv_nsec);
6774
6775     target_itspec->it_value.tv_sec = tswapal(host_its->it_value.tv_sec);
6776     target_itspec->it_value.tv_nsec = tswapal(host_its->it_value.tv_nsec);
6777
6778     unlock_user_struct(target_itspec, target_addr, 0);
6779     return 0;
6780 }
6781
6782 static inline abi_long target_to_host_timex(struct timex *host_tx,
6783                                             abi_long target_addr)
6784 {
6785     struct target_timex *target_tx;
6786
6787     if (!lock_user_struct(VERIFY_READ, target_tx, target_addr, 1)) {
6788         return -TARGET_EFAULT;
6789     }
6790
6791     __get_user(host_tx->modes, &target_tx->modes);
6792     __get_user(host_tx->offset, &target_tx->offset);
6793     __get_user(host_tx->freq, &target_tx->freq);
6794     __get_user(host_tx->maxerror, &target_tx->maxerror);
6795     __get_user(host_tx->esterror, &target_tx->esterror);
6796     __get_user(host_tx->status, &target_tx->status);
6797     __get_user(host_tx->constant, &target_tx->constant);
6798     __get_user(host_tx->precision, &target_tx->precision);
6799     __get_user(host_tx->tolerance, &target_tx->tolerance);
6800     __get_user(host_tx->time.tv_sec, &target_tx->time.tv_sec);
6801     __get_user(host_tx->time.tv_usec, &target_tx->time.tv_usec);
6802     __get_user(host_tx->tick, &target_tx->tick);
6803     __get_user(host_tx->ppsfreq, &target_tx->ppsfreq);
6804     __get_user(host_tx->jitter, &target_tx->jitter);
6805     __get_user(host_tx->shift, &target_tx->shift);
6806     __get_user(host_tx->stabil, &target_tx->stabil);
6807     __get_user(host_tx->jitcnt, &target_tx->jitcnt);
6808     __get_user(host_tx->calcnt, &target_tx->calcnt);
6809     __get_user(host_tx->errcnt, &target_tx->errcnt);
6810     __get_user(host_tx->stbcnt, &target_tx->stbcnt);
6811     __get_user(host_tx->tai, &target_tx->tai);
6812
6813     unlock_user_struct(target_tx, target_addr, 0);
6814     return 0;
6815 }
6816
6817 static inline abi_long host_to_target_timex(abi_long target_addr,
6818                                             struct timex *host_tx)
6819 {
6820     struct target_timex *target_tx;
6821
6822     if (!lock_user_struct(VERIFY_WRITE, target_tx, target_addr, 0)) {
6823         return -TARGET_EFAULT;
6824     }
6825
6826     __put_user(host_tx->modes, &target_tx->modes);
6827     __put_user(host_tx->offset, &target_tx->offset);
6828     __put_user(host_tx->freq, &target_tx->freq);
6829     __put_user(host_tx->maxerror, &target_tx->maxerror);
6830     __put_user(host_tx->esterror, &target_tx->esterror);
6831     __put_user(host_tx->status, &target_tx->status);
6832     __put_user(host_tx->constant, &target_tx->constant);
6833     __put_user(host_tx->precision, &target_tx->precision);
6834     __put_user(host_tx->tolerance, &target_tx->tolerance);
6835     __put_user(host_tx->time.tv_sec, &target_tx->time.tv_sec);
6836     __put_user(host_tx->time.tv_usec, &target_tx->time.tv_usec);
6837     __put_user(host_tx->tick, &target_tx->tick);
6838     __put_user(host_tx->ppsfreq, &target_tx->ppsfreq);
6839     __put_user(host_tx->jitter, &target_tx->jitter);
6840     __put_user(host_tx->shift, &target_tx->shift);
6841     __put_user(host_tx->stabil, &target_tx->stabil);
6842     __put_user(host_tx->jitcnt, &target_tx->jitcnt);
6843     __put_user(host_tx->calcnt, &target_tx->calcnt);
6844     __put_user(host_tx->errcnt, &target_tx->errcnt);
6845     __put_user(host_tx->stbcnt, &target_tx->stbcnt);
6846     __put_user(host_tx->tai, &target_tx->tai);
6847
6848     unlock_user_struct(target_tx, target_addr, 1);
6849     return 0;
6850 }
6851
6852
6853 static inline abi_long target_to_host_sigevent(struct sigevent *host_sevp,
6854                                                abi_ulong target_addr)
6855 {
6856     struct target_sigevent *target_sevp;
6857
6858     if (!lock_user_struct(VERIFY_READ, target_sevp, target_addr, 1)) {
6859         return -TARGET_EFAULT;
6860     }
6861
6862     /* This union is awkward on 64 bit systems because it has a 32 bit
6863      * integer and a pointer in it; we follow the conversion approach
6864      * used for handling sigval types in signal.c so the guest should get
6865      * the correct value back even if we did a 64 bit byteswap and it's
6866      * using the 32 bit integer.
6867      */
6868     host_sevp->sigev_value.sival_ptr =
6869         (void *)(uintptr_t)tswapal(target_sevp->sigev_value.sival_ptr);
6870     host_sevp->sigev_signo =
6871         target_to_host_signal(tswap32(target_sevp->sigev_signo));
6872     host_sevp->sigev_notify = tswap32(target_sevp->sigev_notify);
6873     host_sevp->_sigev_un._tid = tswap32(target_sevp->_sigev_un._tid);
6874
6875     unlock_user_struct(target_sevp, target_addr, 1);
6876     return 0;
6877 }
6878
6879 #if defined(TARGET_NR_mlockall)
6880 static inline int target_to_host_mlockall_arg(int arg)
6881 {
6882     int result = 0;
6883
6884     if (arg & TARGET_MLOCKALL_MCL_CURRENT) {
6885         result |= MCL_CURRENT;
6886     }
6887     if (arg & TARGET_MLOCKALL_MCL_FUTURE) {
6888         result |= MCL_FUTURE;
6889     }
6890     return result;
6891 }
6892 #endif
6893
6894 static inline abi_long host_to_target_stat64(void *cpu_env,
6895                                              abi_ulong target_addr,
6896                                              struct stat *host_st)
6897 {
6898 #if defined(TARGET_ARM) && defined(TARGET_ABI32)
6899     if (((CPUARMState *)cpu_env)->eabi) {
6900         struct target_eabi_stat64 *target_st;
6901
6902         if (!lock_user_struct(VERIFY_WRITE, target_st, target_addr, 0))
6903             return -TARGET_EFAULT;
6904         memset(target_st, 0, sizeof(struct target_eabi_stat64));
6905         __put_user(host_st->st_dev, &target_st->st_dev);
6906         __put_user(host_st->st_ino, &target_st->st_ino);
6907 #ifdef TARGET_STAT64_HAS_BROKEN_ST_INO
6908         __put_user(host_st->st_ino, &target_st->__st_ino);
6909 #endif
6910         __put_user(host_st->st_mode, &target_st->st_mode);
6911         __put_user(host_st->st_nlink, &target_st->st_nlink);
6912         __put_user(host_st->st_uid, &target_st->st_uid);
6913         __put_user(host_st->st_gid, &target_st->st_gid);
6914         __put_user(host_st->st_rdev, &target_st->st_rdev);
6915         __put_user(host_st->st_size, &target_st->st_size);
6916         __put_user(host_st->st_blksize, &target_st->st_blksize);
6917         __put_user(host_st->st_blocks, &target_st->st_blocks);
6918         __put_user(host_st->st_atime, &target_st->target_st_atime);
6919         __put_user(host_st->st_mtime, &target_st->target_st_mtime);
6920         __put_user(host_st->st_ctime, &target_st->target_st_ctime);
6921         unlock_user_struct(target_st, target_addr, 1);
6922     } else
6923 #endif
6924     {
6925 #if defined(TARGET_HAS_STRUCT_STAT64)
6926         struct target_stat64 *target_st;
6927 #else
6928         struct target_stat *target_st;
6929 #endif
6930
6931         if (!lock_user_struct(VERIFY_WRITE, target_st, target_addr, 0))
6932             return -TARGET_EFAULT;
6933         memset(target_st, 0, sizeof(*target_st));
6934         __put_user(host_st->st_dev, &target_st->st_dev);
6935         __put_user(host_st->st_ino, &target_st->st_ino);
6936 #ifdef TARGET_STAT64_HAS_BROKEN_ST_INO
6937         __put_user(host_st->st_ino, &target_st->__st_ino);
6938 #endif
6939         __put_user(host_st->st_mode, &target_st->st_mode);
6940         __put_user(host_st->st_nlink, &target_st->st_nlink);
6941         __put_user(host_st->st_uid, &target_st->st_uid);
6942         __put_user(host_st->st_gid, &target_st->st_gid);
6943         __put_user(host_st->st_rdev, &target_st->st_rdev);
6944         /* XXX: better use of kernel struct */
6945         __put_user(host_st->st_size, &target_st->st_size);
6946         __put_user(host_st->st_blksize, &target_st->st_blksize);
6947         __put_user(host_st->st_blocks, &target_st->st_blocks);
6948         __put_user(host_st->st_atime, &target_st->target_st_atime);
6949         __put_user(host_st->st_mtime, &target_st->target_st_mtime);
6950         __put_user(host_st->st_ctime, &target_st->target_st_ctime);
6951         unlock_user_struct(target_st, target_addr, 1);
6952     }
6953
6954     return 0;
6955 }
6956
6957 /* ??? Using host futex calls even when target atomic operations
6958    are not really atomic probably breaks things.  However implementing
6959    futexes locally would make futexes shared between multiple processes
6960    tricky.  However they're probably useless because guest atomic
6961    operations won't work either.  */
6962 static int do_futex(target_ulong uaddr, int op, int val, target_ulong timeout,
6963                     target_ulong uaddr2, int val3)
6964 {
6965     struct timespec ts, *pts;
6966     int base_op;
6967
6968     /* ??? We assume FUTEX_* constants are the same on both host
6969        and target.  */
6970 #ifdef FUTEX_CMD_MASK
6971     base_op = op & FUTEX_CMD_MASK;
6972 #else
6973     base_op = op;
6974 #endif
6975     switch (base_op) {
6976     case FUTEX_WAIT:
6977     case FUTEX_WAIT_BITSET:
6978         if (timeout) {
6979             pts = &ts;
6980             target_to_host_timespec(pts, timeout);
6981         } else {
6982             pts = NULL;
6983         }
6984         return get_errno(safe_futex(g2h(uaddr), op, tswap32(val),
6985                          pts, NULL, val3));
6986     case FUTEX_WAKE:
6987         return get_errno(safe_futex(g2h(uaddr), op, val, NULL, NULL, 0));
6988     case FUTEX_FD:
6989         return get_errno(safe_futex(g2h(uaddr), op, val, NULL, NULL, 0));
6990     case FUTEX_REQUEUE:
6991     case FUTEX_CMP_REQUEUE:
6992     case FUTEX_WAKE_OP:
6993         /* For FUTEX_REQUEUE, FUTEX_CMP_REQUEUE, and FUTEX_WAKE_OP, the
6994            TIMEOUT parameter is interpreted as a uint32_t by the kernel.
6995            But the prototype takes a `struct timespec *'; insert casts
6996            to satisfy the compiler.  We do not need to tswap TIMEOUT
6997            since it's not compared to guest memory.  */
6998         pts = (struct timespec *)(uintptr_t) timeout;
6999         return get_errno(safe_futex(g2h(uaddr), op, val, pts,
7000                                     g2h(uaddr2),
7001                                     (base_op == FUTEX_CMP_REQUEUE
7002                                      ? tswap32(val3)
7003                                      : val3)));
7004     default:
7005         return -TARGET_ENOSYS;
7006     }
7007 }
7008 #if defined(TARGET_NR_name_to_handle_at) && defined(CONFIG_OPEN_BY_HANDLE)
7009 static abi_long do_name_to_handle_at(abi_long dirfd, abi_long pathname,
7010                                      abi_long handle, abi_long mount_id,
7011                                      abi_long flags)
7012 {
7013     struct file_handle *target_fh;
7014     struct file_handle *fh;
7015     int mid = 0;
7016     abi_long ret;
7017     char *name;
7018     unsigned int size, total_size;
7019
7020     if (get_user_s32(size, handle)) {
7021         return -TARGET_EFAULT;
7022     }
7023
7024     name = lock_user_string(pathname);
7025     if (!name) {
7026         return -TARGET_EFAULT;
7027     }
7028
7029     total_size = sizeof(struct file_handle) + size;
7030     target_fh = lock_user(VERIFY_WRITE, handle, total_size, 0);
7031     if (!target_fh) {
7032         unlock_user(name, pathname, 0);
7033         return -TARGET_EFAULT;
7034     }
7035
7036     fh = g_malloc0(total_size);
7037     fh->handle_bytes = size;
7038
7039     ret = get_errno(name_to_handle_at(dirfd, path(name), fh, &mid, flags));
7040     unlock_user(name, pathname, 0);
7041
7042     /* man name_to_handle_at(2):
7043      * Other than the use of the handle_bytes field, the caller should treat
7044      * the file_handle structure as an opaque data type
7045      */
7046
7047     memcpy(target_fh, fh, total_size);
7048     target_fh->handle_bytes = tswap32(fh->handle_bytes);
7049     target_fh->handle_type = tswap32(fh->handle_type);
7050     g_free(fh);
7051     unlock_user(target_fh, handle, total_size);
7052
7053     if (put_user_s32(mid, mount_id)) {
7054         return -TARGET_EFAULT;
7055     }
7056
7057     return ret;
7058
7059 }
7060 #endif
7061
7062 #if defined(TARGET_NR_open_by_handle_at) && defined(CONFIG_OPEN_BY_HANDLE)
7063 static abi_long do_open_by_handle_at(abi_long mount_fd, abi_long handle,
7064                                      abi_long flags)
7065 {
7066     struct file_handle *target_fh;
7067     struct file_handle *fh;
7068     unsigned int size, total_size;
7069     abi_long ret;
7070
7071     if (get_user_s32(size, handle)) {
7072         return -TARGET_EFAULT;
7073     }
7074
7075     total_size = sizeof(struct file_handle) + size;
7076     target_fh = lock_user(VERIFY_READ, handle, total_size, 1);
7077     if (!target_fh) {
7078         return -TARGET_EFAULT;
7079     }
7080
7081     fh = g_memdup(target_fh, total_size);
7082     fh->handle_bytes = size;
7083     fh->handle_type = tswap32(target_fh->handle_type);
7084
7085     ret = get_errno(open_by_handle_at(mount_fd, fh,
7086                     target_to_host_bitmask(flags, fcntl_flags_tbl)));
7087
7088     g_free(fh);
7089
7090     unlock_user(target_fh, handle, total_size);
7091
7092     return ret;
7093 }
7094 #endif
7095
7096 #if defined(TARGET_NR_signalfd) || defined(TARGET_NR_signalfd4)
7097
7098 /* signalfd siginfo conversion */
7099
7100 static void
7101 host_to_target_signalfd_siginfo(struct signalfd_siginfo *tinfo,
7102                                 const struct signalfd_siginfo *info)
7103 {
7104     int sig = host_to_target_signal(info->ssi_signo);
7105
7106     /* linux/signalfd.h defines a ssi_addr_lsb
7107      * not defined in sys/signalfd.h but used by some kernels
7108      */
7109
7110 #ifdef BUS_MCEERR_AO
7111     if (tinfo->ssi_signo == SIGBUS &&
7112         (tinfo->ssi_code == BUS_MCEERR_AR ||
7113          tinfo->ssi_code == BUS_MCEERR_AO)) {
7114         uint16_t *ssi_addr_lsb = (uint16_t *)(&info->ssi_addr + 1);
7115         uint16_t *tssi_addr_lsb = (uint16_t *)(&tinfo->ssi_addr + 1);
7116         *tssi_addr_lsb = tswap16(*ssi_addr_lsb);
7117     }
7118 #endif
7119
7120     tinfo->ssi_signo = tswap32(sig);
7121     tinfo->ssi_errno = tswap32(tinfo->ssi_errno);
7122     tinfo->ssi_code = tswap32(info->ssi_code);
7123     tinfo->ssi_pid = tswap32(info->ssi_pid);
7124     tinfo->ssi_uid = tswap32(info->ssi_uid);
7125     tinfo->ssi_fd = tswap32(info->ssi_fd);
7126     tinfo->ssi_tid = tswap32(info->ssi_tid);
7127     tinfo->ssi_band = tswap32(info->ssi_band);
7128     tinfo->ssi_overrun = tswap32(info->ssi_overrun);
7129     tinfo->ssi_trapno = tswap32(info->ssi_trapno);
7130     tinfo->ssi_status = tswap32(info->ssi_status);
7131     tinfo->ssi_int = tswap32(info->ssi_int);
7132     tinfo->ssi_ptr = tswap64(info->ssi_ptr);
7133     tinfo->ssi_utime = tswap64(info->ssi_utime);
7134     tinfo->ssi_stime = tswap64(info->ssi_stime);
7135     tinfo->ssi_addr = tswap64(info->ssi_addr);
7136 }
7137
7138 static abi_long host_to_target_data_signalfd(void *buf, size_t len)
7139 {
7140     int i;
7141
7142     for (i = 0; i < len; i += sizeof(struct signalfd_siginfo)) {
7143         host_to_target_signalfd_siginfo(buf + i, buf + i);
7144     }
7145
7146     return len;
7147 }
7148
7149 static TargetFdTrans target_signalfd_trans = {
7150     .host_to_target_data = host_to_target_data_signalfd,
7151 };
7152
7153 static abi_long do_signalfd4(int fd, abi_long mask, int flags)
7154 {
7155     int host_flags;
7156     target_sigset_t *target_mask;
7157     sigset_t host_mask;
7158     abi_long ret;
7159
7160     if (flags & ~(TARGET_O_NONBLOCK | TARGET_O_CLOEXEC)) {
7161         return -TARGET_EINVAL;
7162     }
7163     if (!lock_user_struct(VERIFY_READ, target_mask, mask, 1)) {
7164         return -TARGET_EFAULT;
7165     }
7166
7167     target_to_host_sigset(&host_mask, target_mask);
7168
7169     host_flags = target_to_host_bitmask(flags, fcntl_flags_tbl);
7170
7171     ret = get_errno(signalfd(fd, &host_mask, host_flags));
7172     if (ret >= 0) {
7173         fd_trans_register(ret, &target_signalfd_trans);
7174     }
7175
7176     unlock_user_struct(target_mask, mask, 0);
7177
7178     return ret;
7179 }
7180 #endif
7181
7182 /* Map host to target signal numbers for the wait family of syscalls.
7183    Assume all other status bits are the same.  */
7184 int host_to_target_waitstatus(int status)
7185 {
7186     if (WIFSIGNALED(status)) {
7187         return host_to_target_signal(WTERMSIG(status)) | (status & ~0x7f);
7188     }
7189     if (WIFSTOPPED(status)) {
7190         return (host_to_target_signal(WSTOPSIG(status)) << 8)
7191                | (status & 0xff);
7192     }
7193     return status;
7194 }
7195
7196 static int open_self_cmdline(void *cpu_env, int fd)
7197 {
7198     int fd_orig = -1;
7199     bool word_skipped = false;
7200
7201     fd_orig = open("/proc/self/cmdline", O_RDONLY);
7202     if (fd_orig < 0) {
7203         return fd_orig;
7204     }
7205
7206     while (true) {
7207         ssize_t nb_read;
7208         char buf[128];
7209         char *cp_buf = buf;
7210
7211         nb_read = read(fd_orig, buf, sizeof(buf));
7212         if (nb_read < 0) {
7213             int e = errno;
7214             fd_orig = close(fd_orig);
7215             errno = e;
7216             return -1;
7217         } else if (nb_read == 0) {
7218             break;
7219         }
7220
7221         if (!word_skipped) {
7222             /* Skip the first string, which is the path to qemu-*-static
7223                instead of the actual command. */
7224             cp_buf = memchr(buf, 0, nb_read);
7225             if (cp_buf) {
7226                 /* Null byte found, skip one string */
7227                 cp_buf++;
7228                 nb_read -= cp_buf - buf;
7229                 word_skipped = true;
7230             }
7231         }
7232
7233         if (word_skipped) {
7234             if (write(fd, cp_buf, nb_read) != nb_read) {
7235                 int e = errno;
7236                 close(fd_orig);
7237                 errno = e;
7238                 return -1;
7239             }
7240         }
7241     }
7242
7243     return close(fd_orig);
7244 }
7245
7246 static int open_self_maps(void *cpu_env, int fd)
7247 {
7248     CPUState *cpu = ENV_GET_CPU((CPUArchState *)cpu_env);
7249     TaskState *ts = cpu->opaque;
7250     FILE *fp;
7251     char *line = NULL;
7252     size_t len = 0;
7253     ssize_t read;
7254
7255     fp = fopen("/proc/self/maps", "r");
7256     if (fp == NULL) {
7257         return -1;
7258     }
7259
7260     while ((read = getline(&line, &len, fp)) != -1) {
7261         int fields, dev_maj, dev_min, inode;
7262         uint64_t min, max, offset;
7263         char flag_r, flag_w, flag_x, flag_p;
7264         char path[512] = "";
7265         fields = sscanf(line, "%"PRIx64"-%"PRIx64" %c%c%c%c %"PRIx64" %x:%x %d"
7266                         " %512s", &min, &max, &flag_r, &flag_w, &flag_x,
7267                         &flag_p, &offset, &dev_maj, &dev_min, &inode, path);
7268
7269         if ((fields < 10) || (fields > 11)) {
7270             continue;
7271         }
7272         if (h2g_valid(min)) {
7273             int flags = page_get_flags(h2g(min));
7274             max = h2g_valid(max - 1) ? max : (uintptr_t)g2h(GUEST_ADDR_MAX);
7275             if (page_check_range(h2g(min), max - min, flags) == -1) {
7276                 continue;
7277             }
7278             if (h2g(min) == ts->info->stack_limit) {
7279                 pstrcpy(path, sizeof(path), "      [stack]");
7280             }
7281             dprintf(fd, TARGET_ABI_FMT_lx "-" TARGET_ABI_FMT_lx
7282                     " %c%c%c%c %08" PRIx64 " %02x:%02x %d %s%s\n",
7283                     h2g(min), h2g(max - 1) + 1, flag_r, flag_w,
7284                     flag_x, flag_p, offset, dev_maj, dev_min, inode,
7285                     path[0] ? "         " : "", path);
7286         }
7287     }
7288
7289     free(line);
7290     fclose(fp);
7291
7292     return 0;
7293 }
7294
7295 static int open_self_stat(void *cpu_env, int fd)
7296 {
7297     CPUState *cpu = ENV_GET_CPU((CPUArchState *)cpu_env);
7298     TaskState *ts = cpu->opaque;
7299     abi_ulong start_stack = ts->info->start_stack;
7300     int i;
7301
7302     for (i = 0; i < 44; i++) {
7303       char buf[128];
7304       int len;
7305       uint64_t val = 0;
7306
7307       if (i == 0) {
7308         /* pid */
7309         val = getpid();
7310         snprintf(buf, sizeof(buf), "%"PRId64 " ", val);
7311       } else if (i == 1) {
7312         /* app name */
7313         snprintf(buf, sizeof(buf), "(%s) ", ts->bprm->argv[0]);
7314       } else if (i == 27) {
7315         /* stack bottom */
7316         val = start_stack;
7317         snprintf(buf, sizeof(buf), "%"PRId64 " ", val);
7318       } else {
7319         /* for the rest, there is MasterCard */
7320         snprintf(buf, sizeof(buf), "0%c", i == 43 ? '\n' : ' ');
7321       }
7322
7323       len = strlen(buf);
7324       if (write(fd, buf, len) != len) {
7325           return -1;
7326       }
7327     }
7328
7329     return 0;
7330 }
7331
7332 static int open_self_auxv(void *cpu_env, int fd)
7333 {
7334     CPUState *cpu = ENV_GET_CPU((CPUArchState *)cpu_env);
7335     TaskState *ts = cpu->opaque;
7336     abi_ulong auxv = ts->info->saved_auxv;
7337     abi_ulong len = ts->info->auxv_len;
7338     char *ptr;
7339
7340     /*
7341      * Auxiliary vector is stored in target process stack.
7342      * read in whole auxv vector and copy it to file
7343      */
7344     ptr = lock_user(VERIFY_READ, auxv, len, 0);
7345     if (ptr != NULL) {
7346         while (len > 0) {
7347             ssize_t r;
7348             r = write(fd, ptr, len);
7349             if (r <= 0) {
7350                 break;
7351             }
7352             len -= r;
7353             ptr += r;
7354         }
7355         lseek(fd, 0, SEEK_SET);
7356         unlock_user(ptr, auxv, len);
7357     }
7358
7359     return 0;
7360 }
7361
7362 static int is_proc_myself(const char *filename, const char *entry)
7363 {
7364     if (!strncmp(filename, "/proc/", strlen("/proc/"))) {
7365         filename += strlen("/proc/");
7366         if (!strncmp(filename, "self/", strlen("self/"))) {
7367             filename += strlen("self/");
7368         } else if (*filename >= '1' && *filename <= '9') {
7369             char myself[80];
7370             snprintf(myself, sizeof(myself), "%d/", getpid());
7371             if (!strncmp(filename, myself, strlen(myself))) {
7372                 filename += strlen(myself);
7373             } else {
7374                 return 0;
7375             }
7376         } else {
7377             return 0;
7378         }
7379         if (!strcmp(filename, entry)) {
7380             return 1;
7381         }
7382     }
7383     return 0;
7384 }
7385
7386 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
7387 static int is_proc(const char *filename, const char *entry)
7388 {
7389     return strcmp(filename, entry) == 0;
7390 }
7391
7392 static int open_net_route(void *cpu_env, int fd)
7393 {
7394     FILE *fp;
7395     char *line = NULL;
7396     size_t len = 0;
7397     ssize_t read;
7398
7399     fp = fopen("/proc/net/route", "r");
7400     if (fp == NULL) {
7401         return -1;
7402     }
7403
7404     /* read header */
7405
7406     read = getline(&line, &len, fp);
7407     dprintf(fd, "%s", line);
7408
7409     /* read routes */
7410
7411     while ((read = getline(&line, &len, fp)) != -1) {
7412         char iface[16];
7413         uint32_t dest, gw, mask;
7414         unsigned int flags, refcnt, use, metric, mtu, window, irtt;
7415         sscanf(line, "%s\t%08x\t%08x\t%04x\t%d\t%d\t%d\t%08x\t%d\t%u\t%u\n",
7416                      iface, &dest, &gw, &flags, &refcnt, &use, &metric,
7417                      &mask, &mtu, &window, &irtt);
7418         dprintf(fd, "%s\t%08x\t%08x\t%04x\t%d\t%d\t%d\t%08x\t%d\t%u\t%u\n",
7419                 iface, tswap32(dest), tswap32(gw), flags, refcnt, use,
7420                 metric, tswap32(mask), mtu, window, irtt);
7421     }
7422
7423     free(line);
7424     fclose(fp);
7425
7426     return 0;
7427 }
7428 #endif
7429
7430 static int do_openat(void *cpu_env, int dirfd, const char *pathname, int flags, mode_t mode)
7431 {
7432     struct fake_open {
7433         const char *filename;
7434         int (*fill)(void *cpu_env, int fd);
7435         int (*cmp)(const char *s1, const char *s2);
7436     };
7437     const struct fake_open *fake_open;
7438     static const struct fake_open fakes[] = {
7439         { "maps", open_self_maps, is_proc_myself },
7440         { "stat", open_self_stat, is_proc_myself },
7441         { "auxv", open_self_auxv, is_proc_myself },
7442         { "cmdline", open_self_cmdline, is_proc_myself },
7443 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
7444         { "/proc/net/route", open_net_route, is_proc },
7445 #endif
7446         { NULL, NULL, NULL }
7447     };
7448
7449     if (is_proc_myself(pathname, "exe")) {
7450         int execfd = qemu_getauxval(AT_EXECFD);
7451         return execfd ? execfd : safe_openat(dirfd, exec_path, flags, mode);
7452     }
7453
7454     for (fake_open = fakes; fake_open->filename; fake_open++) {
7455         if (fake_open->cmp(pathname, fake_open->filename)) {
7456             break;
7457         }
7458     }
7459
7460     if (fake_open->filename) {
7461         const char *tmpdir;
7462         char filename[PATH_MAX];
7463         int fd, r;
7464
7465         /* create temporary file to map stat to */
7466         tmpdir = getenv("TMPDIR");
7467         if (!tmpdir)
7468             tmpdir = "/tmp";
7469         snprintf(filename, sizeof(filename), "%s/qemu-open.XXXXXX", tmpdir);
7470         fd = mkstemp(filename);
7471         if (fd < 0) {
7472             return fd;
7473         }
7474         unlink(filename);
7475
7476         if ((r = fake_open->fill(cpu_env, fd))) {
7477             int e = errno;
7478             close(fd);
7479             errno = e;
7480             return r;
7481         }
7482         lseek(fd, 0, SEEK_SET);
7483
7484         return fd;
7485     }
7486
7487     return safe_openat(dirfd, path(pathname), flags, mode);
7488 }
7489
7490 #define TIMER_MAGIC 0x0caf0000
7491 #define TIMER_MAGIC_MASK 0xffff0000
7492
7493 /* Convert QEMU provided timer ID back to internal 16bit index format */
7494 static target_timer_t get_timer_id(abi_long arg)
7495 {
7496     target_timer_t timerid = arg;
7497
7498     if ((timerid & TIMER_MAGIC_MASK) != TIMER_MAGIC) {
7499         return -TARGET_EINVAL;
7500     }
7501
7502     timerid &= 0xffff;
7503
7504     if (timerid >= ARRAY_SIZE(g_posix_timers)) {
7505         return -TARGET_EINVAL;
7506     }
7507
7508     return timerid;
7509 }
7510
7511 /* do_syscall() should always have a single exit point at the end so
7512    that actions, such as logging of syscall results, can be performed.
7513    All errnos that do_syscall() returns must be -TARGET_<errcode>. */
7514 abi_long do_syscall(void *cpu_env, int num, abi_long arg1,
7515                     abi_long arg2, abi_long arg3, abi_long arg4,
7516                     abi_long arg5, abi_long arg6, abi_long arg7,
7517                     abi_long arg8)
7518 {
7519     CPUState *cpu = ENV_GET_CPU(cpu_env);
7520     abi_long ret;
7521     struct stat st;
7522     struct statfs stfs;
7523     void *p;
7524
7525 #if defined(DEBUG_ERESTARTSYS)
7526     /* Debug-only code for exercising the syscall-restart code paths
7527      * in the per-architecture cpu main loops: restart every syscall
7528      * the guest makes once before letting it through.
7529      */
7530     {
7531         static int flag;
7532
7533         flag = !flag;
7534         if (flag) {
7535             return -TARGET_ERESTARTSYS;
7536         }
7537     }
7538 #endif
7539
7540 #ifdef DEBUG
7541     gemu_log("syscall %d", num);
7542 #endif
7543     trace_guest_user_syscall(cpu, num, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
7544     if(do_strace)
7545         print_syscall(num, arg1, arg2, arg3, arg4, arg5, arg6);
7546
7547     switch(num) {
7548     case TARGET_NR_exit:
7549         /* In old applications this may be used to implement _exit(2).
7550            However in threaded applictions it is used for thread termination,
7551            and _exit_group is used for application termination.
7552            Do thread termination if we have more then one thread.  */
7553
7554         if (block_signals()) {
7555             ret = -TARGET_ERESTARTSYS;
7556             break;
7557         }
7558
7559         cpu_list_lock();
7560
7561         if (CPU_NEXT(first_cpu)) {
7562             TaskState *ts;
7563
7564             /* Remove the CPU from the list.  */
7565             QTAILQ_REMOVE(&cpus, cpu, node);
7566
7567             cpu_list_unlock();
7568
7569             ts = cpu->opaque;
7570             if (ts->child_tidptr) {
7571                 put_user_u32(0, ts->child_tidptr);
7572                 sys_futex(g2h(ts->child_tidptr), FUTEX_WAKE, INT_MAX,
7573                           NULL, NULL, 0);
7574             }
7575             thread_cpu = NULL;
7576             object_unref(OBJECT(cpu));
7577             g_free(ts);
7578             rcu_unregister_thread();
7579             pthread_exit(NULL);
7580         }
7581
7582         cpu_list_unlock();
7583 #ifdef TARGET_GPROF
7584         _mcleanup();
7585 #endif
7586         gdb_exit(cpu_env, arg1);
7587         _exit(arg1);
7588         ret = 0; /* avoid warning */
7589         break;
7590     case TARGET_NR_read:
7591         if (arg3 == 0)
7592             ret = 0;
7593         else {
7594             if (!(p = lock_user(VERIFY_WRITE, arg2, arg3, 0)))
7595                 goto efault;
7596             ret = get_errno(safe_read(arg1, p, arg3));
7597             if (ret >= 0 &&
7598                 fd_trans_host_to_target_data(arg1)) {
7599                 ret = fd_trans_host_to_target_data(arg1)(p, ret);
7600             }
7601             unlock_user(p, arg2, ret);
7602         }
7603         break;
7604     case TARGET_NR_write:
7605         if (!(p = lock_user(VERIFY_READ, arg2, arg3, 1)))
7606             goto efault;
7607         ret = get_errno(safe_write(arg1, p, arg3));
7608         unlock_user(p, arg2, 0);
7609         break;
7610 #ifdef TARGET_NR_open
7611     case TARGET_NR_open:
7612         if (!(p = lock_user_string(arg1)))
7613             goto efault;
7614         ret = get_errno(do_openat(cpu_env, AT_FDCWD, p,
7615                                   target_to_host_bitmask(arg2, fcntl_flags_tbl),
7616                                   arg3));
7617         fd_trans_unregister(ret);
7618         unlock_user(p, arg1, 0);
7619         break;
7620 #endif
7621     case TARGET_NR_openat:
7622         if (!(p = lock_user_string(arg2)))
7623             goto efault;
7624         ret = get_errno(do_openat(cpu_env, arg1, p,
7625                                   target_to_host_bitmask(arg3, fcntl_flags_tbl),
7626                                   arg4));
7627         fd_trans_unregister(ret);
7628         unlock_user(p, arg2, 0);
7629         break;
7630 #if defined(TARGET_NR_name_to_handle_at) && defined(CONFIG_OPEN_BY_HANDLE)
7631     case TARGET_NR_name_to_handle_at:
7632         ret = do_name_to_handle_at(arg1, arg2, arg3, arg4, arg5);
7633         break;
7634 #endif
7635 #if defined(TARGET_NR_open_by_handle_at) && defined(CONFIG_OPEN_BY_HANDLE)
7636     case TARGET_NR_open_by_handle_at:
7637         ret = do_open_by_handle_at(arg1, arg2, arg3);
7638         fd_trans_unregister(ret);
7639         break;
7640 #endif
7641     case TARGET_NR_close:
7642         fd_trans_unregister(arg1);
7643         ret = get_errno(close(arg1));
7644         break;
7645     case TARGET_NR_brk:
7646         ret = do_brk(arg1);
7647         break;
7648 #ifdef TARGET_NR_fork
7649     case TARGET_NR_fork:
7650         ret = get_errno(do_fork(cpu_env, SIGCHLD, 0, 0, 0, 0));
7651         break;
7652 #endif
7653 #ifdef TARGET_NR_waitpid
7654     case TARGET_NR_waitpid:
7655         {
7656             int status;
7657             ret = get_errno(safe_wait4(arg1, &status, arg3, 0));
7658             if (!is_error(ret) && arg2 && ret
7659                 && put_user_s32(host_to_target_waitstatus(status), arg2))
7660                 goto efault;
7661         }
7662         break;
7663 #endif
7664 #ifdef TARGET_NR_waitid
7665     case TARGET_NR_waitid:
7666         {
7667             siginfo_t info;
7668             info.si_pid = 0;
7669             ret = get_errno(safe_waitid(arg1, arg2, &info, arg4, NULL));
7670             if (!is_error(ret) && arg3 && info.si_pid != 0) {
7671                 if (!(p = lock_user(VERIFY_WRITE, arg3, sizeof(target_siginfo_t), 0)))
7672                     goto efault;
7673                 host_to_target_siginfo(p, &info);
7674                 unlock_user(p, arg3, sizeof(target_siginfo_t));
7675             }
7676         }
7677         break;
7678 #endif
7679 #ifdef TARGET_NR_creat /* not on alpha */
7680     case TARGET_NR_creat:
7681         if (!(p = lock_user_string(arg1)))
7682             goto efault;
7683         ret = get_errno(creat(p, arg2));
7684         fd_trans_unregister(ret);
7685         unlock_user(p, arg1, 0);
7686         break;
7687 #endif
7688 #ifdef TARGET_NR_link
7689     case TARGET_NR_link:
7690         {
7691             void * p2;
7692             p = lock_user_string(arg1);
7693             p2 = lock_user_string(arg2);
7694             if (!p || !p2)
7695                 ret = -TARGET_EFAULT;
7696             else
7697                 ret = get_errno(link(p, p2));
7698             unlock_user(p2, arg2, 0);
7699             unlock_user(p, arg1, 0);
7700         }
7701         break;
7702 #endif
7703 #if defined(TARGET_NR_linkat)
7704     case TARGET_NR_linkat:
7705         {
7706             void * p2 = NULL;
7707             if (!arg2 || !arg4)
7708                 goto efault;
7709             p  = lock_user_string(arg2);
7710             p2 = lock_user_string(arg4);
7711             if (!p || !p2)
7712                 ret = -TARGET_EFAULT;
7713             else
7714                 ret = get_errno(linkat(arg1, p, arg3, p2, arg5));
7715             unlock_user(p, arg2, 0);
7716             unlock_user(p2, arg4, 0);
7717         }
7718         break;
7719 #endif
7720 #ifdef TARGET_NR_unlink
7721     case TARGET_NR_unlink:
7722         if (!(p = lock_user_string(arg1)))
7723             goto efault;
7724         ret = get_errno(unlink(p));
7725         unlock_user(p, arg1, 0);
7726         break;
7727 #endif
7728 #if defined(TARGET_NR_unlinkat)
7729     case TARGET_NR_unlinkat:
7730         if (!(p = lock_user_string(arg2)))
7731             goto efault;
7732         ret = get_errno(unlinkat(arg1, p, arg3));
7733         unlock_user(p, arg2, 0);
7734         break;
7735 #endif
7736     case TARGET_NR_execve:
7737         {
7738             char **argp, **envp;
7739             int argc, envc;
7740             abi_ulong gp;
7741             abi_ulong guest_argp;
7742             abi_ulong guest_envp;
7743             abi_ulong addr;
7744             char **q;
7745             int total_size = 0;
7746
7747             argc = 0;
7748             guest_argp = arg2;
7749             for (gp = guest_argp; gp; gp += sizeof(abi_ulong)) {
7750                 if (get_user_ual(addr, gp))
7751                     goto efault;
7752                 if (!addr)
7753                     break;
7754                 argc++;
7755             }
7756             envc = 0;
7757             guest_envp = arg3;
7758             for (gp = guest_envp; gp; gp += sizeof(abi_ulong)) {
7759                 if (get_user_ual(addr, gp))
7760                     goto efault;
7761                 if (!addr)
7762                     break;
7763                 envc++;
7764             }
7765
7766             argp = alloca((argc + 1) * sizeof(void *));
7767             envp = alloca((envc + 1) * sizeof(void *));
7768
7769             for (gp = guest_argp, q = argp; gp;
7770                   gp += sizeof(abi_ulong), q++) {
7771                 if (get_user_ual(addr, gp))
7772                     goto execve_efault;
7773                 if (!addr)
7774                     break;
7775                 if (!(*q = lock_user_string(addr)))
7776                     goto execve_efault;
7777                 total_size += strlen(*q) + 1;
7778             }
7779             *q = NULL;
7780
7781             for (gp = guest_envp, q = envp; gp;
7782                   gp += sizeof(abi_ulong), q++) {
7783                 if (get_user_ual(addr, gp))
7784                     goto execve_efault;
7785                 if (!addr)
7786                     break;
7787                 if (!(*q = lock_user_string(addr)))
7788                     goto execve_efault;
7789                 total_size += strlen(*q) + 1;
7790             }
7791             *q = NULL;
7792
7793             if (!(p = lock_user_string(arg1)))
7794                 goto execve_efault;
7795             /* Although execve() is not an interruptible syscall it is
7796              * a special case where we must use the safe_syscall wrapper:
7797              * if we allow a signal to happen before we make the host
7798              * syscall then we will 'lose' it, because at the point of
7799              * execve the process leaves QEMU's control. So we use the
7800              * safe syscall wrapper to ensure that we either take the
7801              * signal as a guest signal, or else it does not happen
7802              * before the execve completes and makes it the other
7803              * program's problem.
7804              */
7805             ret = get_errno(safe_execve(p, argp, envp));
7806             unlock_user(p, arg1, 0);
7807
7808             goto execve_end;
7809
7810         execve_efault:
7811             ret = -TARGET_EFAULT;
7812
7813         execve_end:
7814             for (gp = guest_argp, q = argp; *q;
7815                   gp += sizeof(abi_ulong), q++) {
7816                 if (get_user_ual(addr, gp)
7817                     || !addr)
7818                     break;
7819                 unlock_user(*q, addr, 0);
7820             }
7821             for (gp = guest_envp, q = envp; *q;
7822                   gp += sizeof(abi_ulong), q++) {
7823                 if (get_user_ual(addr, gp)
7824                     || !addr)
7825                     break;
7826                 unlock_user(*q, addr, 0);
7827             }
7828         }
7829         break;
7830     case TARGET_NR_chdir:
7831         if (!(p = lock_user_string(arg1)))
7832             goto efault;
7833         ret = get_errno(chdir(p));
7834         unlock_user(p, arg1, 0);
7835         break;
7836 #ifdef TARGET_NR_time
7837     case TARGET_NR_time:
7838         {
7839             time_t host_time;
7840             ret = get_errno(time(&host_time));
7841             if (!is_error(ret)
7842                 && arg1
7843                 && put_user_sal(host_time, arg1))
7844                 goto efault;
7845         }
7846         break;
7847 #endif
7848 #ifdef TARGET_NR_mknod
7849     case TARGET_NR_mknod:
7850         if (!(p = lock_user_string(arg1)))
7851             goto efault;
7852         ret = get_errno(mknod(p, arg2, arg3));
7853         unlock_user(p, arg1, 0);
7854         break;
7855 #endif
7856 #if defined(TARGET_NR_mknodat)
7857     case TARGET_NR_mknodat:
7858         if (!(p = lock_user_string(arg2)))
7859             goto efault;
7860         ret = get_errno(mknodat(arg1, p, arg3, arg4));
7861         unlock_user(p, arg2, 0);
7862         break;
7863 #endif
7864 #ifdef TARGET_NR_chmod
7865     case TARGET_NR_chmod:
7866         if (!(p = lock_user_string(arg1)))
7867             goto efault;
7868         ret = get_errno(chmod(p, arg2));
7869         unlock_user(p, arg1, 0);
7870         break;
7871 #endif
7872 #ifdef TARGET_NR_break
7873     case TARGET_NR_break:
7874         goto unimplemented;
7875 #endif
7876 #ifdef TARGET_NR_oldstat
7877     case TARGET_NR_oldstat:
7878         goto unimplemented;
7879 #endif
7880     case TARGET_NR_lseek:
7881         ret = get_errno(lseek(arg1, arg2, arg3));
7882         break;
7883 #if defined(TARGET_NR_getxpid) && defined(TARGET_ALPHA)
7884     /* Alpha specific */
7885     case TARGET_NR_getxpid:
7886         ((CPUAlphaState *)cpu_env)->ir[IR_A4] = getppid();
7887         ret = get_errno(getpid());
7888         break;
7889 #endif
7890 #ifdef TARGET_NR_getpid
7891     case TARGET_NR_getpid:
7892         ret = get_errno(getpid());
7893         break;
7894 #endif
7895     case TARGET_NR_mount:
7896         {
7897             /* need to look at the data field */
7898             void *p2, *p3;
7899
7900             if (arg1) {
7901                 p = lock_user_string(arg1);
7902                 if (!p) {
7903                     goto efault;
7904                 }
7905             } else {
7906                 p = NULL;
7907             }
7908
7909             p2 = lock_user_string(arg2);
7910             if (!p2) {
7911                 if (arg1) {
7912                     unlock_user(p, arg1, 0);
7913                 }
7914                 goto efault;
7915             }
7916
7917             if (arg3) {
7918                 p3 = lock_user_string(arg3);
7919                 if (!p3) {
7920                     if (arg1) {
7921                         unlock_user(p, arg1, 0);
7922                     }
7923                     unlock_user(p2, arg2, 0);
7924                     goto efault;
7925                 }
7926             } else {
7927                 p3 = NULL;
7928             }
7929
7930             /* FIXME - arg5 should be locked, but it isn't clear how to
7931              * do that since it's not guaranteed to be a NULL-terminated
7932              * string.
7933              */
7934             if (!arg5) {
7935                 ret = mount(p, p2, p3, (unsigned long)arg4, NULL);
7936             } else {
7937                 ret = mount(p, p2, p3, (unsigned long)arg4, g2h(arg5));
7938             }
7939             ret = get_errno(ret);
7940
7941             if (arg1) {
7942                 unlock_user(p, arg1, 0);
7943             }
7944             unlock_user(p2, arg2, 0);
7945             if (arg3) {
7946                 unlock_user(p3, arg3, 0);
7947             }
7948         }
7949         break;
7950 #ifdef TARGET_NR_umount
7951     case TARGET_NR_umount:
7952         if (!(p = lock_user_string(arg1)))
7953             goto efault;
7954         ret = get_errno(umount(p));
7955         unlock_user(p, arg1, 0);
7956         break;
7957 #endif
7958 #ifdef TARGET_NR_stime /* not on alpha */
7959     case TARGET_NR_stime:
7960         {
7961             time_t host_time;
7962             if (get_user_sal(host_time, arg1))
7963                 goto efault;
7964             ret = get_errno(stime(&host_time));
7965         }
7966         break;
7967 #endif
7968     case TARGET_NR_ptrace:
7969         goto unimplemented;
7970 #ifdef TARGET_NR_alarm /* not on alpha */
7971     case TARGET_NR_alarm:
7972         ret = alarm(arg1);
7973         break;
7974 #endif
7975 #ifdef TARGET_NR_oldfstat
7976     case TARGET_NR_oldfstat:
7977         goto unimplemented;
7978 #endif
7979 #ifdef TARGET_NR_pause /* not on alpha */
7980     case TARGET_NR_pause:
7981         if (!block_signals()) {
7982             sigsuspend(&((TaskState *)cpu->opaque)->signal_mask);
7983         }
7984         ret = -TARGET_EINTR;
7985         break;
7986 #endif
7987 #ifdef TARGET_NR_utime
7988     case TARGET_NR_utime:
7989         {
7990             struct utimbuf tbuf, *host_tbuf;
7991             struct target_utimbuf *target_tbuf;
7992             if (arg2) {
7993                 if (!lock_user_struct(VERIFY_READ, target_tbuf, arg2, 1))
7994                     goto efault;
7995                 tbuf.actime = tswapal(target_tbuf->actime);
7996                 tbuf.modtime = tswapal(target_tbuf->modtime);
7997                 unlock_user_struct(target_tbuf, arg2, 0);
7998                 host_tbuf = &tbuf;
7999             } else {
8000                 host_tbuf = NULL;
8001             }
8002             if (!(p = lock_user_string(arg1)))
8003                 goto efault;
8004             ret = get_errno(utime(p, host_tbuf));
8005             unlock_user(p, arg1, 0);
8006         }
8007         break;
8008 #endif
8009 #ifdef TARGET_NR_utimes
8010     case TARGET_NR_utimes:
8011         {
8012             struct timeval *tvp, tv[2];
8013             if (arg2) {
8014                 if (copy_from_user_timeval(&tv[0], arg2)
8015                     || copy_from_user_timeval(&tv[1],
8016                                               arg2 + sizeof(struct target_timeval)))
8017                     goto efault;
8018                 tvp = tv;
8019             } else {
8020                 tvp = NULL;
8021             }
8022             if (!(p = lock_user_string(arg1)))
8023                 goto efault;
8024             ret = get_errno(utimes(p, tvp));
8025             unlock_user(p, arg1, 0);
8026         }
8027         break;
8028 #endif
8029 #if defined(TARGET_NR_futimesat)
8030     case TARGET_NR_futimesat:
8031         {
8032             struct timeval *tvp, tv[2];
8033             if (arg3) {
8034                 if (copy_from_user_timeval(&tv[0], arg3)
8035                     || copy_from_user_timeval(&tv[1],
8036                                               arg3 + sizeof(struct target_timeval)))
8037                     goto efault;
8038                 tvp = tv;
8039             } else {
8040                 tvp = NULL;
8041             }
8042             if (!(p = lock_user_string(arg2)))
8043                 goto efault;
8044             ret = get_errno(futimesat(arg1, path(p), tvp));
8045             unlock_user(p, arg2, 0);
8046         }
8047         break;
8048 #endif
8049 #ifdef TARGET_NR_stty
8050     case TARGET_NR_stty:
8051         goto unimplemented;
8052 #endif
8053 #ifdef TARGET_NR_gtty
8054     case TARGET_NR_gtty:
8055         goto unimplemented;
8056 #endif
8057 #ifdef TARGET_NR_access
8058     case TARGET_NR_access:
8059         if (!(p = lock_user_string(arg1)))
8060             goto efault;
8061         ret = get_errno(access(path(p), arg2));
8062         unlock_user(p, arg1, 0);
8063         break;
8064 #endif
8065 #if defined(TARGET_NR_faccessat) && defined(__NR_faccessat)
8066     case TARGET_NR_faccessat:
8067         if (!(p = lock_user_string(arg2)))
8068             goto efault;
8069         ret = get_errno(faccessat(arg1, p, arg3, 0));
8070         unlock_user(p, arg2, 0);
8071         break;
8072 #endif
8073 #ifdef TARGET_NR_nice /* not on alpha */
8074     case TARGET_NR_nice:
8075         ret = get_errno(nice(arg1));
8076         break;
8077 #endif
8078 #ifdef TARGET_NR_ftime
8079     case TARGET_NR_ftime:
8080         goto unimplemented;
8081 #endif
8082     case TARGET_NR_sync:
8083         sync();
8084         ret = 0;
8085         break;
8086     case TARGET_NR_kill:
8087         ret = get_errno(safe_kill(arg1, target_to_host_signal(arg2)));
8088         break;
8089 #ifdef TARGET_NR_rename
8090     case TARGET_NR_rename:
8091         {
8092             void *p2;
8093             p = lock_user_string(arg1);
8094             p2 = lock_user_string(arg2);
8095             if (!p || !p2)
8096                 ret = -TARGET_EFAULT;
8097             else
8098                 ret = get_errno(rename(p, p2));
8099             unlock_user(p2, arg2, 0);
8100             unlock_user(p, arg1, 0);
8101         }
8102         break;
8103 #endif
8104 #if defined(TARGET_NR_renameat)
8105     case TARGET_NR_renameat:
8106         {
8107             void *p2;
8108             p  = lock_user_string(arg2);
8109             p2 = lock_user_string(arg4);
8110             if (!p || !p2)
8111                 ret = -TARGET_EFAULT;
8112             else
8113                 ret = get_errno(renameat(arg1, p, arg3, p2));
8114             unlock_user(p2, arg4, 0);
8115             unlock_user(p, arg2, 0);
8116         }
8117         break;
8118 #endif
8119 #ifdef TARGET_NR_mkdir
8120     case TARGET_NR_mkdir:
8121         if (!(p = lock_user_string(arg1)))
8122             goto efault;
8123         ret = get_errno(mkdir(p, arg2));
8124         unlock_user(p, arg1, 0);
8125         break;
8126 #endif
8127 #if defined(TARGET_NR_mkdirat)
8128     case TARGET_NR_mkdirat:
8129         if (!(p = lock_user_string(arg2)))
8130             goto efault;
8131         ret = get_errno(mkdirat(arg1, p, arg3));
8132         unlock_user(p, arg2, 0);
8133         break;
8134 #endif
8135 #ifdef TARGET_NR_rmdir
8136     case TARGET_NR_rmdir:
8137         if (!(p = lock_user_string(arg1)))
8138             goto efault;
8139         ret = get_errno(rmdir(p));
8140         unlock_user(p, arg1, 0);
8141         break;
8142 #endif
8143     case TARGET_NR_dup:
8144         ret = get_errno(dup(arg1));
8145         if (ret >= 0) {
8146             fd_trans_dup(arg1, ret);
8147         }
8148         break;
8149 #ifdef TARGET_NR_pipe
8150     case TARGET_NR_pipe:
8151         ret = do_pipe(cpu_env, arg1, 0, 0);
8152         break;
8153 #endif
8154 #ifdef TARGET_NR_pipe2
8155     case TARGET_NR_pipe2:
8156         ret = do_pipe(cpu_env, arg1,
8157                       target_to_host_bitmask(arg2, fcntl_flags_tbl), 1);
8158         break;
8159 #endif
8160     case TARGET_NR_times:
8161         {
8162             struct target_tms *tmsp;
8163             struct tms tms;
8164             ret = get_errno(times(&tms));
8165             if (arg1) {
8166                 tmsp = lock_user(VERIFY_WRITE, arg1, sizeof(struct target_tms), 0);
8167                 if (!tmsp)
8168                     goto efault;
8169                 tmsp->tms_utime = tswapal(host_to_target_clock_t(tms.tms_utime));
8170                 tmsp->tms_stime = tswapal(host_to_target_clock_t(tms.tms_stime));
8171                 tmsp->tms_cutime = tswapal(host_to_target_clock_t(tms.tms_cutime));
8172                 tmsp->tms_cstime = tswapal(host_to_target_clock_t(tms.tms_cstime));
8173             }
8174             if (!is_error(ret))
8175                 ret = host_to_target_clock_t(ret);
8176         }
8177         break;
8178 #ifdef TARGET_NR_prof
8179     case TARGET_NR_prof:
8180         goto unimplemented;
8181 #endif
8182 #ifdef TARGET_NR_signal
8183     case TARGET_NR_signal:
8184         goto unimplemented;
8185 #endif
8186     case TARGET_NR_acct:
8187         if (arg1 == 0) {
8188             ret = get_errno(acct(NULL));
8189         } else {
8190             if (!(p = lock_user_string(arg1)))
8191                 goto efault;
8192             ret = get_errno(acct(path(p)));
8193             unlock_user(p, arg1, 0);
8194         }
8195         break;
8196 #ifdef TARGET_NR_umount2
8197     case TARGET_NR_umount2:
8198         if (!(p = lock_user_string(arg1)))
8199             goto efault;
8200         ret = get_errno(umount2(p, arg2));
8201         unlock_user(p, arg1, 0);
8202         break;
8203 #endif
8204 #ifdef TARGET_NR_lock
8205     case TARGET_NR_lock:
8206         goto unimplemented;
8207 #endif
8208     case TARGET_NR_ioctl:
8209         ret = do_ioctl(arg1, arg2, arg3);
8210         break;
8211     case TARGET_NR_fcntl:
8212         ret = do_fcntl(arg1, arg2, arg3);
8213         break;
8214 #ifdef TARGET_NR_mpx
8215     case TARGET_NR_mpx:
8216         goto unimplemented;
8217 #endif
8218     case TARGET_NR_setpgid:
8219         ret = get_errno(setpgid(arg1, arg2));
8220         break;
8221 #ifdef TARGET_NR_ulimit
8222     case TARGET_NR_ulimit:
8223         goto unimplemented;
8224 #endif
8225 #ifdef TARGET_NR_oldolduname
8226     case TARGET_NR_oldolduname:
8227         goto unimplemented;
8228 #endif
8229     case TARGET_NR_umask:
8230         ret = get_errno(umask(arg1));
8231         break;
8232     case TARGET_NR_chroot:
8233         if (!(p = lock_user_string(arg1)))
8234             goto efault;
8235         ret = get_errno(chroot(p));
8236         unlock_user(p, arg1, 0);
8237         break;
8238 #ifdef TARGET_NR_ustat
8239     case TARGET_NR_ustat:
8240         goto unimplemented;
8241 #endif
8242 #ifdef TARGET_NR_dup2
8243     case TARGET_NR_dup2:
8244         ret = get_errno(dup2(arg1, arg2));
8245         if (ret >= 0) {
8246             fd_trans_dup(arg1, arg2);
8247         }
8248         break;
8249 #endif
8250 #if defined(CONFIG_DUP3) && defined(TARGET_NR_dup3)
8251     case TARGET_NR_dup3:
8252         ret = get_errno(dup3(arg1, arg2, arg3));
8253         if (ret >= 0) {
8254             fd_trans_dup(arg1, arg2);
8255         }
8256         break;
8257 #endif
8258 #ifdef TARGET_NR_getppid /* not on alpha */
8259     case TARGET_NR_getppid:
8260         ret = get_errno(getppid());
8261         break;
8262 #endif
8263 #ifdef TARGET_NR_getpgrp
8264     case TARGET_NR_getpgrp:
8265         ret = get_errno(getpgrp());
8266         break;
8267 #endif
8268     case TARGET_NR_setsid:
8269         ret = get_errno(setsid());
8270         break;
8271 #ifdef TARGET_NR_sigaction
8272     case TARGET_NR_sigaction:
8273         {
8274 #if defined(TARGET_ALPHA)
8275             struct target_sigaction act, oact, *pact = 0;
8276             struct target_old_sigaction *old_act;
8277             if (arg2) {
8278                 if (!lock_user_struct(VERIFY_READ, old_act, arg2, 1))
8279                     goto efault;
8280                 act._sa_handler = old_act->_sa_handler;
8281                 target_siginitset(&act.sa_mask, old_act->sa_mask);
8282                 act.sa_flags = old_act->sa_flags;
8283                 act.sa_restorer = 0;
8284                 unlock_user_struct(old_act, arg2, 0);
8285                 pact = &act;
8286             }
8287             ret = get_errno(do_sigaction(arg1, pact, &oact));
8288             if (!is_error(ret) && arg3) {
8289                 if (!lock_user_struct(VERIFY_WRITE, old_act, arg3, 0))
8290                     goto efault;
8291                 old_act->_sa_handler = oact._sa_handler;
8292                 old_act->sa_mask = oact.sa_mask.sig[0];
8293                 old_act->sa_flags = oact.sa_flags;
8294                 unlock_user_struct(old_act, arg3, 1);
8295             }
8296 #elif defined(TARGET_MIPS)
8297             struct target_sigaction act, oact, *pact, *old_act;
8298
8299             if (arg2) {
8300                 if (!lock_user_struct(VERIFY_READ, old_act, arg2, 1))
8301                     goto efault;
8302                 act._sa_handler = old_act->_sa_handler;
8303                 target_siginitset(&act.sa_mask, old_act->sa_mask.sig[0]);
8304                 act.sa_flags = old_act->sa_flags;
8305                 unlock_user_struct(old_act, arg2, 0);
8306                 pact = &act;
8307             } else {
8308                 pact = NULL;
8309             }
8310
8311             ret = get_errno(do_sigaction(arg1, pact, &oact));
8312
8313             if (!is_error(ret) && arg3) {
8314                 if (!lock_user_struct(VERIFY_WRITE, old_act, arg3, 0))
8315                     goto efault;
8316                 old_act->_sa_handler = oact._sa_handler;
8317                 old_act->sa_flags = oact.sa_flags;
8318                 old_act->sa_mask.sig[0] = oact.sa_mask.sig[0];
8319                 old_act->sa_mask.sig[1] = 0;
8320                 old_act->sa_mask.sig[2] = 0;
8321                 old_act->sa_mask.sig[3] = 0;
8322                 unlock_user_struct(old_act, arg3, 1);
8323             }
8324 #else
8325             struct target_old_sigaction *old_act;
8326             struct target_sigaction act, oact, *pact;
8327             if (arg2) {
8328                 if (!lock_user_struct(VERIFY_READ, old_act, arg2, 1))
8329                     goto efault;
8330                 act._sa_handler = old_act->_sa_handler;
8331                 target_siginitset(&act.sa_mask, old_act->sa_mask);
8332                 act.sa_flags = old_act->sa_flags;
8333                 act.sa_restorer = old_act->sa_restorer;
8334                 unlock_user_struct(old_act, arg2, 0);
8335                 pact = &act;
8336             } else {
8337                 pact = NULL;
8338             }
8339             ret = get_errno(do_sigaction(arg1, pact, &oact));
8340             if (!is_error(ret) && arg3) {
8341                 if (!lock_user_struct(VERIFY_WRITE, old_act, arg3, 0))
8342                     goto efault;
8343                 old_act->_sa_handler = oact._sa_handler;
8344                 old_act->sa_mask = oact.sa_mask.sig[0];
8345                 old_act->sa_flags = oact.sa_flags;
8346                 old_act->sa_restorer = oact.sa_restorer;
8347                 unlock_user_struct(old_act, arg3, 1);
8348             }
8349 #endif
8350         }
8351         break;
8352 #endif
8353     case TARGET_NR_rt_sigaction:
8354         {
8355 #if defined(TARGET_ALPHA)
8356             struct target_sigaction act, oact, *pact = 0;
8357             struct target_rt_sigaction *rt_act;
8358
8359             if (arg4 != sizeof(target_sigset_t)) {
8360                 ret = -TARGET_EINVAL;
8361                 break;
8362             }
8363             if (arg2) {
8364                 if (!lock_user_struct(VERIFY_READ, rt_act, arg2, 1))
8365                     goto efault;
8366                 act._sa_handler = rt_act->_sa_handler;
8367                 act.sa_mask = rt_act->sa_mask;
8368                 act.sa_flags = rt_act->sa_flags;
8369                 act.sa_restorer = arg5;
8370                 unlock_user_struct(rt_act, arg2, 0);
8371                 pact = &act;
8372             }
8373             ret = get_errno(do_sigaction(arg1, pact, &oact));
8374             if (!is_error(ret) && arg3) {
8375                 if (!lock_user_struct(VERIFY_WRITE, rt_act, arg3, 0))
8376                     goto efault;
8377                 rt_act->_sa_handler = oact._sa_handler;
8378                 rt_act->sa_mask = oact.sa_mask;
8379                 rt_act->sa_flags = oact.sa_flags;
8380                 unlock_user_struct(rt_act, arg3, 1);
8381             }
8382 #else
8383             struct target_sigaction *act;
8384             struct target_sigaction *oact;
8385
8386             if (arg4 != sizeof(target_sigset_t)) {
8387                 ret = -TARGET_EINVAL;
8388                 break;
8389             }
8390             if (arg2) {
8391                 if (!lock_user_struct(VERIFY_READ, act, arg2, 1))
8392                     goto efault;
8393             } else
8394                 act = NULL;
8395             if (arg3) {
8396                 if (!lock_user_struct(VERIFY_WRITE, oact, arg3, 0)) {
8397                     ret = -TARGET_EFAULT;
8398                     goto rt_sigaction_fail;
8399                 }
8400             } else
8401                 oact = NULL;
8402             ret = get_errno(do_sigaction(arg1, act, oact));
8403         rt_sigaction_fail:
8404             if (act)
8405                 unlock_user_struct(act, arg2, 0);
8406             if (oact)
8407                 unlock_user_struct(oact, arg3, 1);
8408 #endif
8409         }
8410         break;
8411 #ifdef TARGET_NR_sgetmask /* not on alpha */
8412     case TARGET_NR_sgetmask:
8413         {
8414             sigset_t cur_set;
8415             abi_ulong target_set;
8416             ret = do_sigprocmask(0, NULL, &cur_set);
8417             if (!ret) {
8418                 host_to_target_old_sigset(&target_set, &cur_set);
8419                 ret = target_set;
8420             }
8421         }
8422         break;
8423 #endif
8424 #ifdef TARGET_NR_ssetmask /* not on alpha */
8425     case TARGET_NR_ssetmask:
8426         {
8427             sigset_t set, oset, cur_set;
8428             abi_ulong target_set = arg1;
8429             /* We only have one word of the new mask so we must read
8430              * the rest of it with do_sigprocmask() and OR in this word.
8431              * We are guaranteed that a do_sigprocmask() that only queries
8432              * the signal mask will not fail.
8433              */
8434             ret = do_sigprocmask(0, NULL, &cur_set);
8435             assert(!ret);
8436             target_to_host_old_sigset(&set, &target_set);
8437             sigorset(&set, &set, &cur_set);
8438             ret = do_sigprocmask(SIG_SETMASK, &set, &oset);
8439             if (!ret) {
8440                 host_to_target_old_sigset(&target_set, &oset);
8441                 ret = target_set;
8442             }
8443         }
8444         break;
8445 #endif
8446 #ifdef TARGET_NR_sigprocmask
8447     case TARGET_NR_sigprocmask:
8448         {
8449 #if defined(TARGET_ALPHA)
8450             sigset_t set, oldset;
8451             abi_ulong mask;
8452             int how;
8453
8454             switch (arg1) {
8455             case TARGET_SIG_BLOCK:
8456                 how = SIG_BLOCK;
8457                 break;
8458             case TARGET_SIG_UNBLOCK:
8459                 how = SIG_UNBLOCK;
8460                 break;
8461             case TARGET_SIG_SETMASK:
8462                 how = SIG_SETMASK;
8463                 break;
8464             default:
8465                 ret = -TARGET_EINVAL;
8466                 goto fail;
8467             }
8468             mask = arg2;
8469             target_to_host_old_sigset(&set, &mask);
8470
8471             ret = do_sigprocmask(how, &set, &oldset);
8472             if (!is_error(ret)) {
8473                 host_to_target_old_sigset(&mask, &oldset);
8474                 ret = mask;
8475                 ((CPUAlphaState *)cpu_env)->ir[IR_V0] = 0; /* force no error */
8476             }
8477 #else
8478             sigset_t set, oldset, *set_ptr;
8479             int how;
8480
8481             if (arg2) {
8482                 switch (arg1) {
8483                 case TARGET_SIG_BLOCK:
8484                     how = SIG_BLOCK;
8485                     break;
8486                 case TARGET_SIG_UNBLOCK:
8487                     how = SIG_UNBLOCK;
8488                     break;
8489                 case TARGET_SIG_SETMASK:
8490                     how = SIG_SETMASK;
8491                     break;
8492                 default:
8493                     ret = -TARGET_EINVAL;
8494                     goto fail;
8495                 }
8496                 if (!(p = lock_user(VERIFY_READ, arg2, sizeof(target_sigset_t), 1)))
8497                     goto efault;
8498                 target_to_host_old_sigset(&set, p);
8499                 unlock_user(p, arg2, 0);
8500                 set_ptr = &set;
8501             } else {
8502                 how = 0;
8503                 set_ptr = NULL;
8504             }
8505             ret = do_sigprocmask(how, set_ptr, &oldset);
8506             if (!is_error(ret) && arg3) {
8507                 if (!(p = lock_user(VERIFY_WRITE, arg3, sizeof(target_sigset_t), 0)))
8508                     goto efault;
8509                 host_to_target_old_sigset(p, &oldset);
8510                 unlock_user(p, arg3, sizeof(target_sigset_t));
8511             }
8512 #endif
8513         }
8514         break;
8515 #endif
8516     case TARGET_NR_rt_sigprocmask:
8517         {
8518             int how = arg1;
8519             sigset_t set, oldset, *set_ptr;
8520
8521             if (arg4 != sizeof(target_sigset_t)) {
8522                 ret = -TARGET_EINVAL;
8523                 break;
8524             }
8525
8526             if (arg2) {
8527                 switch(how) {
8528                 case TARGET_SIG_BLOCK:
8529                     how = SIG_BLOCK;
8530                     break;
8531                 case TARGET_SIG_UNBLOCK:
8532                     how = SIG_UNBLOCK;
8533                     break;
8534                 case TARGET_SIG_SETMASK:
8535                     how = SIG_SETMASK;
8536                     break;
8537                 default:
8538                     ret = -TARGET_EINVAL;
8539                     goto fail;
8540                 }
8541                 if (!(p = lock_user(VERIFY_READ, arg2, sizeof(target_sigset_t), 1)))
8542                     goto efault;
8543                 target_to_host_sigset(&set, p);
8544                 unlock_user(p, arg2, 0);
8545                 set_ptr = &set;
8546             } else {
8547                 how = 0;
8548                 set_ptr = NULL;
8549             }
8550             ret = do_sigprocmask(how, set_ptr, &oldset);
8551             if (!is_error(ret) && arg3) {
8552                 if (!(p = lock_user(VERIFY_WRITE, arg3, sizeof(target_sigset_t), 0)))
8553                     goto efault;
8554                 host_to_target_sigset(p, &oldset);
8555                 unlock_user(p, arg3, sizeof(target_sigset_t));
8556             }
8557         }
8558         break;
8559 #ifdef TARGET_NR_sigpending
8560     case TARGET_NR_sigpending:
8561         {
8562             sigset_t set;
8563             ret = get_errno(sigpending(&set));
8564             if (!is_error(ret)) {
8565                 if (!(p = lock_user(VERIFY_WRITE, arg1, sizeof(target_sigset_t), 0)))
8566                     goto efault;
8567                 host_to_target_old_sigset(p, &set);
8568                 unlock_user(p, arg1, sizeof(target_sigset_t));
8569             }
8570         }
8571         break;
8572 #endif
8573     case TARGET_NR_rt_sigpending:
8574         {
8575             sigset_t set;
8576
8577             /* Yes, this check is >, not != like most. We follow the kernel's
8578              * logic and it does it like this because it implements
8579              * NR_sigpending through the same code path, and in that case
8580              * the old_sigset_t is smaller in size.
8581              */
8582             if (arg2 > sizeof(target_sigset_t)) {
8583                 ret = -TARGET_EINVAL;
8584                 break;
8585             }
8586
8587             ret = get_errno(sigpending(&set));
8588             if (!is_error(ret)) {
8589                 if (!(p = lock_user(VERIFY_WRITE, arg1, sizeof(target_sigset_t), 0)))
8590                     goto efault;
8591                 host_to_target_sigset(p, &set);
8592                 unlock_user(p, arg1, sizeof(target_sigset_t));
8593             }
8594         }
8595         break;
8596 #ifdef TARGET_NR_sigsuspend
8597     case TARGET_NR_sigsuspend:
8598         {
8599             TaskState *ts = cpu->opaque;
8600 #if defined(TARGET_ALPHA)
8601             abi_ulong mask = arg1;
8602             target_to_host_old_sigset(&ts->sigsuspend_mask, &mask);
8603 #else
8604             if (!(p = lock_user(VERIFY_READ, arg1, sizeof(target_sigset_t), 1)))
8605                 goto efault;
8606             target_to_host_old_sigset(&ts->sigsuspend_mask, p);
8607             unlock_user(p, arg1, 0);
8608 #endif
8609             ret = get_errno(safe_rt_sigsuspend(&ts->sigsuspend_mask,
8610                                                SIGSET_T_SIZE));
8611             if (ret != -TARGET_ERESTARTSYS) {
8612                 ts->in_sigsuspend = 1;
8613             }
8614         }
8615         break;
8616 #endif
8617     case TARGET_NR_rt_sigsuspend:
8618         {
8619             TaskState *ts = cpu->opaque;
8620
8621             if (arg2 != sizeof(target_sigset_t)) {
8622                 ret = -TARGET_EINVAL;
8623                 break;
8624             }
8625             if (!(p = lock_user(VERIFY_READ, arg1, sizeof(target_sigset_t), 1)))
8626                 goto efault;
8627             target_to_host_sigset(&ts->sigsuspend_mask, p);
8628             unlock_user(p, arg1, 0);
8629             ret = get_errno(safe_rt_sigsuspend(&ts->sigsuspend_mask,
8630                                                SIGSET_T_SIZE));
8631             if (ret != -TARGET_ERESTARTSYS) {
8632                 ts->in_sigsuspend = 1;
8633             }
8634         }
8635         break;
8636     case TARGET_NR_rt_sigtimedwait:
8637         {
8638             sigset_t set;
8639             struct timespec uts, *puts;
8640             siginfo_t uinfo;
8641
8642             if (arg4 != sizeof(target_sigset_t)) {
8643                 ret = -TARGET_EINVAL;
8644                 break;
8645             }
8646
8647             if (!(p = lock_user(VERIFY_READ, arg1, sizeof(target_sigset_t), 1)))
8648                 goto efault;
8649             target_to_host_sigset(&set, p);
8650             unlock_user(p, arg1, 0);
8651             if (arg3) {
8652                 puts = &uts;
8653                 target_to_host_timespec(puts, arg3);
8654             } else {
8655                 puts = NULL;
8656             }
8657             ret = get_errno(safe_rt_sigtimedwait(&set, &uinfo, puts,
8658                                                  SIGSET_T_SIZE));
8659             if (!is_error(ret)) {
8660                 if (arg2) {
8661                     p = lock_user(VERIFY_WRITE, arg2, sizeof(target_siginfo_t),
8662                                   0);
8663                     if (!p) {
8664                         goto efault;
8665                     }
8666                     host_to_target_siginfo(p, &uinfo);
8667                     unlock_user(p, arg2, sizeof(target_siginfo_t));
8668                 }
8669                 ret = host_to_target_signal(ret);
8670             }
8671         }
8672         break;
8673     case TARGET_NR_rt_sigqueueinfo:
8674         {
8675             siginfo_t uinfo;
8676
8677             p = lock_user(VERIFY_READ, arg3, sizeof(target_siginfo_t), 1);
8678             if (!p) {
8679                 goto efault;
8680             }
8681             target_to_host_siginfo(&uinfo, p);
8682             unlock_user(p, arg1, 0);
8683             ret = get_errno(sys_rt_sigqueueinfo(arg1, arg2, &uinfo));
8684         }
8685         break;
8686 #ifdef TARGET_NR_sigreturn
8687     case TARGET_NR_sigreturn:
8688         if (block_signals()) {
8689             ret = -TARGET_ERESTARTSYS;
8690         } else {
8691             ret = do_sigreturn(cpu_env);
8692         }
8693         break;
8694 #endif
8695     case TARGET_NR_rt_sigreturn:
8696         if (block_signals()) {
8697             ret = -TARGET_ERESTARTSYS;
8698         } else {
8699             ret = do_rt_sigreturn(cpu_env);
8700         }
8701         break;
8702     case TARGET_NR_sethostname:
8703         if (!(p = lock_user_string(arg1)))
8704             goto efault;
8705         ret = get_errno(sethostname(p, arg2));
8706         unlock_user(p, arg1, 0);
8707         break;
8708     case TARGET_NR_setrlimit:
8709         {
8710             int resource = target_to_host_resource(arg1);
8711             struct target_rlimit *target_rlim;
8712             struct rlimit rlim;
8713             if (!lock_user_struct(VERIFY_READ, target_rlim, arg2, 1))
8714                 goto efault;
8715             rlim.rlim_cur = target_to_host_rlim(target_rlim->rlim_cur);
8716             rlim.rlim_max = target_to_host_rlim(target_rlim->rlim_max);
8717             unlock_user_struct(target_rlim, arg2, 0);
8718             ret = get_errno(setrlimit(resource, &rlim));
8719         }
8720         break;
8721     case TARGET_NR_getrlimit:
8722         {
8723             int resource = target_to_host_resource(arg1);
8724             struct target_rlimit *target_rlim;
8725             struct rlimit rlim;
8726
8727             ret = get_errno(getrlimit(resource, &rlim));
8728             if (!is_error(ret)) {
8729                 if (!lock_user_struct(VERIFY_WRITE, target_rlim, arg2, 0))
8730                     goto efault;
8731                 target_rlim->rlim_cur = host_to_target_rlim(rlim.rlim_cur);
8732                 target_rlim->rlim_max = host_to_target_rlim(rlim.rlim_max);
8733                 unlock_user_struct(target_rlim, arg2, 1);
8734             }
8735         }
8736         break;
8737     case TARGET_NR_getrusage:
8738         {
8739             struct rusage rusage;
8740             ret = get_errno(getrusage(arg1, &rusage));
8741             if (!is_error(ret)) {
8742                 ret = host_to_target_rusage(arg2, &rusage);
8743             }
8744         }
8745         break;
8746     case TARGET_NR_gettimeofday:
8747         {
8748             struct timeval tv;
8749             ret = get_errno(gettimeofday(&tv, NULL));
8750             if (!is_error(ret)) {
8751                 if (copy_to_user_timeval(arg1, &tv))
8752                     goto efault;
8753             }
8754         }
8755         break;
8756     case TARGET_NR_settimeofday:
8757         {
8758             struct timeval tv, *ptv = NULL;
8759             struct timezone tz, *ptz = NULL;
8760
8761             if (arg1) {
8762                 if (copy_from_user_timeval(&tv, arg1)) {
8763                     goto efault;
8764                 }
8765                 ptv = &tv;
8766             }
8767
8768             if (arg2) {
8769                 if (copy_from_user_timezone(&tz, arg2)) {
8770                     goto efault;
8771                 }
8772                 ptz = &tz;
8773             }
8774
8775             ret = get_errno(settimeofday(ptv, ptz));
8776         }
8777         break;
8778 #if defined(TARGET_NR_select)
8779     case TARGET_NR_select:
8780 #if defined(TARGET_WANT_NI_OLD_SELECT)
8781         /* some architectures used to have old_select here
8782          * but now ENOSYS it.
8783          */
8784         ret = -TARGET_ENOSYS;
8785 #elif defined(TARGET_WANT_OLD_SYS_SELECT)
8786         ret = do_old_select(arg1);
8787 #else
8788         ret = do_select(arg1, arg2, arg3, arg4, arg5);
8789 #endif
8790         break;
8791 #endif
8792 #ifdef TARGET_NR_pselect6
8793     case TARGET_NR_pselect6:
8794         {
8795             abi_long rfd_addr, wfd_addr, efd_addr, n, ts_addr;
8796             fd_set rfds, wfds, efds;
8797             fd_set *rfds_ptr, *wfds_ptr, *efds_ptr;
8798             struct timespec ts, *ts_ptr;
8799
8800             /*
8801              * The 6th arg is actually two args smashed together,
8802              * so we cannot use the C library.
8803              */
8804             sigset_t set;
8805             struct {
8806                 sigset_t *set;
8807                 size_t size;
8808             } sig, *sig_ptr;
8809
8810             abi_ulong arg_sigset, arg_sigsize, *arg7;
8811             target_sigset_t *target_sigset;
8812
8813             n = arg1;
8814             rfd_addr = arg2;
8815             wfd_addr = arg3;
8816             efd_addr = arg4;
8817             ts_addr = arg5;
8818
8819             ret = copy_from_user_fdset_ptr(&rfds, &rfds_ptr, rfd_addr, n);
8820             if (ret) {
8821                 goto fail;
8822             }
8823             ret = copy_from_user_fdset_ptr(&wfds, &wfds_ptr, wfd_addr, n);
8824             if (ret) {
8825                 goto fail;
8826             }
8827             ret = copy_from_user_fdset_ptr(&efds, &efds_ptr, efd_addr, n);
8828             if (ret) {
8829                 goto fail;
8830             }
8831
8832             /*
8833              * This takes a timespec, and not a timeval, so we cannot
8834              * use the do_select() helper ...
8835              */
8836             if (ts_addr) {
8837                 if (target_to_host_timespec(&ts, ts_addr)) {
8838                     goto efault;
8839                 }
8840                 ts_ptr = &ts;
8841             } else {
8842                 ts_ptr = NULL;
8843             }
8844
8845             /* Extract the two packed args for the sigset */
8846             if (arg6) {
8847                 sig_ptr = &sig;
8848                 sig.size = SIGSET_T_SIZE;
8849
8850                 arg7 = lock_user(VERIFY_READ, arg6, sizeof(*arg7) * 2, 1);
8851                 if (!arg7) {
8852                     goto efault;
8853                 }
8854                 arg_sigset = tswapal(arg7[0]);
8855                 arg_sigsize = tswapal(arg7[1]);
8856                 unlock_user(arg7, arg6, 0);
8857
8858                 if (arg_sigset) {
8859                     sig.set = &set;
8860                     if (arg_sigsize != sizeof(*target_sigset)) {
8861                         /* Like the kernel, we enforce correct size sigsets */
8862                         ret = -TARGET_EINVAL;
8863                         goto fail;
8864                     }
8865                     target_sigset = lock_user(VERIFY_READ, arg_sigset,
8866                                               sizeof(*target_sigset), 1);
8867                     if (!target_sigset) {
8868                         goto efault;
8869                     }
8870                     target_to_host_sigset(&set, target_sigset);
8871                     unlock_user(target_sigset, arg_sigset, 0);
8872                 } else {
8873                     sig.set = NULL;
8874                 }
8875             } else {
8876                 sig_ptr = NULL;
8877             }
8878
8879             ret = get_errno(safe_pselect6(n, rfds_ptr, wfds_ptr, efds_ptr,
8880                                           ts_ptr, sig_ptr));
8881
8882             if (!is_error(ret)) {
8883                 if (rfd_addr && copy_to_user_fdset(rfd_addr, &rfds, n))
8884                     goto efault;
8885                 if (wfd_addr && copy_to_user_fdset(wfd_addr, &wfds, n))
8886                     goto efault;
8887                 if (efd_addr && copy_to_user_fdset(efd_addr, &efds, n))
8888                     goto efault;
8889
8890                 if (ts_addr && host_to_target_timespec(ts_addr, &ts))
8891                     goto efault;
8892             }
8893         }
8894         break;
8895 #endif
8896 #ifdef TARGET_NR_symlink
8897     case TARGET_NR_symlink:
8898         {
8899             void *p2;
8900             p = lock_user_string(arg1);
8901             p2 = lock_user_string(arg2);
8902             if (!p || !p2)
8903                 ret = -TARGET_EFAULT;
8904             else
8905                 ret = get_errno(symlink(p, p2));
8906             unlock_user(p2, arg2, 0);
8907             unlock_user(p, arg1, 0);
8908         }
8909         break;
8910 #endif
8911 #if defined(TARGET_NR_symlinkat)
8912     case TARGET_NR_symlinkat:
8913         {
8914             void *p2;
8915             p  = lock_user_string(arg1);
8916             p2 = lock_user_string(arg3);
8917             if (!p || !p2)
8918                 ret = -TARGET_EFAULT;
8919             else
8920                 ret = get_errno(symlinkat(p, arg2, p2));
8921             unlock_user(p2, arg3, 0);
8922             unlock_user(p, arg1, 0);
8923         }
8924         break;
8925 #endif
8926 #ifdef TARGET_NR_oldlstat
8927     case TARGET_NR_oldlstat:
8928         goto unimplemented;
8929 #endif
8930 #ifdef TARGET_NR_readlink
8931     case TARGET_NR_readlink:
8932         {
8933             void *p2;
8934             p = lock_user_string(arg1);
8935             p2 = lock_user(VERIFY_WRITE, arg2, arg3, 0);
8936             if (!p || !p2) {
8937                 ret = -TARGET_EFAULT;
8938             } else if (!arg3) {
8939                 /* Short circuit this for the magic exe check. */
8940                 ret = -TARGET_EINVAL;
8941             } else if (is_proc_myself((const char *)p, "exe")) {
8942                 char real[PATH_MAX], *temp;
8943                 temp = realpath(exec_path, real);
8944                 /* Return value is # of bytes that we wrote to the buffer. */
8945                 if (temp == NULL) {
8946                     ret = get_errno(-1);
8947                 } else {
8948                     /* Don't worry about sign mismatch as earlier mapping
8949                      * logic would have thrown a bad address error. */
8950                     ret = MIN(strlen(real), arg3);
8951                     /* We cannot NUL terminate the string. */
8952                     memcpy(p2, real, ret);
8953                 }
8954             } else {
8955                 ret = get_errno(readlink(path(p), p2, arg3));
8956             }
8957             unlock_user(p2, arg2, ret);
8958             unlock_user(p, arg1, 0);
8959         }
8960         break;
8961 #endif
8962 #if defined(TARGET_NR_readlinkat)
8963     case TARGET_NR_readlinkat:
8964         {
8965             void *p2;
8966             p  = lock_user_string(arg2);
8967             p2 = lock_user(VERIFY_WRITE, arg3, arg4, 0);
8968             if (!p || !p2) {
8969                 ret = -TARGET_EFAULT;
8970             } else if (is_proc_myself((const char *)p, "exe")) {
8971                 char real[PATH_MAX], *temp;
8972                 temp = realpath(exec_path, real);
8973                 ret = temp == NULL ? get_errno(-1) : strlen(real) ;
8974                 snprintf((char *)p2, arg4, "%s", real);
8975             } else {
8976                 ret = get_errno(readlinkat(arg1, path(p), p2, arg4));
8977             }
8978             unlock_user(p2, arg3, ret);
8979             unlock_user(p, arg2, 0);
8980         }
8981         break;
8982 #endif
8983 #ifdef TARGET_NR_uselib
8984     case TARGET_NR_uselib:
8985         goto unimplemented;
8986 #endif
8987 #ifdef TARGET_NR_swapon
8988     case TARGET_NR_swapon:
8989         if (!(p = lock_user_string(arg1)))
8990             goto efault;
8991         ret = get_errno(swapon(p, arg2));
8992         unlock_user(p, arg1, 0);
8993         break;
8994 #endif
8995     case TARGET_NR_reboot:
8996         if (arg3 == LINUX_REBOOT_CMD_RESTART2) {
8997            /* arg4 must be ignored in all other cases */
8998            p = lock_user_string(arg4);
8999            if (!p) {
9000               goto efault;
9001            }
9002            ret = get_errno(reboot(arg1, arg2, arg3, p));
9003            unlock_user(p, arg4, 0);
9004         } else {
9005            ret = get_errno(reboot(arg1, arg2, arg3, NULL));
9006         }
9007         break;
9008 #ifdef TARGET_NR_readdir
9009     case TARGET_NR_readdir:
9010         goto unimplemented;
9011 #endif
9012 #ifdef TARGET_NR_mmap
9013     case TARGET_NR_mmap:
9014 #if (defined(TARGET_I386) && defined(TARGET_ABI32)) || \
9015     (defined(TARGET_ARM) && defined(TARGET_ABI32)) || \
9016     defined(TARGET_M68K) || defined(TARGET_CRIS) || defined(TARGET_MICROBLAZE) \
9017     || defined(TARGET_S390X)
9018         {
9019             abi_ulong *v;
9020             abi_ulong v1, v2, v3, v4, v5, v6;
9021             if (!(v = lock_user(VERIFY_READ, arg1, 6 * sizeof(abi_ulong), 1)))
9022                 goto efault;
9023             v1 = tswapal(v[0]);
9024             v2 = tswapal(v[1]);
9025             v3 = tswapal(v[2]);
9026             v4 = tswapal(v[3]);
9027             v5 = tswapal(v[4]);
9028             v6 = tswapal(v[5]);
9029             unlock_user(v, arg1, 0);
9030             ret = get_errno(target_mmap(v1, v2, v3,
9031                                         target_to_host_bitmask(v4, mmap_flags_tbl),
9032                                         v5, v6));
9033         }
9034 #else
9035         ret = get_errno(target_mmap(arg1, arg2, arg3,
9036                                     target_to_host_bitmask(arg4, mmap_flags_tbl),
9037                                     arg5,
9038                                     arg6));
9039 #endif
9040         break;
9041 #endif
9042 #ifdef TARGET_NR_mmap2
9043     case TARGET_NR_mmap2:
9044 #ifndef MMAP_SHIFT
9045 #define MMAP_SHIFT 12
9046 #endif
9047         ret = get_errno(target_mmap(arg1, arg2, arg3,
9048                                     target_to_host_bitmask(arg4, mmap_flags_tbl),
9049                                     arg5,
9050                                     arg6 << MMAP_SHIFT));
9051         break;
9052 #endif
9053     case TARGET_NR_munmap:
9054         ret = get_errno(target_munmap(arg1, arg2));
9055         break;
9056     case TARGET_NR_mprotect:
9057         {
9058             TaskState *ts = cpu->opaque;
9059             /* Special hack to detect libc making the stack executable.  */
9060             if ((arg3 & PROT_GROWSDOWN)
9061                 && arg1 >= ts->info->stack_limit
9062                 && arg1 <= ts->info->start_stack) {
9063                 arg3 &= ~PROT_GROWSDOWN;
9064                 arg2 = arg2 + arg1 - ts->info->stack_limit;
9065                 arg1 = ts->info->stack_limit;
9066             }
9067         }
9068         ret = get_errno(target_mprotect(arg1, arg2, arg3));
9069         break;
9070 #ifdef TARGET_NR_mremap
9071     case TARGET_NR_mremap:
9072         ret = get_errno(target_mremap(arg1, arg2, arg3, arg4, arg5));
9073         break;
9074 #endif
9075         /* ??? msync/mlock/munlock are broken for softmmu.  */
9076 #ifdef TARGET_NR_msync
9077     case TARGET_NR_msync:
9078         ret = get_errno(msync(g2h(arg1), arg2, arg3));
9079         break;
9080 #endif
9081 #ifdef TARGET_NR_mlock
9082     case TARGET_NR_mlock:
9083         ret = get_errno(mlock(g2h(arg1), arg2));
9084         break;
9085 #endif
9086 #ifdef TARGET_NR_munlock
9087     case TARGET_NR_munlock:
9088         ret = get_errno(munlock(g2h(arg1), arg2));
9089         break;
9090 #endif
9091 #ifdef TARGET_NR_mlockall
9092     case TARGET_NR_mlockall:
9093         ret = get_errno(mlockall(target_to_host_mlockall_arg(arg1)));
9094         break;
9095 #endif
9096 #ifdef TARGET_NR_munlockall
9097     case TARGET_NR_munlockall:
9098         ret = get_errno(munlockall());
9099         break;
9100 #endif
9101     case TARGET_NR_truncate:
9102         if (!(p = lock_user_string(arg1)))
9103             goto efault;
9104         ret = get_errno(truncate(p, arg2));
9105         unlock_user(p, arg1, 0);
9106         break;
9107     case TARGET_NR_ftruncate:
9108         ret = get_errno(ftruncate(arg1, arg2));
9109         break;
9110     case TARGET_NR_fchmod:
9111         ret = get_errno(fchmod(arg1, arg2));
9112         break;
9113 #if defined(TARGET_NR_fchmodat)
9114     case TARGET_NR_fchmodat:
9115         if (!(p = lock_user_string(arg2)))
9116             goto efault;
9117         ret = get_errno(fchmodat(arg1, p, arg3, 0));
9118         unlock_user(p, arg2, 0);
9119         break;
9120 #endif
9121     case TARGET_NR_getpriority:
9122         /* Note that negative values are valid for getpriority, so we must
9123            differentiate based on errno settings.  */
9124         errno = 0;
9125         ret = getpriority(arg1, arg2);
9126         if (ret == -1 && errno != 0) {
9127             ret = -host_to_target_errno(errno);
9128             break;
9129         }
9130 #ifdef TARGET_ALPHA
9131         /* Return value is the unbiased priority.  Signal no error.  */
9132         ((CPUAlphaState *)cpu_env)->ir[IR_V0] = 0;
9133 #else
9134         /* Return value is a biased priority to avoid negative numbers.  */
9135         ret = 20 - ret;
9136 #endif
9137         break;
9138     case TARGET_NR_setpriority:
9139         ret = get_errno(setpriority(arg1, arg2, arg3));
9140         break;
9141 #ifdef TARGET_NR_profil
9142     case TARGET_NR_profil:
9143         goto unimplemented;
9144 #endif
9145     case TARGET_NR_statfs:
9146         if (!(p = lock_user_string(arg1)))
9147             goto efault;
9148         ret = get_errno(statfs(path(p), &stfs));
9149         unlock_user(p, arg1, 0);
9150     convert_statfs:
9151         if (!is_error(ret)) {
9152             struct target_statfs *target_stfs;
9153
9154             if (!lock_user_struct(VERIFY_WRITE, target_stfs, arg2, 0))
9155                 goto efault;
9156             __put_user(stfs.f_type, &target_stfs->f_type);
9157             __put_user(stfs.f_bsize, &target_stfs->f_bsize);
9158             __put_user(stfs.f_blocks, &target_stfs->f_blocks);
9159             __put_user(stfs.f_bfree, &target_stfs->f_bfree);
9160             __put_user(stfs.f_bavail, &target_stfs->f_bavail);
9161             __put_user(stfs.f_files, &target_stfs->f_files);
9162             __put_user(stfs.f_ffree, &target_stfs->f_ffree);
9163             __put_user(stfs.f_fsid.__val[0], &target_stfs->f_fsid.val[0]);
9164             __put_user(stfs.f_fsid.__val[1], &target_stfs->f_fsid.val[1]);
9165             __put_user(stfs.f_namelen, &target_stfs->f_namelen);
9166             __put_user(stfs.f_frsize, &target_stfs->f_frsize);
9167             memset(target_stfs->f_spare, 0, sizeof(target_stfs->f_spare));
9168             unlock_user_struct(target_stfs, arg2, 1);
9169         }
9170         break;
9171     case TARGET_NR_fstatfs:
9172         ret = get_errno(fstatfs(arg1, &stfs));
9173         goto convert_statfs;
9174 #ifdef TARGET_NR_statfs64
9175     case TARGET_NR_statfs64:
9176         if (!(p = lock_user_string(arg1)))
9177             goto efault;
9178         ret = get_errno(statfs(path(p), &stfs));
9179         unlock_user(p, arg1, 0);
9180     convert_statfs64:
9181         if (!is_error(ret)) {
9182             struct target_statfs64 *target_stfs;
9183
9184             if (!lock_user_struct(VERIFY_WRITE, target_stfs, arg3, 0))
9185                 goto efault;
9186             __put_user(stfs.f_type, &target_stfs->f_type);
9187             __put_user(stfs.f_bsize, &target_stfs->f_bsize);
9188             __put_user(stfs.f_blocks, &target_stfs->f_blocks);
9189             __put_user(stfs.f_bfree, &target_stfs->f_bfree);
9190             __put_user(stfs.f_bavail, &target_stfs->f_bavail);
9191             __put_user(stfs.f_files, &target_stfs->f_files);
9192             __put_user(stfs.f_ffree, &target_stfs->f_ffree);
9193             __put_user(stfs.f_fsid.__val[0], &target_stfs->f_fsid.val[0]);
9194             __put_user(stfs.f_fsid.__val[1], &target_stfs->f_fsid.val[1]);
9195             __put_user(stfs.f_namelen, &target_stfs->f_namelen);
9196             __put_user(stfs.f_frsize, &target_stfs->f_frsize);
9197             memset(target_stfs->f_spare, 0, sizeof(target_stfs->f_spare));
9198             unlock_user_struct(target_stfs, arg3, 1);
9199         }
9200         break;
9201     case TARGET_NR_fstatfs64:
9202         ret = get_errno(fstatfs(arg1, &stfs));
9203         goto convert_statfs64;
9204 #endif
9205 #ifdef TARGET_NR_ioperm
9206     case TARGET_NR_ioperm:
9207         goto unimplemented;
9208 #endif
9209 #ifdef TARGET_NR_socketcall
9210     case TARGET_NR_socketcall:
9211         ret = do_socketcall(arg1, arg2);
9212         break;
9213 #endif
9214 #ifdef TARGET_NR_accept
9215     case TARGET_NR_accept:
9216         ret = do_accept4(arg1, arg2, arg3, 0);
9217         break;
9218 #endif
9219 #ifdef TARGET_NR_accept4
9220     case TARGET_NR_accept4:
9221         ret = do_accept4(arg1, arg2, arg3, arg4);
9222         break;
9223 #endif
9224 #ifdef TARGET_NR_bind
9225     case TARGET_NR_bind:
9226         ret = do_bind(arg1, arg2, arg3);
9227         break;
9228 #endif
9229 #ifdef TARGET_NR_connect
9230     case TARGET_NR_connect:
9231         ret = do_connect(arg1, arg2, arg3);
9232         break;
9233 #endif
9234 #ifdef TARGET_NR_getpeername
9235     case TARGET_NR_getpeername:
9236         ret = do_getpeername(arg1, arg2, arg3);
9237         break;
9238 #endif
9239 #ifdef TARGET_NR_getsockname
9240     case TARGET_NR_getsockname:
9241         ret = do_getsockname(arg1, arg2, arg3);
9242         break;
9243 #endif
9244 #ifdef TARGET_NR_getsockopt
9245     case TARGET_NR_getsockopt:
9246         ret = do_getsockopt(arg1, arg2, arg3, arg4, arg5);
9247         break;
9248 #endif
9249 #ifdef TARGET_NR_listen
9250     case TARGET_NR_listen:
9251         ret = get_errno(listen(arg1, arg2));
9252         break;
9253 #endif
9254 #ifdef TARGET_NR_recv
9255     case TARGET_NR_recv:
9256         ret = do_recvfrom(arg1, arg2, arg3, arg4, 0, 0);
9257         break;
9258 #endif
9259 #ifdef TARGET_NR_recvfrom
9260     case TARGET_NR_recvfrom:
9261         ret = do_recvfrom(arg1, arg2, arg3, arg4, arg5, arg6);
9262         break;
9263 #endif
9264 #ifdef TARGET_NR_recvmsg
9265     case TARGET_NR_recvmsg:
9266         ret = do_sendrecvmsg(arg1, arg2, arg3, 0);
9267         break;
9268 #endif
9269 #ifdef TARGET_NR_send
9270     case TARGET_NR_send:
9271         ret = do_sendto(arg1, arg2, arg3, arg4, 0, 0);
9272         break;
9273 #endif
9274 #ifdef TARGET_NR_sendmsg
9275     case TARGET_NR_sendmsg:
9276         ret = do_sendrecvmsg(arg1, arg2, arg3, 1);
9277         break;
9278 #endif
9279 #ifdef TARGET_NR_sendmmsg
9280     case TARGET_NR_sendmmsg:
9281         ret = do_sendrecvmmsg(arg1, arg2, arg3, arg4, 1);
9282         break;
9283     case TARGET_NR_recvmmsg:
9284         ret = do_sendrecvmmsg(arg1, arg2, arg3, arg4, 0);
9285         break;
9286 #endif
9287 #ifdef TARGET_NR_sendto
9288     case TARGET_NR_sendto:
9289         ret = do_sendto(arg1, arg2, arg3, arg4, arg5, arg6);
9290         break;
9291 #endif
9292 #ifdef TARGET_NR_shutdown
9293     case TARGET_NR_shutdown:
9294         ret = get_errno(shutdown(arg1, arg2));
9295         break;
9296 #endif
9297 #if defined(TARGET_NR_getrandom) && defined(__NR_getrandom)
9298     case TARGET_NR_getrandom:
9299         p = lock_user(VERIFY_WRITE, arg1, arg2, 0);
9300         if (!p) {
9301             goto efault;
9302         }
9303         ret = get_errno(getrandom(p, arg2, arg3));
9304         unlock_user(p, arg1, ret);
9305         break;
9306 #endif
9307 #ifdef TARGET_NR_socket
9308     case TARGET_NR_socket:
9309         ret = do_socket(arg1, arg2, arg3);
9310         fd_trans_unregister(ret);
9311         break;
9312 #endif
9313 #ifdef TARGET_NR_socketpair
9314     case TARGET_NR_socketpair:
9315         ret = do_socketpair(arg1, arg2, arg3, arg4);
9316         break;
9317 #endif
9318 #ifdef TARGET_NR_setsockopt
9319     case TARGET_NR_setsockopt:
9320         ret = do_setsockopt(arg1, arg2, arg3, arg4, (socklen_t) arg5);
9321         break;
9322 #endif
9323
9324     case TARGET_NR_syslog:
9325         if (!(p = lock_user_string(arg2)))
9326             goto efault;
9327         ret = get_errno(sys_syslog((int)arg1, p, (int)arg3));
9328         unlock_user(p, arg2, 0);
9329         break;
9330
9331     case TARGET_NR_setitimer:
9332         {
9333             struct itimerval value, ovalue, *pvalue;
9334
9335             if (arg2) {
9336                 pvalue = &value;
9337                 if (copy_from_user_timeval(&pvalue->it_interval, arg2)
9338                     || copy_from_user_timeval(&pvalue->it_value,
9339                                               arg2 + sizeof(struct target_timeval)))
9340                     goto efault;
9341             } else {
9342                 pvalue = NULL;
9343             }
9344             ret = get_errno(setitimer(arg1, pvalue, &ovalue));
9345             if (!is_error(ret) && arg3) {
9346                 if (copy_to_user_timeval(arg3,
9347                                          &ovalue.it_interval)
9348                     || copy_to_user_timeval(arg3 + sizeof(struct target_timeval),
9349                                             &ovalue.it_value))
9350                     goto efault;
9351             }
9352         }
9353         break;
9354     case TARGET_NR_getitimer:
9355         {
9356             struct itimerval value;
9357
9358             ret = get_errno(getitimer(arg1, &value));
9359             if (!is_error(ret) && arg2) {
9360                 if (copy_to_user_timeval(arg2,
9361                                          &value.it_interval)
9362                     || copy_to_user_timeval(arg2 + sizeof(struct target_timeval),
9363                                             &value.it_value))
9364                     goto efault;
9365             }
9366         }
9367         break;
9368 #ifdef TARGET_NR_stat
9369     case TARGET_NR_stat:
9370         if (!(p = lock_user_string(arg1)))
9371             goto efault;
9372         ret = get_errno(stat(path(p), &st));
9373         unlock_user(p, arg1, 0);
9374         goto do_stat;
9375 #endif
9376 #ifdef TARGET_NR_lstat
9377     case TARGET_NR_lstat:
9378         if (!(p = lock_user_string(arg1)))
9379             goto efault;
9380         ret = get_errno(lstat(path(p), &st));
9381         unlock_user(p, arg1, 0);
9382         goto do_stat;
9383 #endif
9384     case TARGET_NR_fstat:
9385         {
9386             ret = get_errno(fstat(arg1, &st));
9387 #if defined(TARGET_NR_stat) || defined(TARGET_NR_lstat)
9388         do_stat:
9389 #endif
9390             if (!is_error(ret)) {
9391                 struct target_stat *target_st;
9392
9393                 if (!lock_user_struct(VERIFY_WRITE, target_st, arg2, 0))
9394                     goto efault;
9395                 memset(target_st, 0, sizeof(*target_st));
9396                 __put_user(st.st_dev, &target_st->st_dev);
9397                 __put_user(st.st_ino, &target_st->st_ino);
9398                 __put_user(st.st_mode, &target_st->st_mode);
9399                 __put_user(st.st_uid, &target_st->st_uid);
9400                 __put_user(st.st_gid, &target_st->st_gid);
9401                 __put_user(st.st_nlink, &target_st->st_nlink);
9402                 __put_user(st.st_rdev, &target_st->st_rdev);
9403                 __put_user(st.st_size, &target_st->st_size);
9404                 __put_user(st.st_blksize, &target_st->st_blksize);
9405                 __put_user(st.st_blocks, &target_st->st_blocks);
9406                 __put_user(st.st_atime, &target_st->target_st_atime);
9407                 __put_user(st.st_mtime, &target_st->target_st_mtime);
9408                 __put_user(st.st_ctime, &target_st->target_st_ctime);
9409                 unlock_user_struct(target_st, arg2, 1);
9410             }
9411         }
9412         break;
9413 #ifdef TARGET_NR_olduname
9414     case TARGET_NR_olduname:
9415         goto unimplemented;
9416 #endif
9417 #ifdef TARGET_NR_iopl
9418     case TARGET_NR_iopl:
9419         goto unimplemented;
9420 #endif
9421     case TARGET_NR_vhangup:
9422         ret = get_errno(vhangup());
9423         break;
9424 #ifdef TARGET_NR_idle
9425     case TARGET_NR_idle:
9426         goto unimplemented;
9427 #endif
9428 #ifdef TARGET_NR_syscall
9429     case TARGET_NR_syscall:
9430         ret = do_syscall(cpu_env, arg1 & 0xffff, arg2, arg3, arg4, arg5,
9431                          arg6, arg7, arg8, 0);
9432         break;
9433 #endif
9434     case TARGET_NR_wait4:
9435         {
9436             int status;
9437             abi_long status_ptr = arg2;
9438             struct rusage rusage, *rusage_ptr;
9439             abi_ulong target_rusage = arg4;
9440             abi_long rusage_err;
9441             if (target_rusage)
9442                 rusage_ptr = &rusage;
9443             else
9444                 rusage_ptr = NULL;
9445             ret = get_errno(safe_wait4(arg1, &status, arg3, rusage_ptr));
9446             if (!is_error(ret)) {
9447                 if (status_ptr && ret) {
9448                     status = host_to_target_waitstatus(status);
9449                     if (put_user_s32(status, status_ptr))
9450                         goto efault;
9451                 }
9452                 if (target_rusage) {
9453                     rusage_err = host_to_target_rusage(target_rusage, &rusage);
9454                     if (rusage_err) {
9455                         ret = rusage_err;
9456                     }
9457                 }
9458             }
9459         }
9460         break;
9461 #ifdef TARGET_NR_swapoff
9462     case TARGET_NR_swapoff:
9463         if (!(p = lock_user_string(arg1)))
9464             goto efault;
9465         ret = get_errno(swapoff(p));
9466         unlock_user(p, arg1, 0);
9467         break;
9468 #endif
9469     case TARGET_NR_sysinfo:
9470         {
9471             struct target_sysinfo *target_value;
9472             struct sysinfo value;
9473             ret = get_errno(sysinfo(&value));
9474             if (!is_error(ret) && arg1)
9475             {
9476                 if (!lock_user_struct(VERIFY_WRITE, target_value, arg1, 0))
9477                     goto efault;
9478                 __put_user(value.uptime, &target_value->uptime);
9479                 __put_user(value.loads[0], &target_value->loads[0]);
9480                 __put_user(value.loads[1], &target_value->loads[1]);
9481                 __put_user(value.loads[2], &target_value->loads[2]);
9482                 __put_user(value.totalram, &target_value->totalram);
9483                 __put_user(value.freeram, &target_value->freeram);
9484                 __put_user(value.sharedram, &target_value->sharedram);
9485                 __put_user(value.bufferram, &target_value->bufferram);
9486                 __put_user(value.totalswap, &target_value->totalswap);
9487                 __put_user(value.freeswap, &target_value->freeswap);
9488                 __put_user(value.procs, &target_value->procs);
9489                 __put_user(value.totalhigh, &target_value->totalhigh);
9490                 __put_user(value.freehigh, &target_value->freehigh);
9491                 __put_user(value.mem_unit, &target_value->mem_unit);
9492                 unlock_user_struct(target_value, arg1, 1);
9493             }
9494         }
9495         break;
9496 #ifdef TARGET_NR_ipc
9497     case TARGET_NR_ipc:
9498         ret = do_ipc(cpu_env, arg1, arg2, arg3, arg4, arg5, arg6);
9499         break;
9500 #endif
9501 #ifdef TARGET_NR_semget
9502     case TARGET_NR_semget:
9503         ret = get_errno(semget(arg1, arg2, arg3));
9504         break;
9505 #endif
9506 #ifdef TARGET_NR_semop
9507     case TARGET_NR_semop:
9508         ret = do_semop(arg1, arg2, arg3);
9509         break;
9510 #endif
9511 #ifdef TARGET_NR_semctl
9512     case TARGET_NR_semctl:
9513         ret = do_semctl(arg1, arg2, arg3, arg4);
9514         break;
9515 #endif
9516 #ifdef TARGET_NR_msgctl
9517     case TARGET_NR_msgctl:
9518         ret = do_msgctl(arg1, arg2, arg3);
9519         break;
9520 #endif
9521 #ifdef TARGET_NR_msgget
9522     case TARGET_NR_msgget:
9523         ret = get_errno(msgget(arg1, arg2));
9524         break;
9525 #endif
9526 #ifdef TARGET_NR_msgrcv
9527     case TARGET_NR_msgrcv:
9528         ret = do_msgrcv(arg1, arg2, arg3, arg4, arg5);
9529         break;
9530 #endif
9531 #ifdef TARGET_NR_msgsnd
9532     case TARGET_NR_msgsnd:
9533         ret = do_msgsnd(arg1, arg2, arg3, arg4);
9534         break;
9535 #endif
9536 #ifdef TARGET_NR_shmget
9537     case TARGET_NR_shmget:
9538         ret = get_errno(shmget(arg1, arg2, arg3));
9539         break;
9540 #endif
9541 #ifdef TARGET_NR_shmctl
9542     case TARGET_NR_shmctl:
9543         ret = do_shmctl(arg1, arg2, arg3);
9544         break;
9545 #endif
9546 #ifdef TARGET_NR_shmat
9547     case TARGET_NR_shmat:
9548         ret = do_shmat(cpu_env, arg1, arg2, arg3);
9549         break;
9550 #endif
9551 #ifdef TARGET_NR_shmdt
9552     case TARGET_NR_shmdt:
9553         ret = do_shmdt(arg1);
9554         break;
9555 #endif
9556     case TARGET_NR_fsync:
9557         ret = get_errno(fsync(arg1));
9558         break;
9559     case TARGET_NR_clone:
9560         /* Linux manages to have three different orderings for its
9561          * arguments to clone(); the BACKWARDS and BACKWARDS2 defines
9562          * match the kernel's CONFIG_CLONE_* settings.
9563          * Microblaze is further special in that it uses a sixth
9564          * implicit argument to clone for the TLS pointer.
9565          */
9566 #if defined(TARGET_MICROBLAZE)
9567         ret = get_errno(do_fork(cpu_env, arg1, arg2, arg4, arg6, arg5));
9568 #elif defined(TARGET_CLONE_BACKWARDS)
9569         ret = get_errno(do_fork(cpu_env, arg1, arg2, arg3, arg4, arg5));
9570 #elif defined(TARGET_CLONE_BACKWARDS2)
9571         ret = get_errno(do_fork(cpu_env, arg2, arg1, arg3, arg5, arg4));
9572 #else
9573         ret = get_errno(do_fork(cpu_env, arg1, arg2, arg3, arg5, arg4));
9574 #endif
9575         break;
9576 #ifdef __NR_exit_group
9577         /* new thread calls */
9578     case TARGET_NR_exit_group:
9579 #ifdef TARGET_GPROF
9580         _mcleanup();
9581 #endif
9582         gdb_exit(cpu_env, arg1);
9583         ret = get_errno(exit_group(arg1));
9584         break;
9585 #endif
9586     case TARGET_NR_setdomainname:
9587         if (!(p = lock_user_string(arg1)))
9588             goto efault;
9589         ret = get_errno(setdomainname(p, arg2));
9590         unlock_user(p, arg1, 0);
9591         break;
9592     case TARGET_NR_uname:
9593         /* no need to transcode because we use the linux syscall */
9594         {
9595             struct new_utsname * buf;
9596
9597             if (!lock_user_struct(VERIFY_WRITE, buf, arg1, 0))
9598                 goto efault;
9599             ret = get_errno(sys_uname(buf));
9600             if (!is_error(ret)) {
9601                 /* Overwrite the native machine name with whatever is being
9602                    emulated. */
9603                 strcpy (buf->machine, cpu_to_uname_machine(cpu_env));
9604                 /* Allow the user to override the reported release.  */
9605                 if (qemu_uname_release && *qemu_uname_release) {
9606                     g_strlcpy(buf->release, qemu_uname_release,
9607                               sizeof(buf->release));
9608                 }
9609             }
9610             unlock_user_struct(buf, arg1, 1);
9611         }
9612         break;
9613 #ifdef TARGET_I386
9614     case TARGET_NR_modify_ldt:
9615         ret = do_modify_ldt(cpu_env, arg1, arg2, arg3);
9616         break;
9617 #if !defined(TARGET_X86_64)
9618     case TARGET_NR_vm86old:
9619         goto unimplemented;
9620     case TARGET_NR_vm86:
9621         ret = do_vm86(cpu_env, arg1, arg2);
9622         break;
9623 #endif
9624 #endif
9625     case TARGET_NR_adjtimex:
9626         {
9627             struct timex host_buf;
9628
9629             if (target_to_host_timex(&host_buf, arg1) != 0) {
9630                 goto efault;
9631             }
9632             ret = get_errno(adjtimex(&host_buf));
9633             if (!is_error(ret)) {
9634                 if (host_to_target_timex(arg1, &host_buf) != 0) {
9635                     goto efault;
9636                 }
9637             }
9638         }
9639         break;
9640 #ifdef TARGET_NR_create_module
9641     case TARGET_NR_create_module:
9642 #endif
9643     case TARGET_NR_init_module:
9644     case TARGET_NR_delete_module:
9645 #ifdef TARGET_NR_get_kernel_syms
9646     case TARGET_NR_get_kernel_syms:
9647 #endif
9648         goto unimplemented;
9649     case TARGET_NR_quotactl:
9650         goto unimplemented;
9651     case TARGET_NR_getpgid:
9652         ret = get_errno(getpgid(arg1));
9653         break;
9654     case TARGET_NR_fchdir:
9655         ret = get_errno(fchdir(arg1));
9656         break;
9657 #ifdef TARGET_NR_bdflush /* not on x86_64 */
9658     case TARGET_NR_bdflush:
9659         goto unimplemented;
9660 #endif
9661 #ifdef TARGET_NR_sysfs
9662     case TARGET_NR_sysfs:
9663         goto unimplemented;
9664 #endif
9665     case TARGET_NR_personality:
9666         ret = get_errno(personality(arg1));
9667         break;
9668 #ifdef TARGET_NR_afs_syscall
9669     case TARGET_NR_afs_syscall:
9670         goto unimplemented;
9671 #endif
9672 #ifdef TARGET_NR__llseek /* Not on alpha */
9673     case TARGET_NR__llseek:
9674         {
9675             int64_t res;
9676 #if !defined(__NR_llseek)
9677             res = lseek(arg1, ((uint64_t)arg2 << 32) | (abi_ulong)arg3, arg5);
9678             if (res == -1) {
9679                 ret = get_errno(res);
9680             } else {
9681                 ret = 0;
9682             }
9683 #else
9684             ret = get_errno(_llseek(arg1, arg2, arg3, &res, arg5));
9685 #endif
9686             if ((ret == 0) && put_user_s64(res, arg4)) {
9687                 goto efault;
9688             }
9689         }
9690         break;
9691 #endif
9692 #ifdef TARGET_NR_getdents
9693     case TARGET_NR_getdents:
9694 #ifdef __NR_getdents
9695 #if TARGET_ABI_BITS == 32 && HOST_LONG_BITS == 64
9696         {
9697             struct target_dirent *target_dirp;
9698             struct linux_dirent *dirp;
9699             abi_long count = arg3;
9700
9701             dirp = g_try_malloc(count);
9702             if (!dirp) {
9703                 ret = -TARGET_ENOMEM;
9704                 goto fail;
9705             }
9706
9707             ret = get_errno(sys_getdents(arg1, dirp, count));
9708             if (!is_error(ret)) {
9709                 struct linux_dirent *de;
9710                 struct target_dirent *tde;
9711                 int len = ret;
9712                 int reclen, treclen;
9713                 int count1, tnamelen;
9714
9715                 count1 = 0;
9716                 de = dirp;
9717                 if (!(target_dirp = lock_user(VERIFY_WRITE, arg2, count, 0)))
9718                     goto efault;
9719                 tde = target_dirp;
9720                 while (len > 0) {
9721                     reclen = de->d_reclen;
9722                     tnamelen = reclen - offsetof(struct linux_dirent, d_name);
9723                     assert(tnamelen >= 0);
9724                     treclen = tnamelen + offsetof(struct target_dirent, d_name);
9725                     assert(count1 + treclen <= count);
9726                     tde->d_reclen = tswap16(treclen);
9727                     tde->d_ino = tswapal(de->d_ino);
9728                     tde->d_off = tswapal(de->d_off);
9729                     memcpy(tde->d_name, de->d_name, tnamelen);
9730                     de = (struct linux_dirent *)((char *)de + reclen);
9731                     len -= reclen;
9732                     tde = (struct target_dirent *)((char *)tde + treclen);
9733                     count1 += treclen;
9734                 }
9735                 ret = count1;
9736                 unlock_user(target_dirp, arg2, ret);
9737             }
9738             g_free(dirp);
9739         }
9740 #else
9741         {
9742             struct linux_dirent *dirp;
9743             abi_long count = arg3;
9744
9745             if (!(dirp = lock_user(VERIFY_WRITE, arg2, count, 0)))
9746                 goto efault;
9747             ret = get_errno(sys_getdents(arg1, dirp, count));
9748             if (!is_error(ret)) {
9749                 struct linux_dirent *de;
9750                 int len = ret;
9751                 int reclen;
9752                 de = dirp;
9753                 while (len > 0) {
9754                     reclen = de->d_reclen;
9755                     if (reclen > len)
9756                         break;
9757                     de->d_reclen = tswap16(reclen);
9758                     tswapls(&de->d_ino);
9759                     tswapls(&de->d_off);
9760                     de = (struct linux_dirent *)((char *)de + reclen);
9761                     len -= reclen;
9762                 }
9763             }
9764             unlock_user(dirp, arg2, ret);
9765         }
9766 #endif
9767 #else
9768         /* Implement getdents in terms of getdents64 */
9769         {
9770             struct linux_dirent64 *dirp;
9771             abi_long count = arg3;
9772
9773             dirp = lock_user(VERIFY_WRITE, arg2, count, 0);
9774             if (!dirp) {
9775                 goto efault;
9776             }
9777             ret = get_errno(sys_getdents64(arg1, dirp, count));
9778             if (!is_error(ret)) {
9779                 /* Convert the dirent64 structs to target dirent.  We do this
9780                  * in-place, since we can guarantee that a target_dirent is no
9781                  * larger than a dirent64; however this means we have to be
9782                  * careful to read everything before writing in the new format.
9783                  */
9784                 struct linux_dirent64 *de;
9785                 struct target_dirent *tde;
9786                 int len = ret;
9787                 int tlen = 0;
9788
9789                 de = dirp;
9790                 tde = (struct target_dirent *)dirp;
9791                 while (len > 0) {
9792                     int namelen, treclen;
9793                     int reclen = de->d_reclen;
9794                     uint64_t ino = de->d_ino;
9795                     int64_t off = de->d_off;
9796                     uint8_t type = de->d_type;
9797
9798                     namelen = strlen(de->d_name);
9799                     treclen = offsetof(struct target_dirent, d_name)
9800                         + namelen + 2;
9801                     treclen = QEMU_ALIGN_UP(treclen, sizeof(abi_long));
9802
9803                     memmove(tde->d_name, de->d_name, namelen + 1);
9804                     tde->d_ino = tswapal(ino);
9805                     tde->d_off = tswapal(off);
9806                     tde->d_reclen = tswap16(treclen);
9807                     /* The target_dirent type is in what was formerly a padding
9808                      * byte at the end of the structure:
9809                      */
9810                     *(((char *)tde) + treclen - 1) = type;
9811
9812                     de = (struct linux_dirent64 *)((char *)de + reclen);
9813                     tde = (struct target_dirent *)((char *)tde + treclen);
9814                     len -= reclen;
9815                     tlen += treclen;
9816                 }
9817                 ret = tlen;
9818             }
9819             unlock_user(dirp, arg2, ret);
9820         }
9821 #endif
9822         break;
9823 #endif /* TARGET_NR_getdents */
9824 #if defined(TARGET_NR_getdents64) && defined(__NR_getdents64)
9825     case TARGET_NR_getdents64:
9826         {
9827             struct linux_dirent64 *dirp;
9828             abi_long count = arg3;
9829             if (!(dirp = lock_user(VERIFY_WRITE, arg2, count, 0)))
9830                 goto efault;
9831             ret = get_errno(sys_getdents64(arg1, dirp, count));
9832             if (!is_error(ret)) {
9833                 struct linux_dirent64 *de;
9834                 int len = ret;
9835                 int reclen;
9836                 de = dirp;
9837                 while (len > 0) {
9838                     reclen = de->d_reclen;
9839                     if (reclen > len)
9840                         break;
9841                     de->d_reclen = tswap16(reclen);
9842                     tswap64s((uint64_t *)&de->d_ino);
9843                     tswap64s((uint64_t *)&de->d_off);
9844                     de = (struct linux_dirent64 *)((char *)de + reclen);
9845                     len -= reclen;
9846                 }
9847             }
9848             unlock_user(dirp, arg2, ret);
9849         }
9850         break;
9851 #endif /* TARGET_NR_getdents64 */
9852 #if defined(TARGET_NR__newselect)
9853     case TARGET_NR__newselect:
9854         ret = do_select(arg1, arg2, arg3, arg4, arg5);
9855         break;
9856 #endif
9857 #if defined(TARGET_NR_poll) || defined(TARGET_NR_ppoll)
9858 # ifdef TARGET_NR_poll
9859     case TARGET_NR_poll:
9860 # endif
9861 # ifdef TARGET_NR_ppoll
9862     case TARGET_NR_ppoll:
9863 # endif
9864         {
9865             struct target_pollfd *target_pfd;
9866             unsigned int nfds = arg2;
9867             struct pollfd *pfd;
9868             unsigned int i;
9869
9870             pfd = NULL;
9871             target_pfd = NULL;
9872             if (nfds) {
9873                 if (nfds > (INT_MAX / sizeof(struct target_pollfd))) {
9874                     ret = -TARGET_EINVAL;
9875                     break;
9876                 }
9877
9878                 target_pfd = lock_user(VERIFY_WRITE, arg1,
9879                                        sizeof(struct target_pollfd) * nfds, 1);
9880                 if (!target_pfd) {
9881                     goto efault;
9882                 }
9883
9884                 pfd = alloca(sizeof(struct pollfd) * nfds);
9885                 for (i = 0; i < nfds; i++) {
9886                     pfd[i].fd = tswap32(target_pfd[i].fd);
9887                     pfd[i].events = tswap16(target_pfd[i].events);
9888                 }
9889             }
9890
9891             switch (num) {
9892 # ifdef TARGET_NR_ppoll
9893             case TARGET_NR_ppoll:
9894             {
9895                 struct timespec _timeout_ts, *timeout_ts = &_timeout_ts;
9896                 target_sigset_t *target_set;
9897                 sigset_t _set, *set = &_set;
9898
9899                 if (arg3) {
9900                     if (target_to_host_timespec(timeout_ts, arg3)) {
9901                         unlock_user(target_pfd, arg1, 0);
9902                         goto efault;
9903                     }
9904                 } else {
9905                     timeout_ts = NULL;
9906                 }
9907
9908                 if (arg4) {
9909                     if (arg5 != sizeof(target_sigset_t)) {
9910                         unlock_user(target_pfd, arg1, 0);
9911                         ret = -TARGET_EINVAL;
9912                         break;
9913                     }
9914
9915                     target_set = lock_user(VERIFY_READ, arg4, sizeof(target_sigset_t), 1);
9916                     if (!target_set) {
9917                         unlock_user(target_pfd, arg1, 0);
9918                         goto efault;
9919                     }
9920                     target_to_host_sigset(set, target_set);
9921                 } else {
9922                     set = NULL;
9923                 }
9924
9925                 ret = get_errno(safe_ppoll(pfd, nfds, timeout_ts,
9926                                            set, SIGSET_T_SIZE));
9927
9928                 if (!is_error(ret) && arg3) {
9929                     host_to_target_timespec(arg3, timeout_ts);
9930                 }
9931                 if (arg4) {
9932                     unlock_user(target_set, arg4, 0);
9933                 }
9934                 break;
9935             }
9936 # endif
9937 # ifdef TARGET_NR_poll
9938             case TARGET_NR_poll:
9939             {
9940                 struct timespec ts, *pts;
9941
9942                 if (arg3 >= 0) {
9943                     /* Convert ms to secs, ns */
9944                     ts.tv_sec = arg3 / 1000;
9945                     ts.tv_nsec = (arg3 % 1000) * 1000000LL;
9946                     pts = &ts;
9947                 } else {
9948                     /* -ve poll() timeout means "infinite" */
9949                     pts = NULL;
9950                 }
9951                 ret = get_errno(safe_ppoll(pfd, nfds, pts, NULL, 0));
9952                 break;
9953             }
9954 # endif
9955             default:
9956                 g_assert_not_reached();
9957             }
9958
9959             if (!is_error(ret)) {
9960                 for(i = 0; i < nfds; i++) {
9961                     target_pfd[i].revents = tswap16(pfd[i].revents);
9962                 }
9963             }
9964             unlock_user(target_pfd, arg1, sizeof(struct target_pollfd) * nfds);
9965         }
9966         break;
9967 #endif
9968     case TARGET_NR_flock:
9969         /* NOTE: the flock constant seems to be the same for every
9970            Linux platform */
9971         ret = get_errno(safe_flock(arg1, arg2));
9972         break;
9973     case TARGET_NR_readv:
9974         {
9975             struct iovec *vec = lock_iovec(VERIFY_WRITE, arg2, arg3, 0);
9976             if (vec != NULL) {
9977                 ret = get_errno(safe_readv(arg1, vec, arg3));
9978                 unlock_iovec(vec, arg2, arg3, 1);
9979             } else {
9980                 ret = -host_to_target_errno(errno);
9981             }
9982         }
9983         break;
9984     case TARGET_NR_writev:
9985         {
9986             struct iovec *vec = lock_iovec(VERIFY_READ, arg2, arg3, 1);
9987             if (vec != NULL) {
9988                 ret = get_errno(safe_writev(arg1, vec, arg3));
9989                 unlock_iovec(vec, arg2, arg3, 0);
9990             } else {
9991                 ret = -host_to_target_errno(errno);
9992             }
9993         }
9994         break;
9995     case TARGET_NR_getsid:
9996         ret = get_errno(getsid(arg1));
9997         break;
9998 #if defined(TARGET_NR_fdatasync) /* Not on alpha (osf_datasync ?) */
9999     case TARGET_NR_fdatasync:
10000         ret = get_errno(fdatasync(arg1));
10001         break;
10002 #endif
10003 #ifdef TARGET_NR__sysctl
10004     case TARGET_NR__sysctl:
10005         /* We don't implement this, but ENOTDIR is always a safe
10006            return value. */
10007         ret = -TARGET_ENOTDIR;
10008         break;
10009 #endif
10010     case TARGET_NR_sched_getaffinity:
10011         {
10012             unsigned int mask_size;
10013             unsigned long *mask;
10014
10015             /*
10016              * sched_getaffinity needs multiples of ulong, so need to take
10017              * care of mismatches between target ulong and host ulong sizes.
10018              */
10019             if (arg2 & (sizeof(abi_ulong) - 1)) {
10020                 ret = -TARGET_EINVAL;
10021                 break;
10022             }
10023             mask_size = (arg2 + (sizeof(*mask) - 1)) & ~(sizeof(*mask) - 1);
10024
10025             mask = alloca(mask_size);
10026             ret = get_errno(sys_sched_getaffinity(arg1, mask_size, mask));
10027
10028             if (!is_error(ret)) {
10029                 if (ret > arg2) {
10030                     /* More data returned than the caller's buffer will fit.
10031                      * This only happens if sizeof(abi_long) < sizeof(long)
10032                      * and the caller passed us a buffer holding an odd number
10033                      * of abi_longs. If the host kernel is actually using the
10034                      * extra 4 bytes then fail EINVAL; otherwise we can just
10035                      * ignore them and only copy the interesting part.
10036                      */
10037                     int numcpus = sysconf(_SC_NPROCESSORS_CONF);
10038                     if (numcpus > arg2 * 8) {
10039                         ret = -TARGET_EINVAL;
10040                         break;
10041                     }
10042                     ret = arg2;
10043                 }
10044
10045                 if (copy_to_user(arg3, mask, ret)) {
10046                     goto efault;
10047                 }
10048             }
10049         }
10050         break;
10051     case TARGET_NR_sched_setaffinity:
10052         {
10053             unsigned int mask_size;
10054             unsigned long *mask;
10055
10056             /*
10057              * sched_setaffinity needs multiples of ulong, so need to take
10058              * care of mismatches between target ulong and host ulong sizes.
10059              */
10060             if (arg2 & (sizeof(abi_ulong) - 1)) {
10061                 ret = -TARGET_EINVAL;
10062                 break;
10063             }
10064             mask_size = (arg2 + (sizeof(*mask) - 1)) & ~(sizeof(*mask) - 1);
10065
10066             mask = alloca(mask_size);
10067             if (!lock_user_struct(VERIFY_READ, p, arg3, 1)) {
10068                 goto efault;
10069             }
10070             memcpy(mask, p, arg2);
10071             unlock_user_struct(p, arg2, 0);
10072
10073             ret = get_errno(sys_sched_setaffinity(arg1, mask_size, mask));
10074         }
10075         break;
10076     case TARGET_NR_sched_setparam:
10077         {
10078             struct sched_param *target_schp;
10079             struct sched_param schp;
10080
10081             if (arg2 == 0) {
10082                 return -TARGET_EINVAL;
10083             }
10084             if (!lock_user_struct(VERIFY_READ, target_schp, arg2, 1))
10085                 goto efault;
10086             schp.sched_priority = tswap32(target_schp->sched_priority);
10087             unlock_user_struct(target_schp, arg2, 0);
10088             ret = get_errno(sched_setparam(arg1, &schp));
10089         }
10090         break;
10091     case TARGET_NR_sched_getparam:
10092         {
10093             struct sched_param *target_schp;
10094             struct sched_param schp;
10095
10096             if (arg2 == 0) {
10097                 return -TARGET_EINVAL;
10098             }
10099             ret = get_errno(sched_getparam(arg1, &schp));
10100             if (!is_error(ret)) {
10101                 if (!lock_user_struct(VERIFY_WRITE, target_schp, arg2, 0))
10102                     goto efault;
10103                 target_schp->sched_priority = tswap32(schp.sched_priority);
10104                 unlock_user_struct(target_schp, arg2, 1);
10105             }
10106         }
10107         break;
10108     case TARGET_NR_sched_setscheduler:
10109         {
10110             struct sched_param *target_schp;
10111             struct sched_param schp;
10112             if (arg3 == 0) {
10113                 return -TARGET_EINVAL;
10114             }
10115             if (!lock_user_struct(VERIFY_READ, target_schp, arg3, 1))
10116                 goto efault;
10117             schp.sched_priority = tswap32(target_schp->sched_priority);
10118             unlock_user_struct(target_schp, arg3, 0);
10119             ret = get_errno(sched_setscheduler(arg1, arg2, &schp));
10120         }
10121         break;
10122     case TARGET_NR_sched_getscheduler:
10123         ret = get_errno(sched_getscheduler(arg1));
10124         break;
10125     case TARGET_NR_sched_yield:
10126         ret = get_errno(sched_yield());
10127         break;
10128     case TARGET_NR_sched_get_priority_max:
10129         ret = get_errno(sched_get_priority_max(arg1));
10130         break;
10131     case TARGET_NR_sched_get_priority_min:
10132         ret = get_errno(sched_get_priority_min(arg1));
10133         break;
10134     case TARGET_NR_sched_rr_get_interval:
10135         {
10136             struct timespec ts;
10137             ret = get_errno(sched_rr_get_interval(arg1, &ts));
10138             if (!is_error(ret)) {
10139                 ret = host_to_target_timespec(arg2, &ts);
10140             }
10141         }
10142         break;
10143     case TARGET_NR_nanosleep:
10144         {
10145             struct timespec req, rem;
10146             target_to_host_timespec(&req, arg1);
10147             ret = get_errno(safe_nanosleep(&req, &rem));
10148             if (is_error(ret) && arg2) {
10149                 host_to_target_timespec(arg2, &rem);
10150             }
10151         }
10152         break;
10153 #ifdef TARGET_NR_query_module
10154     case TARGET_NR_query_module:
10155         goto unimplemented;
10156 #endif
10157 #ifdef TARGET_NR_nfsservctl
10158     case TARGET_NR_nfsservctl:
10159         goto unimplemented;
10160 #endif
10161     case TARGET_NR_prctl:
10162         switch (arg1) {
10163         case PR_GET_PDEATHSIG:
10164         {
10165             int deathsig;
10166             ret = get_errno(prctl(arg1, &deathsig, arg3, arg4, arg5));
10167             if (!is_error(ret) && arg2
10168                 && put_user_ual(deathsig, arg2)) {
10169                 goto efault;
10170             }
10171             break;
10172         }
10173 #ifdef PR_GET_NAME
10174         case PR_GET_NAME:
10175         {
10176             void *name = lock_user(VERIFY_WRITE, arg2, 16, 1);
10177             if (!name) {
10178                 goto efault;
10179             }
10180             ret = get_errno(prctl(arg1, (unsigned long)name,
10181                                   arg3, arg4, arg5));
10182             unlock_user(name, arg2, 16);
10183             break;
10184         }
10185         case PR_SET_NAME:
10186         {
10187             void *name = lock_user(VERIFY_READ, arg2, 16, 1);
10188             if (!name) {
10189                 goto efault;
10190             }
10191             ret = get_errno(prctl(arg1, (unsigned long)name,
10192                                   arg3, arg4, arg5));
10193             unlock_user(name, arg2, 0);
10194             break;
10195         }
10196 #endif
10197         default:
10198             /* Most prctl options have no pointer arguments */
10199             ret = get_errno(prctl(arg1, arg2, arg3, arg4, arg5));
10200             break;
10201         }
10202         break;
10203 #ifdef TARGET_NR_arch_prctl
10204     case TARGET_NR_arch_prctl:
10205 #if defined(TARGET_I386) && !defined(TARGET_ABI32)
10206         ret = do_arch_prctl(cpu_env, arg1, arg2);
10207         break;
10208 #else
10209         goto unimplemented;
10210 #endif
10211 #endif
10212 #ifdef TARGET_NR_pread64
10213     case TARGET_NR_pread64:
10214         if (regpairs_aligned(cpu_env)) {
10215             arg4 = arg5;
10216             arg5 = arg6;
10217         }
10218         if (!(p = lock_user(VERIFY_WRITE, arg2, arg3, 0)))
10219             goto efault;
10220         ret = get_errno(pread64(arg1, p, arg3, target_offset64(arg4, arg5)));
10221         unlock_user(p, arg2, ret);
10222         break;
10223     case TARGET_NR_pwrite64:
10224         if (regpairs_aligned(cpu_env)) {
10225             arg4 = arg5;
10226             arg5 = arg6;
10227         }
10228         if (!(p = lock_user(VERIFY_READ, arg2, arg3, 1)))
10229             goto efault;
10230         ret = get_errno(pwrite64(arg1, p, arg3, target_offset64(arg4, arg5)));
10231         unlock_user(p, arg2, 0);
10232         break;
10233 #endif
10234     case TARGET_NR_getcwd:
10235         if (!(p = lock_user(VERIFY_WRITE, arg1, arg2, 0)))
10236             goto efault;
10237         ret = get_errno(sys_getcwd1(p, arg2));
10238         unlock_user(p, arg1, ret);
10239         break;
10240     case TARGET_NR_capget:
10241     case TARGET_NR_capset:
10242     {
10243         struct target_user_cap_header *target_header;
10244         struct target_user_cap_data *target_data = NULL;
10245         struct __user_cap_header_struct header;
10246         struct __user_cap_data_struct data[2];
10247         struct __user_cap_data_struct *dataptr = NULL;
10248         int i, target_datalen;
10249         int data_items = 1;
10250
10251         if (!lock_user_struct(VERIFY_WRITE, target_header, arg1, 1)) {
10252             goto efault;
10253         }
10254         header.version = tswap32(target_header->version);
10255         header.pid = tswap32(target_header->pid);
10256
10257         if (header.version != _LINUX_CAPABILITY_VERSION) {
10258             /* Version 2 and up takes pointer to two user_data structs */
10259             data_items = 2;
10260         }
10261
10262         target_datalen = sizeof(*target_data) * data_items;
10263
10264         if (arg2) {
10265             if (num == TARGET_NR_capget) {
10266                 target_data = lock_user(VERIFY_WRITE, arg2, target_datalen, 0);
10267             } else {
10268                 target_data = lock_user(VERIFY_READ, arg2, target_datalen, 1);
10269             }
10270             if (!target_data) {
10271                 unlock_user_struct(target_header, arg1, 0);
10272                 goto efault;
10273             }
10274
10275             if (num == TARGET_NR_capset) {
10276                 for (i = 0; i < data_items; i++) {
10277                     data[i].effective = tswap32(target_data[i].effective);
10278                     data[i].permitted = tswap32(target_data[i].permitted);
10279                     data[i].inheritable = tswap32(target_data[i].inheritable);
10280                 }
10281             }
10282
10283             dataptr = data;
10284         }
10285
10286         if (num == TARGET_NR_capget) {
10287             ret = get_errno(capget(&header, dataptr));
10288         } else {
10289             ret = get_errno(capset(&header, dataptr));
10290         }
10291
10292         /* The kernel always updates version for both capget and capset */
10293         target_header->version = tswap32(header.version);
10294         unlock_user_struct(target_header, arg1, 1);
10295
10296         if (arg2) {
10297             if (num == TARGET_NR_capget) {
10298                 for (i = 0; i < data_items; i++) {
10299                     target_data[i].effective = tswap32(data[i].effective);
10300                     target_data[i].permitted = tswap32(data[i].permitted);
10301                     target_data[i].inheritable = tswap32(data[i].inheritable);
10302                 }
10303                 unlock_user(target_data, arg2, target_datalen);
10304             } else {
10305                 unlock_user(target_data, arg2, 0);
10306             }
10307         }
10308         break;
10309     }
10310     case TARGET_NR_sigaltstack:
10311         ret = do_sigaltstack(arg1, arg2, get_sp_from_cpustate((CPUArchState *)cpu_env));
10312         break;
10313
10314 #ifdef CONFIG_SENDFILE
10315     case TARGET_NR_sendfile:
10316     {
10317         off_t *offp = NULL;
10318         off_t off;
10319         if (arg3) {
10320             ret = get_user_sal(off, arg3);
10321             if (is_error(ret)) {
10322                 break;
10323             }
10324             offp = &off;
10325         }
10326         ret = get_errno(sendfile(arg1, arg2, offp, arg4));
10327         if (!is_error(ret) && arg3) {
10328             abi_long ret2 = put_user_sal(off, arg3);
10329             if (is_error(ret2)) {
10330                 ret = ret2;
10331             }
10332         }
10333         break;
10334     }
10335 #ifdef TARGET_NR_sendfile64
10336     case TARGET_NR_sendfile64:
10337     {
10338         off_t *offp = NULL;
10339         off_t off;
10340         if (arg3) {
10341             ret = get_user_s64(off, arg3);
10342             if (is_error(ret)) {
10343                 break;
10344             }
10345             offp = &off;
10346         }
10347         ret = get_errno(sendfile(arg1, arg2, offp, arg4));
10348         if (!is_error(ret) && arg3) {
10349             abi_long ret2 = put_user_s64(off, arg3);
10350             if (is_error(ret2)) {
10351                 ret = ret2;
10352             }
10353         }
10354         break;
10355     }
10356 #endif
10357 #else
10358     case TARGET_NR_sendfile:
10359 #ifdef TARGET_NR_sendfile64
10360     case TARGET_NR_sendfile64:
10361 #endif
10362         goto unimplemented;
10363 #endif
10364
10365 #ifdef TARGET_NR_getpmsg
10366     case TARGET_NR_getpmsg:
10367         goto unimplemented;
10368 #endif
10369 #ifdef TARGET_NR_putpmsg
10370     case TARGET_NR_putpmsg:
10371         goto unimplemented;
10372 #endif
10373 #ifdef TARGET_NR_vfork
10374     case TARGET_NR_vfork:
10375         ret = get_errno(do_fork(cpu_env, CLONE_VFORK | CLONE_VM | SIGCHLD,
10376                         0, 0, 0, 0));
10377         break;
10378 #endif
10379 #ifdef TARGET_NR_ugetrlimit
10380     case TARGET_NR_ugetrlimit:
10381     {
10382         struct rlimit rlim;
10383         int resource = target_to_host_resource(arg1);
10384         ret = get_errno(getrlimit(resource, &rlim));
10385         if (!is_error(ret)) {
10386             struct target_rlimit *target_rlim;
10387             if (!lock_user_struct(VERIFY_WRITE, target_rlim, arg2, 0))
10388                 goto efault;
10389             target_rlim->rlim_cur = host_to_target_rlim(rlim.rlim_cur);
10390             target_rlim->rlim_max = host_to_target_rlim(rlim.rlim_max);
10391             unlock_user_struct(target_rlim, arg2, 1);
10392         }
10393         break;
10394     }
10395 #endif
10396 #ifdef TARGET_NR_truncate64
10397     case TARGET_NR_truncate64:
10398         if (!(p = lock_user_string(arg1)))
10399             goto efault;
10400         ret = target_truncate64(cpu_env, p, arg2, arg3, arg4);
10401         unlock_user(p, arg1, 0);
10402         break;
10403 #endif
10404 #ifdef TARGET_NR_ftruncate64
10405     case TARGET_NR_ftruncate64:
10406         ret = target_ftruncate64(cpu_env, arg1, arg2, arg3, arg4);
10407         break;
10408 #endif
10409 #ifdef TARGET_NR_stat64
10410     case TARGET_NR_stat64:
10411         if (!(p = lock_user_string(arg1)))
10412             goto efault;
10413         ret = get_errno(stat(path(p), &st));
10414         unlock_user(p, arg1, 0);
10415         if (!is_error(ret))
10416             ret = host_to_target_stat64(cpu_env, arg2, &st);
10417         break;
10418 #endif
10419 #ifdef TARGET_NR_lstat64
10420     case TARGET_NR_lstat64:
10421         if (!(p = lock_user_string(arg1)))
10422             goto efault;
10423         ret = get_errno(lstat(path(p), &st));
10424         unlock_user(p, arg1, 0);
10425         if (!is_error(ret))
10426             ret = host_to_target_stat64(cpu_env, arg2, &st);
10427         break;
10428 #endif
10429 #ifdef TARGET_NR_fstat64
10430     case TARGET_NR_fstat64:
10431         ret = get_errno(fstat(arg1, &st));
10432         if (!is_error(ret))
10433             ret = host_to_target_stat64(cpu_env, arg2, &st);
10434         break;
10435 #endif
10436 #if (defined(TARGET_NR_fstatat64) || defined(TARGET_NR_newfstatat))
10437 #ifdef TARGET_NR_fstatat64
10438     case TARGET_NR_fstatat64:
10439 #endif
10440 #ifdef TARGET_NR_newfstatat
10441     case TARGET_NR_newfstatat:
10442 #endif
10443         if (!(p = lock_user_string(arg2)))
10444             goto efault;
10445         ret = get_errno(fstatat(arg1, path(p), &st, arg4));
10446         if (!is_error(ret))
10447             ret = host_to_target_stat64(cpu_env, arg3, &st);
10448         break;
10449 #endif
10450 #ifdef TARGET_NR_lchown
10451     case TARGET_NR_lchown:
10452         if (!(p = lock_user_string(arg1)))
10453             goto efault;
10454         ret = get_errno(lchown(p, low2highuid(arg2), low2highgid(arg3)));
10455         unlock_user(p, arg1, 0);
10456         break;
10457 #endif
10458 #ifdef TARGET_NR_getuid
10459     case TARGET_NR_getuid:
10460         ret = get_errno(high2lowuid(getuid()));
10461         break;
10462 #endif
10463 #ifdef TARGET_NR_getgid
10464     case TARGET_NR_getgid:
10465         ret = get_errno(high2lowgid(getgid()));
10466         break;
10467 #endif
10468 #ifdef TARGET_NR_geteuid
10469     case TARGET_NR_geteuid:
10470         ret = get_errno(high2lowuid(geteuid()));
10471         break;
10472 #endif
10473 #ifdef TARGET_NR_getegid
10474     case TARGET_NR_getegid:
10475         ret = get_errno(high2lowgid(getegid()));
10476         break;
10477 #endif
10478     case TARGET_NR_setreuid:
10479         ret = get_errno(setreuid(low2highuid(arg1), low2highuid(arg2)));
10480         break;
10481     case TARGET_NR_setregid:
10482         ret = get_errno(setregid(low2highgid(arg1), low2highgid(arg2)));
10483         break;
10484     case TARGET_NR_getgroups:
10485         {
10486             int gidsetsize = arg1;
10487             target_id *target_grouplist;
10488             gid_t *grouplist;
10489             int i;
10490
10491             grouplist = alloca(gidsetsize * sizeof(gid_t));
10492             ret = get_errno(getgroups(gidsetsize, grouplist));
10493             if (gidsetsize == 0)
10494                 break;
10495             if (!is_error(ret)) {
10496                 target_grouplist = lock_user(VERIFY_WRITE, arg2, gidsetsize * sizeof(target_id), 0);
10497                 if (!target_grouplist)
10498                     goto efault;
10499                 for(i = 0;i < ret; i++)
10500                     target_grouplist[i] = tswapid(high2lowgid(grouplist[i]));
10501                 unlock_user(target_grouplist, arg2, gidsetsize * sizeof(target_id));
10502             }
10503         }
10504         break;
10505     case TARGET_NR_setgroups:
10506         {
10507             int gidsetsize = arg1;
10508             target_id *target_grouplist;
10509             gid_t *grouplist = NULL;
10510             int i;
10511             if (gidsetsize) {
10512                 grouplist = alloca(gidsetsize * sizeof(gid_t));
10513                 target_grouplist = lock_user(VERIFY_READ, arg2, gidsetsize * sizeof(target_id), 1);
10514                 if (!target_grouplist) {
10515                     ret = -TARGET_EFAULT;
10516                     goto fail;
10517                 }
10518                 for (i = 0; i < gidsetsize; i++) {
10519                     grouplist[i] = low2highgid(tswapid(target_grouplist[i]));
10520                 }
10521                 unlock_user(target_grouplist, arg2, 0);
10522             }
10523             ret = get_errno(setgroups(gidsetsize, grouplist));
10524         }
10525         break;
10526     case TARGET_NR_fchown:
10527         ret = get_errno(fchown(arg1, low2highuid(arg2), low2highgid(arg3)));
10528         break;
10529 #if defined(TARGET_NR_fchownat)
10530     case TARGET_NR_fchownat:
10531         if (!(p = lock_user_string(arg2))) 
10532             goto efault;
10533         ret = get_errno(fchownat(arg1, p, low2highuid(arg3),
10534                                  low2highgid(arg4), arg5));
10535         unlock_user(p, arg2, 0);
10536         break;
10537 #endif
10538 #ifdef TARGET_NR_setresuid
10539     case TARGET_NR_setresuid:
10540         ret = get_errno(sys_setresuid(low2highuid(arg1),
10541                                       low2highuid(arg2),
10542                                       low2highuid(arg3)));
10543         break;
10544 #endif
10545 #ifdef TARGET_NR_getresuid
10546     case TARGET_NR_getresuid:
10547         {
10548             uid_t ruid, euid, suid;
10549             ret = get_errno(getresuid(&ruid, &euid, &suid));
10550             if (!is_error(ret)) {
10551                 if (put_user_id(high2lowuid(ruid), arg1)
10552                     || put_user_id(high2lowuid(euid), arg2)
10553                     || put_user_id(high2lowuid(suid), arg3))
10554                     goto efault;
10555             }
10556         }
10557         break;
10558 #endif
10559 #ifdef TARGET_NR_getresgid
10560     case TARGET_NR_setresgid:
10561         ret = get_errno(sys_setresgid(low2highgid(arg1),
10562                                       low2highgid(arg2),
10563                                       low2highgid(arg3)));
10564         break;
10565 #endif
10566 #ifdef TARGET_NR_getresgid
10567     case TARGET_NR_getresgid:
10568         {
10569             gid_t rgid, egid, sgid;
10570             ret = get_errno(getresgid(&rgid, &egid, &sgid));
10571             if (!is_error(ret)) {
10572                 if (put_user_id(high2lowgid(rgid), arg1)
10573                     || put_user_id(high2lowgid(egid), arg2)
10574                     || put_user_id(high2lowgid(sgid), arg3))
10575                     goto efault;
10576             }
10577         }
10578         break;
10579 #endif
10580 #ifdef TARGET_NR_chown
10581     case TARGET_NR_chown:
10582         if (!(p = lock_user_string(arg1)))
10583             goto efault;
10584         ret = get_errno(chown(p, low2highuid(arg2), low2highgid(arg3)));
10585         unlock_user(p, arg1, 0);
10586         break;
10587 #endif
10588     case TARGET_NR_setuid:
10589         ret = get_errno(sys_setuid(low2highuid(arg1)));
10590         break;
10591     case TARGET_NR_setgid:
10592         ret = get_errno(sys_setgid(low2highgid(arg1)));
10593         break;
10594     case TARGET_NR_setfsuid:
10595         ret = get_errno(setfsuid(arg1));
10596         break;
10597     case TARGET_NR_setfsgid:
10598         ret = get_errno(setfsgid(arg1));
10599         break;
10600
10601 #ifdef TARGET_NR_lchown32
10602     case TARGET_NR_lchown32:
10603         if (!(p = lock_user_string(arg1)))
10604             goto efault;
10605         ret = get_errno(lchown(p, arg2, arg3));
10606         unlock_user(p, arg1, 0);
10607         break;
10608 #endif
10609 #ifdef TARGET_NR_getuid32
10610     case TARGET_NR_getuid32:
10611         ret = get_errno(getuid());
10612         break;
10613 #endif
10614
10615 #if defined(TARGET_NR_getxuid) && defined(TARGET_ALPHA)
10616    /* Alpha specific */
10617     case TARGET_NR_getxuid:
10618          {
10619             uid_t euid;
10620             euid=geteuid();
10621             ((CPUAlphaState *)cpu_env)->ir[IR_A4]=euid;
10622          }
10623         ret = get_errno(getuid());
10624         break;
10625 #endif
10626 #if defined(TARGET_NR_getxgid) && defined(TARGET_ALPHA)
10627    /* Alpha specific */
10628     case TARGET_NR_getxgid:
10629          {
10630             uid_t egid;
10631             egid=getegid();
10632             ((CPUAlphaState *)cpu_env)->ir[IR_A4]=egid;
10633          }
10634         ret = get_errno(getgid());
10635         break;
10636 #endif
10637 #if defined(TARGET_NR_osf_getsysinfo) && defined(TARGET_ALPHA)
10638     /* Alpha specific */
10639     case TARGET_NR_osf_getsysinfo:
10640         ret = -TARGET_EOPNOTSUPP;
10641         switch (arg1) {
10642           case TARGET_GSI_IEEE_FP_CONTROL:
10643             {
10644                 uint64_t swcr, fpcr = cpu_alpha_load_fpcr (cpu_env);
10645
10646                 /* Copied from linux ieee_fpcr_to_swcr.  */
10647                 swcr = (fpcr >> 35) & SWCR_STATUS_MASK;
10648                 swcr |= (fpcr >> 36) & SWCR_MAP_DMZ;
10649                 swcr |= (~fpcr >> 48) & (SWCR_TRAP_ENABLE_INV
10650                                         | SWCR_TRAP_ENABLE_DZE
10651                                         | SWCR_TRAP_ENABLE_OVF);
10652                 swcr |= (~fpcr >> 57) & (SWCR_TRAP_ENABLE_UNF
10653                                         | SWCR_TRAP_ENABLE_INE);
10654                 swcr |= (fpcr >> 47) & SWCR_MAP_UMZ;
10655                 swcr |= (~fpcr >> 41) & SWCR_TRAP_ENABLE_DNO;
10656
10657                 if (put_user_u64 (swcr, arg2))
10658                         goto efault;
10659                 ret = 0;
10660             }
10661             break;
10662
10663           /* case GSI_IEEE_STATE_AT_SIGNAL:
10664              -- Not implemented in linux kernel.
10665              case GSI_UACPROC:
10666              -- Retrieves current unaligned access state; not much used.
10667              case GSI_PROC_TYPE:
10668              -- Retrieves implver information; surely not used.
10669              case GSI_GET_HWRPB:
10670              -- Grabs a copy of the HWRPB; surely not used.
10671           */
10672         }
10673         break;
10674 #endif
10675 #if defined(TARGET_NR_osf_setsysinfo) && defined(TARGET_ALPHA)
10676     /* Alpha specific */
10677     case TARGET_NR_osf_setsysinfo:
10678         ret = -TARGET_EOPNOTSUPP;
10679         switch (arg1) {
10680           case TARGET_SSI_IEEE_FP_CONTROL:
10681             {
10682                 uint64_t swcr, fpcr, orig_fpcr;
10683
10684                 if (get_user_u64 (swcr, arg2)) {
10685                     goto efault;
10686                 }
10687                 orig_fpcr = cpu_alpha_load_fpcr(cpu_env);
10688                 fpcr = orig_fpcr & FPCR_DYN_MASK;
10689
10690                 /* Copied from linux ieee_swcr_to_fpcr.  */
10691                 fpcr |= (swcr & SWCR_STATUS_MASK) << 35;
10692                 fpcr |= (swcr & SWCR_MAP_DMZ) << 36;
10693                 fpcr |= (~swcr & (SWCR_TRAP_ENABLE_INV
10694                                   | SWCR_TRAP_ENABLE_DZE
10695                                   | SWCR_TRAP_ENABLE_OVF)) << 48;
10696                 fpcr |= (~swcr & (SWCR_TRAP_ENABLE_UNF
10697                                   | SWCR_TRAP_ENABLE_INE)) << 57;
10698                 fpcr |= (swcr & SWCR_MAP_UMZ ? FPCR_UNDZ | FPCR_UNFD : 0);
10699                 fpcr |= (~swcr & SWCR_TRAP_ENABLE_DNO) << 41;
10700
10701                 cpu_alpha_store_fpcr(cpu_env, fpcr);
10702                 ret = 0;
10703             }
10704             break;
10705
10706           case TARGET_SSI_IEEE_RAISE_EXCEPTION:
10707             {
10708                 uint64_t exc, fpcr, orig_fpcr;
10709                 int si_code;
10710
10711                 if (get_user_u64(exc, arg2)) {
10712                     goto efault;
10713                 }
10714
10715                 orig_fpcr = cpu_alpha_load_fpcr(cpu_env);
10716
10717                 /* We only add to the exception status here.  */
10718                 fpcr = orig_fpcr | ((exc & SWCR_STATUS_MASK) << 35);
10719
10720                 cpu_alpha_store_fpcr(cpu_env, fpcr);
10721                 ret = 0;
10722
10723                 /* Old exceptions are not signaled.  */
10724                 fpcr &= ~(orig_fpcr & FPCR_STATUS_MASK);
10725
10726                 /* If any exceptions set by this call,
10727                    and are unmasked, send a signal.  */
10728                 si_code = 0;
10729                 if ((fpcr & (FPCR_INE | FPCR_INED)) == FPCR_INE) {
10730                     si_code = TARGET_FPE_FLTRES;
10731                 }
10732                 if ((fpcr & (FPCR_UNF | FPCR_UNFD)) == FPCR_UNF) {
10733                     si_code = TARGET_FPE_FLTUND;
10734                 }
10735                 if ((fpcr & (FPCR_OVF | FPCR_OVFD)) == FPCR_OVF) {
10736                     si_code = TARGET_FPE_FLTOVF;
10737                 }
10738                 if ((fpcr & (FPCR_DZE | FPCR_DZED)) == FPCR_DZE) {
10739                     si_code = TARGET_FPE_FLTDIV;
10740                 }
10741                 if ((fpcr & (FPCR_INV | FPCR_INVD)) == FPCR_INV) {
10742                     si_code = TARGET_FPE_FLTINV;
10743                 }
10744                 if (si_code != 0) {
10745                     target_siginfo_t info;
10746                     info.si_signo = SIGFPE;
10747                     info.si_errno = 0;
10748                     info.si_code = si_code;
10749                     info._sifields._sigfault._addr
10750                         = ((CPUArchState *)cpu_env)->pc;
10751                     queue_signal((CPUArchState *)cpu_env, info.si_signo,
10752                                  QEMU_SI_FAULT, &info);
10753                 }
10754             }
10755             break;
10756
10757           /* case SSI_NVPAIRS:
10758              -- Used with SSIN_UACPROC to enable unaligned accesses.
10759              case SSI_IEEE_STATE_AT_SIGNAL:
10760              case SSI_IEEE_IGNORE_STATE_AT_SIGNAL:
10761              -- Not implemented in linux kernel
10762           */
10763         }
10764         break;
10765 #endif
10766 #ifdef TARGET_NR_osf_sigprocmask
10767     /* Alpha specific.  */
10768     case TARGET_NR_osf_sigprocmask:
10769         {
10770             abi_ulong mask;
10771             int how;
10772             sigset_t set, oldset;
10773
10774             switch(arg1) {
10775             case TARGET_SIG_BLOCK:
10776                 how = SIG_BLOCK;
10777                 break;
10778             case TARGET_SIG_UNBLOCK:
10779                 how = SIG_UNBLOCK;
10780                 break;
10781             case TARGET_SIG_SETMASK:
10782                 how = SIG_SETMASK;
10783                 break;
10784             default:
10785                 ret = -TARGET_EINVAL;
10786                 goto fail;
10787             }
10788             mask = arg2;
10789             target_to_host_old_sigset(&set, &mask);
10790             ret = do_sigprocmask(how, &set, &oldset);
10791             if (!ret) {
10792                 host_to_target_old_sigset(&mask, &oldset);
10793                 ret = mask;
10794             }
10795         }
10796         break;
10797 #endif
10798
10799 #ifdef TARGET_NR_getgid32
10800     case TARGET_NR_getgid32:
10801         ret = get_errno(getgid());
10802         break;
10803 #endif
10804 #ifdef TARGET_NR_geteuid32
10805     case TARGET_NR_geteuid32:
10806         ret = get_errno(geteuid());
10807         break;
10808 #endif
10809 #ifdef TARGET_NR_getegid32
10810     case TARGET_NR_getegid32:
10811         ret = get_errno(getegid());
10812         break;
10813 #endif
10814 #ifdef TARGET_NR_setreuid32
10815     case TARGET_NR_setreuid32:
10816         ret = get_errno(setreuid(arg1, arg2));
10817         break;
10818 #endif
10819 #ifdef TARGET_NR_setregid32
10820     case TARGET_NR_setregid32:
10821         ret = get_errno(setregid(arg1, arg2));
10822         break;
10823 #endif
10824 #ifdef TARGET_NR_getgroups32
10825     case TARGET_NR_getgroups32:
10826         {
10827             int gidsetsize = arg1;
10828             uint32_t *target_grouplist;
10829             gid_t *grouplist;
10830             int i;
10831
10832             grouplist = alloca(gidsetsize * sizeof(gid_t));
10833             ret = get_errno(getgroups(gidsetsize, grouplist));
10834             if (gidsetsize == 0)
10835                 break;
10836             if (!is_error(ret)) {
10837                 target_grouplist = lock_user(VERIFY_WRITE, arg2, gidsetsize * 4, 0);
10838                 if (!target_grouplist) {
10839                     ret = -TARGET_EFAULT;
10840                     goto fail;
10841                 }
10842                 for(i = 0;i < ret; i++)
10843                     target_grouplist[i] = tswap32(grouplist[i]);
10844                 unlock_user(target_grouplist, arg2, gidsetsize * 4);
10845             }
10846         }
10847         break;
10848 #endif
10849 #ifdef TARGET_NR_setgroups32
10850     case TARGET_NR_setgroups32:
10851         {
10852             int gidsetsize = arg1;
10853             uint32_t *target_grouplist;
10854             gid_t *grouplist;
10855             int i;
10856
10857             grouplist = alloca(gidsetsize * sizeof(gid_t));
10858             target_grouplist = lock_user(VERIFY_READ, arg2, gidsetsize * 4, 1);
10859             if (!target_grouplist) {
10860                 ret = -TARGET_EFAULT;
10861                 goto fail;
10862             }
10863             for(i = 0;i < gidsetsize; i++)
10864                 grouplist[i] = tswap32(target_grouplist[i]);
10865             unlock_user(target_grouplist, arg2, 0);
10866             ret = get_errno(setgroups(gidsetsize, grouplist));
10867         }
10868         break;
10869 #endif
10870 #ifdef TARGET_NR_fchown32
10871     case TARGET_NR_fchown32:
10872         ret = get_errno(fchown(arg1, arg2, arg3));
10873         break;
10874 #endif
10875 #ifdef TARGET_NR_setresuid32
10876     case TARGET_NR_setresuid32:
10877         ret = get_errno(sys_setresuid(arg1, arg2, arg3));
10878         break;
10879 #endif
10880 #ifdef TARGET_NR_getresuid32
10881     case TARGET_NR_getresuid32:
10882         {
10883             uid_t ruid, euid, suid;
10884             ret = get_errno(getresuid(&ruid, &euid, &suid));
10885             if (!is_error(ret)) {
10886                 if (put_user_u32(ruid, arg1)
10887                     || put_user_u32(euid, arg2)
10888                     || put_user_u32(suid, arg3))
10889                     goto efault;
10890             }
10891         }
10892         break;
10893 #endif
10894 #ifdef TARGET_NR_setresgid32
10895     case TARGET_NR_setresgid32:
10896         ret = get_errno(sys_setresgid(arg1, arg2, arg3));
10897         break;
10898 #endif
10899 #ifdef TARGET_NR_getresgid32
10900     case TARGET_NR_getresgid32:
10901         {
10902             gid_t rgid, egid, sgid;
10903             ret = get_errno(getresgid(&rgid, &egid, &sgid));
10904             if (!is_error(ret)) {
10905                 if (put_user_u32(rgid, arg1)
10906                     || put_user_u32(egid, arg2)
10907                     || put_user_u32(sgid, arg3))
10908                     goto efault;
10909             }
10910         }
10911         break;
10912 #endif
10913 #ifdef TARGET_NR_chown32
10914     case TARGET_NR_chown32:
10915         if (!(p = lock_user_string(arg1)))
10916             goto efault;
10917         ret = get_errno(chown(p, arg2, arg3));
10918         unlock_user(p, arg1, 0);
10919         break;
10920 #endif
10921 #ifdef TARGET_NR_setuid32
10922     case TARGET_NR_setuid32:
10923         ret = get_errno(sys_setuid(arg1));
10924         break;
10925 #endif
10926 #ifdef TARGET_NR_setgid32
10927     case TARGET_NR_setgid32:
10928         ret = get_errno(sys_setgid(arg1));
10929         break;
10930 #endif
10931 #ifdef TARGET_NR_setfsuid32
10932     case TARGET_NR_setfsuid32:
10933         ret = get_errno(setfsuid(arg1));
10934         break;
10935 #endif
10936 #ifdef TARGET_NR_setfsgid32
10937     case TARGET_NR_setfsgid32:
10938         ret = get_errno(setfsgid(arg1));
10939         break;
10940 #endif
10941
10942     case TARGET_NR_pivot_root:
10943         goto unimplemented;
10944 #ifdef TARGET_NR_mincore
10945     case TARGET_NR_mincore:
10946         {
10947             void *a;
10948             ret = -TARGET_EFAULT;
10949             if (!(a = lock_user(VERIFY_READ, arg1,arg2, 0)))
10950                 goto efault;
10951             if (!(p = lock_user_string(arg3)))
10952                 goto mincore_fail;
10953             ret = get_errno(mincore(a, arg2, p));
10954             unlock_user(p, arg3, ret);
10955             mincore_fail:
10956             unlock_user(a, arg1, 0);
10957         }
10958         break;
10959 #endif
10960 #ifdef TARGET_NR_arm_fadvise64_64
10961     case TARGET_NR_arm_fadvise64_64:
10962         /* arm_fadvise64_64 looks like fadvise64_64 but
10963          * with different argument order: fd, advice, offset, len
10964          * rather than the usual fd, offset, len, advice.
10965          * Note that offset and len are both 64-bit so appear as
10966          * pairs of 32-bit registers.
10967          */
10968         ret = posix_fadvise(arg1, target_offset64(arg3, arg4),
10969                             target_offset64(arg5, arg6), arg2);
10970         ret = -host_to_target_errno(ret);
10971         break;
10972 #endif
10973
10974 #if TARGET_ABI_BITS == 32
10975
10976 #ifdef TARGET_NR_fadvise64_64
10977     case TARGET_NR_fadvise64_64:
10978         /* 6 args: fd, offset (high, low), len (high, low), advice */
10979         if (regpairs_aligned(cpu_env)) {
10980             /* offset is in (3,4), len in (5,6) and advice in 7 */
10981             arg2 = arg3;
10982             arg3 = arg4;
10983             arg4 = arg5;
10984             arg5 = arg6;
10985             arg6 = arg7;
10986         }
10987         ret = -host_to_target_errno(posix_fadvise(arg1,
10988                                                   target_offset64(arg2, arg3),
10989                                                   target_offset64(arg4, arg5),
10990                                                   arg6));
10991         break;
10992 #endif
10993
10994 #ifdef TARGET_NR_fadvise64
10995     case TARGET_NR_fadvise64:
10996         /* 5 args: fd, offset (high, low), len, advice */
10997         if (regpairs_aligned(cpu_env)) {
10998             /* offset is in (3,4), len in 5 and advice in 6 */
10999             arg2 = arg3;
11000             arg3 = arg4;
11001             arg4 = arg5;
11002             arg5 = arg6;
11003         }
11004         ret = -host_to_target_errno(posix_fadvise(arg1,
11005                                                   target_offset64(arg2, arg3),
11006                                                   arg4, arg5));
11007         break;
11008 #endif
11009
11010 #else /* not a 32-bit ABI */
11011 #if defined(TARGET_NR_fadvise64_64) || defined(TARGET_NR_fadvise64)
11012 #ifdef TARGET_NR_fadvise64_64
11013     case TARGET_NR_fadvise64_64:
11014 #endif
11015 #ifdef TARGET_NR_fadvise64
11016     case TARGET_NR_fadvise64:
11017 #endif
11018 #ifdef TARGET_S390X
11019         switch (arg4) {
11020         case 4: arg4 = POSIX_FADV_NOREUSE + 1; break; /* make sure it's an invalid value */
11021         case 5: arg4 = POSIX_FADV_NOREUSE + 2; break; /* ditto */
11022         case 6: arg4 = POSIX_FADV_DONTNEED; break;
11023         case 7: arg4 = POSIX_FADV_NOREUSE; break;
11024         default: break;
11025         }
11026 #endif
11027         ret = -host_to_target_errno(posix_fadvise(arg1, arg2, arg3, arg4));
11028         break;
11029 #endif
11030 #endif /* end of 64-bit ABI fadvise handling */
11031
11032 #ifdef TARGET_NR_madvise
11033     case TARGET_NR_madvise:
11034         /* A straight passthrough may not be safe because qemu sometimes
11035            turns private file-backed mappings into anonymous mappings.
11036            This will break MADV_DONTNEED.
11037            This is a hint, so ignoring and returning success is ok.  */
11038         ret = get_errno(0);
11039         break;
11040 #endif
11041 #if TARGET_ABI_BITS == 32
11042     case TARGET_NR_fcntl64:
11043     {
11044         int cmd;
11045         struct flock64 fl;
11046         from_flock64_fn *copyfrom = copy_from_user_flock64;
11047         to_flock64_fn *copyto = copy_to_user_flock64;
11048
11049 #ifdef TARGET_ARM
11050         if (((CPUARMState *)cpu_env)->eabi) {
11051             copyfrom = copy_from_user_eabi_flock64;
11052             copyto = copy_to_user_eabi_flock64;
11053         }
11054 #endif
11055
11056         cmd = target_to_host_fcntl_cmd(arg2);
11057         if (cmd == -TARGET_EINVAL) {
11058             ret = cmd;
11059             break;
11060         }
11061
11062         switch(arg2) {
11063         case TARGET_F_GETLK64:
11064             ret = copyfrom(&fl, arg3);
11065             if (ret) {
11066                 break;
11067             }
11068             ret = get_errno(fcntl(arg1, cmd, &fl));
11069             if (ret == 0) {
11070                 ret = copyto(arg3, &fl);
11071             }
11072             break;
11073
11074         case TARGET_F_SETLK64:
11075         case TARGET_F_SETLKW64:
11076             ret = copyfrom(&fl, arg3);
11077             if (ret) {
11078                 break;
11079             }
11080             ret = get_errno(safe_fcntl(arg1, cmd, &fl));
11081             break;
11082         default:
11083             ret = do_fcntl(arg1, arg2, arg3);
11084             break;
11085         }
11086         break;
11087     }
11088 #endif
11089 #ifdef TARGET_NR_cacheflush
11090     case TARGET_NR_cacheflush:
11091         /* self-modifying code is handled automatically, so nothing needed */
11092         ret = 0;
11093         break;
11094 #endif
11095 #ifdef TARGET_NR_security
11096     case TARGET_NR_security:
11097         goto unimplemented;
11098 #endif
11099 #ifdef TARGET_NR_getpagesize
11100     case TARGET_NR_getpagesize:
11101         ret = TARGET_PAGE_SIZE;
11102         break;
11103 #endif
11104     case TARGET_NR_gettid:
11105         ret = get_errno(gettid());
11106         break;
11107 #ifdef TARGET_NR_readahead
11108     case TARGET_NR_readahead:
11109 #if TARGET_ABI_BITS == 32
11110         if (regpairs_aligned(cpu_env)) {
11111             arg2 = arg3;
11112             arg3 = arg4;
11113             arg4 = arg5;
11114         }
11115         ret = get_errno(readahead(arg1, ((off64_t)arg3 << 32) | arg2, arg4));
11116 #else
11117         ret = get_errno(readahead(arg1, arg2, arg3));
11118 #endif
11119         break;
11120 #endif
11121 #ifdef CONFIG_ATTR
11122 #ifdef TARGET_NR_setxattr
11123     case TARGET_NR_listxattr:
11124     case TARGET_NR_llistxattr:
11125     {
11126         void *p, *b = 0;
11127         if (arg2) {
11128             b = lock_user(VERIFY_WRITE, arg2, arg3, 0);
11129             if (!b) {
11130                 ret = -TARGET_EFAULT;
11131                 break;
11132             }
11133         }
11134         p = lock_user_string(arg1);
11135         if (p) {
11136             if (num == TARGET_NR_listxattr) {
11137                 ret = get_errno(listxattr(p, b, arg3));
11138             } else {
11139                 ret = get_errno(llistxattr(p, b, arg3));
11140             }
11141         } else {
11142             ret = -TARGET_EFAULT;
11143         }
11144         unlock_user(p, arg1, 0);
11145         unlock_user(b, arg2, arg3);
11146         break;
11147     }
11148     case TARGET_NR_flistxattr:
11149     {
11150         void *b = 0;
11151         if (arg2) {
11152             b = lock_user(VERIFY_WRITE, arg2, arg3, 0);
11153             if (!b) {
11154                 ret = -TARGET_EFAULT;
11155                 break;
11156             }
11157         }
11158         ret = get_errno(flistxattr(arg1, b, arg3));
11159         unlock_user(b, arg2, arg3);
11160         break;
11161     }
11162     case TARGET_NR_setxattr:
11163     case TARGET_NR_lsetxattr:
11164         {
11165             void *p, *n, *v = 0;
11166             if (arg3) {
11167                 v = lock_user(VERIFY_READ, arg3, arg4, 1);
11168                 if (!v) {
11169                     ret = -TARGET_EFAULT;
11170                     break;
11171                 }
11172             }
11173             p = lock_user_string(arg1);
11174             n = lock_user_string(arg2);
11175             if (p && n) {
11176                 if (num == TARGET_NR_setxattr) {
11177                     ret = get_errno(setxattr(p, n, v, arg4, arg5));
11178                 } else {
11179                     ret = get_errno(lsetxattr(p, n, v, arg4, arg5));
11180                 }
11181             } else {
11182                 ret = -TARGET_EFAULT;
11183             }
11184             unlock_user(p, arg1, 0);
11185             unlock_user(n, arg2, 0);
11186             unlock_user(v, arg3, 0);
11187         }
11188         break;
11189     case TARGET_NR_fsetxattr:
11190         {
11191             void *n, *v = 0;
11192             if (arg3) {
11193                 v = lock_user(VERIFY_READ, arg3, arg4, 1);
11194                 if (!v) {
11195                     ret = -TARGET_EFAULT;
11196                     break;
11197                 }
11198             }
11199             n = lock_user_string(arg2);
11200             if (n) {
11201                 ret = get_errno(fsetxattr(arg1, n, v, arg4, arg5));
11202             } else {
11203                 ret = -TARGET_EFAULT;
11204             }
11205             unlock_user(n, arg2, 0);
11206             unlock_user(v, arg3, 0);
11207         }
11208         break;
11209     case TARGET_NR_getxattr:
11210     case TARGET_NR_lgetxattr:
11211         {
11212             void *p, *n, *v = 0;
11213             if (arg3) {
11214                 v = lock_user(VERIFY_WRITE, arg3, arg4, 0);
11215                 if (!v) {
11216                     ret = -TARGET_EFAULT;
11217                     break;
11218                 }
11219             }
11220             p = lock_user_string(arg1);
11221             n = lock_user_string(arg2);
11222             if (p && n) {
11223                 if (num == TARGET_NR_getxattr) {
11224                     ret = get_errno(getxattr(p, n, v, arg4));
11225                 } else {
11226                     ret = get_errno(lgetxattr(p, n, v, arg4));
11227                 }
11228             } else {
11229                 ret = -TARGET_EFAULT;
11230             }
11231             unlock_user(p, arg1, 0);
11232             unlock_user(n, arg2, 0);
11233             unlock_user(v, arg3, arg4);
11234         }
11235         break;
11236     case TARGET_NR_fgetxattr:
11237         {
11238             void *n, *v = 0;
11239             if (arg3) {
11240                 v = lock_user(VERIFY_WRITE, arg3, arg4, 0);
11241                 if (!v) {
11242                     ret = -TARGET_EFAULT;
11243                     break;
11244                 }
11245             }
11246             n = lock_user_string(arg2);
11247             if (n) {
11248                 ret = get_errno(fgetxattr(arg1, n, v, arg4));
11249             } else {
11250                 ret = -TARGET_EFAULT;
11251             }
11252             unlock_user(n, arg2, 0);
11253             unlock_user(v, arg3, arg4);
11254         }
11255         break;
11256     case TARGET_NR_removexattr:
11257     case TARGET_NR_lremovexattr:
11258         {
11259             void *p, *n;
11260             p = lock_user_string(arg1);
11261             n = lock_user_string(arg2);
11262             if (p && n) {
11263                 if (num == TARGET_NR_removexattr) {
11264                     ret = get_errno(removexattr(p, n));
11265                 } else {
11266                     ret = get_errno(lremovexattr(p, n));
11267                 }
11268             } else {
11269                 ret = -TARGET_EFAULT;
11270             }
11271             unlock_user(p, arg1, 0);
11272             unlock_user(n, arg2, 0);
11273         }
11274         break;
11275     case TARGET_NR_fremovexattr:
11276         {
11277             void *n;
11278             n = lock_user_string(arg2);
11279             if (n) {
11280                 ret = get_errno(fremovexattr(arg1, n));
11281             } else {
11282                 ret = -TARGET_EFAULT;
11283             }
11284             unlock_user(n, arg2, 0);
11285         }
11286         break;
11287 #endif
11288 #endif /* CONFIG_ATTR */
11289 #ifdef TARGET_NR_set_thread_area
11290     case TARGET_NR_set_thread_area:
11291 #if defined(TARGET_MIPS)
11292       ((CPUMIPSState *) cpu_env)->active_tc.CP0_UserLocal = arg1;
11293       ret = 0;
11294       break;
11295 #elif defined(TARGET_CRIS)
11296       if (arg1 & 0xff)
11297           ret = -TARGET_EINVAL;
11298       else {
11299           ((CPUCRISState *) cpu_env)->pregs[PR_PID] = arg1;
11300           ret = 0;
11301       }
11302       break;
11303 #elif defined(TARGET_I386) && defined(TARGET_ABI32)
11304       ret = do_set_thread_area(cpu_env, arg1);
11305       break;
11306 #elif defined(TARGET_M68K)
11307       {
11308           TaskState *ts = cpu->opaque;
11309           ts->tp_value = arg1;
11310           ret = 0;
11311           break;
11312       }
11313 #else
11314       goto unimplemented_nowarn;
11315 #endif
11316 #endif
11317 #ifdef TARGET_NR_get_thread_area
11318     case TARGET_NR_get_thread_area:
11319 #if defined(TARGET_I386) && defined(TARGET_ABI32)
11320         ret = do_get_thread_area(cpu_env, arg1);
11321         break;
11322 #elif defined(TARGET_M68K)
11323         {
11324             TaskState *ts = cpu->opaque;
11325             ret = ts->tp_value;
11326             break;
11327         }
11328 #else
11329         goto unimplemented_nowarn;
11330 #endif
11331 #endif
11332 #ifdef TARGET_NR_getdomainname
11333     case TARGET_NR_getdomainname:
11334         goto unimplemented_nowarn;
11335 #endif
11336
11337 #ifdef TARGET_NR_clock_gettime
11338     case TARGET_NR_clock_gettime:
11339     {
11340         struct timespec ts;
11341         ret = get_errno(clock_gettime(arg1, &ts));
11342         if (!is_error(ret)) {
11343             host_to_target_timespec(arg2, &ts);
11344         }
11345         break;
11346     }
11347 #endif
11348 #ifdef TARGET_NR_clock_getres
11349     case TARGET_NR_clock_getres:
11350     {
11351         struct timespec ts;
11352         ret = get_errno(clock_getres(arg1, &ts));
11353         if (!is_error(ret)) {
11354             host_to_target_timespec(arg2, &ts);
11355         }
11356         break;
11357     }
11358 #endif
11359 #ifdef TARGET_NR_clock_nanosleep
11360     case TARGET_NR_clock_nanosleep:
11361     {
11362         struct timespec ts;
11363         target_to_host_timespec(&ts, arg3);
11364         ret = get_errno(safe_clock_nanosleep(arg1, arg2,
11365                                              &ts, arg4 ? &ts : NULL));
11366         if (arg4)
11367             host_to_target_timespec(arg4, &ts);
11368
11369 #if defined(TARGET_PPC)
11370         /* clock_nanosleep is odd in that it returns positive errno values.
11371          * On PPC, CR0 bit 3 should be set in such a situation. */
11372         if (ret && ret != -TARGET_ERESTARTSYS) {
11373             ((CPUPPCState *)cpu_env)->crf[0] |= 1;
11374         }
11375 #endif
11376         break;
11377     }
11378 #endif
11379
11380 #if defined(TARGET_NR_set_tid_address) && defined(__NR_set_tid_address)
11381     case TARGET_NR_set_tid_address:
11382         ret = get_errno(set_tid_address((int *)g2h(arg1)));
11383         break;
11384 #endif
11385
11386     case TARGET_NR_tkill:
11387         ret = get_errno(safe_tkill((int)arg1, target_to_host_signal(arg2)));
11388         break;
11389
11390     case TARGET_NR_tgkill:
11391         ret = get_errno(safe_tgkill((int)arg1, (int)arg2,
11392                         target_to_host_signal(arg3)));
11393         break;
11394
11395 #ifdef TARGET_NR_set_robust_list
11396     case TARGET_NR_set_robust_list:
11397     case TARGET_NR_get_robust_list:
11398         /* The ABI for supporting robust futexes has userspace pass
11399          * the kernel a pointer to a linked list which is updated by
11400          * userspace after the syscall; the list is walked by the kernel
11401          * when the thread exits. Since the linked list in QEMU guest
11402          * memory isn't a valid linked list for the host and we have
11403          * no way to reliably intercept the thread-death event, we can't
11404          * support these. Silently return ENOSYS so that guest userspace
11405          * falls back to a non-robust futex implementation (which should
11406          * be OK except in the corner case of the guest crashing while
11407          * holding a mutex that is shared with another process via
11408          * shared memory).
11409          */
11410         goto unimplemented_nowarn;
11411 #endif
11412
11413 #if defined(TARGET_NR_utimensat)
11414     case TARGET_NR_utimensat:
11415         {
11416             struct timespec *tsp, ts[2];
11417             if (!arg3) {
11418                 tsp = NULL;
11419             } else {
11420                 target_to_host_timespec(ts, arg3);
11421                 target_to_host_timespec(ts+1, arg3+sizeof(struct target_timespec));
11422                 tsp = ts;
11423             }
11424             if (!arg2)
11425                 ret = get_errno(sys_utimensat(arg1, NULL, tsp, arg4));
11426             else {
11427                 if (!(p = lock_user_string(arg2))) {
11428                     ret = -TARGET_EFAULT;
11429                     goto fail;
11430                 }
11431                 ret = get_errno(sys_utimensat(arg1, path(p), tsp, arg4));
11432                 unlock_user(p, arg2, 0);
11433             }
11434         }
11435         break;
11436 #endif
11437     case TARGET_NR_futex:
11438         ret = do_futex(arg1, arg2, arg3, arg4, arg5, arg6);
11439         break;
11440 #if defined(TARGET_NR_inotify_init) && defined(__NR_inotify_init)
11441     case TARGET_NR_inotify_init:
11442         ret = get_errno(sys_inotify_init());
11443         break;
11444 #endif
11445 #ifdef CONFIG_INOTIFY1
11446 #if defined(TARGET_NR_inotify_init1) && defined(__NR_inotify_init1)
11447     case TARGET_NR_inotify_init1:
11448         ret = get_errno(sys_inotify_init1(arg1));
11449         break;
11450 #endif
11451 #endif
11452 #if defined(TARGET_NR_inotify_add_watch) && defined(__NR_inotify_add_watch)
11453     case TARGET_NR_inotify_add_watch:
11454         p = lock_user_string(arg2);
11455         ret = get_errno(sys_inotify_add_watch(arg1, path(p), arg3));
11456         unlock_user(p, arg2, 0);
11457         break;
11458 #endif
11459 #if defined(TARGET_NR_inotify_rm_watch) && defined(__NR_inotify_rm_watch)
11460     case TARGET_NR_inotify_rm_watch:
11461         ret = get_errno(sys_inotify_rm_watch(arg1, arg2));
11462         break;
11463 #endif
11464
11465 #if defined(TARGET_NR_mq_open) && defined(__NR_mq_open)
11466     case TARGET_NR_mq_open:
11467         {
11468             struct mq_attr posix_mq_attr;
11469             int host_flags;
11470
11471             host_flags = target_to_host_bitmask(arg2, fcntl_flags_tbl);
11472             if (copy_from_user_mq_attr(&posix_mq_attr, arg4) != 0) {
11473                 goto efault;
11474             }
11475             p = lock_user_string(arg1 - 1);
11476             if (!p) {
11477                 goto efault;
11478             }
11479             ret = get_errno(mq_open(p, host_flags, arg3, &posix_mq_attr));
11480             unlock_user (p, arg1, 0);
11481         }
11482         break;
11483
11484     case TARGET_NR_mq_unlink:
11485         p = lock_user_string(arg1 - 1);
11486         if (!p) {
11487             ret = -TARGET_EFAULT;
11488             break;
11489         }
11490         ret = get_errno(mq_unlink(p));
11491         unlock_user (p, arg1, 0);
11492         break;
11493
11494     case TARGET_NR_mq_timedsend:
11495         {
11496             struct timespec ts;
11497
11498             p = lock_user (VERIFY_READ, arg2, arg3, 1);
11499             if (arg5 != 0) {
11500                 target_to_host_timespec(&ts, arg5);
11501                 ret = get_errno(safe_mq_timedsend(arg1, p, arg3, arg4, &ts));
11502                 host_to_target_timespec(arg5, &ts);
11503             } else {
11504                 ret = get_errno(safe_mq_timedsend(arg1, p, arg3, arg4, NULL));
11505             }
11506             unlock_user (p, arg2, arg3);
11507         }
11508         break;
11509
11510     case TARGET_NR_mq_timedreceive:
11511         {
11512             struct timespec ts;
11513             unsigned int prio;
11514
11515             p = lock_user (VERIFY_READ, arg2, arg3, 1);
11516             if (arg5 != 0) {
11517                 target_to_host_timespec(&ts, arg5);
11518                 ret = get_errno(safe_mq_timedreceive(arg1, p, arg3,
11519                                                      &prio, &ts));
11520                 host_to_target_timespec(arg5, &ts);
11521             } else {
11522                 ret = get_errno(safe_mq_timedreceive(arg1, p, arg3,
11523                                                      &prio, NULL));
11524             }
11525             unlock_user (p, arg2, arg3);
11526             if (arg4 != 0)
11527                 put_user_u32(prio, arg4);
11528         }
11529         break;
11530
11531     /* Not implemented for now... */
11532 /*     case TARGET_NR_mq_notify: */
11533 /*         break; */
11534
11535     case TARGET_NR_mq_getsetattr:
11536         {
11537             struct mq_attr posix_mq_attr_in, posix_mq_attr_out;
11538             ret = 0;
11539             if (arg3 != 0) {
11540                 ret = mq_getattr(arg1, &posix_mq_attr_out);
11541                 copy_to_user_mq_attr(arg3, &posix_mq_attr_out);
11542             }
11543             if (arg2 != 0) {
11544                 copy_from_user_mq_attr(&posix_mq_attr_in, arg2);
11545                 ret |= mq_setattr(arg1, &posix_mq_attr_in, &posix_mq_attr_out);
11546             }
11547
11548         }
11549         break;
11550 #endif
11551
11552 #ifdef CONFIG_SPLICE
11553 #ifdef TARGET_NR_tee
11554     case TARGET_NR_tee:
11555         {
11556             ret = get_errno(tee(arg1,arg2,arg3,arg4));
11557         }
11558         break;
11559 #endif
11560 #ifdef TARGET_NR_splice
11561     case TARGET_NR_splice:
11562         {
11563             loff_t loff_in, loff_out;
11564             loff_t *ploff_in = NULL, *ploff_out = NULL;
11565             if (arg2) {
11566                 if (get_user_u64(loff_in, arg2)) {
11567                     goto efault;
11568                 }
11569                 ploff_in = &loff_in;
11570             }
11571             if (arg4) {
11572                 if (get_user_u64(loff_out, arg4)) {
11573                     goto efault;
11574                 }
11575                 ploff_out = &loff_out;
11576             }
11577             ret = get_errno(splice(arg1, ploff_in, arg3, ploff_out, arg5, arg6));
11578             if (arg2) {
11579                 if (put_user_u64(loff_in, arg2)) {
11580                     goto efault;
11581                 }
11582             }
11583             if (arg4) {
11584                 if (put_user_u64(loff_out, arg4)) {
11585                     goto efault;
11586                 }
11587             }
11588         }
11589         break;
11590 #endif
11591 #ifdef TARGET_NR_vmsplice
11592         case TARGET_NR_vmsplice:
11593         {
11594             struct iovec *vec = lock_iovec(VERIFY_READ, arg2, arg3, 1);
11595             if (vec != NULL) {
11596                 ret = get_errno(vmsplice(arg1, vec, arg3, arg4));
11597                 unlock_iovec(vec, arg2, arg3, 0);
11598             } else {
11599                 ret = -host_to_target_errno(errno);
11600             }
11601         }
11602         break;
11603 #endif
11604 #endif /* CONFIG_SPLICE */
11605 #ifdef CONFIG_EVENTFD
11606 #if defined(TARGET_NR_eventfd)
11607     case TARGET_NR_eventfd:
11608         ret = get_errno(eventfd(arg1, 0));
11609         fd_trans_unregister(ret);
11610         break;
11611 #endif
11612 #if defined(TARGET_NR_eventfd2)
11613     case TARGET_NR_eventfd2:
11614     {
11615         int host_flags = arg2 & (~(TARGET_O_NONBLOCK | TARGET_O_CLOEXEC));
11616         if (arg2 & TARGET_O_NONBLOCK) {
11617             host_flags |= O_NONBLOCK;
11618         }
11619         if (arg2 & TARGET_O_CLOEXEC) {
11620             host_flags |= O_CLOEXEC;
11621         }
11622         ret = get_errno(eventfd(arg1, host_flags));
11623         fd_trans_unregister(ret);
11624         break;
11625     }
11626 #endif
11627 #endif /* CONFIG_EVENTFD  */
11628 #if defined(CONFIG_FALLOCATE) && defined(TARGET_NR_fallocate)
11629     case TARGET_NR_fallocate:
11630 #if TARGET_ABI_BITS == 32
11631         ret = get_errno(fallocate(arg1, arg2, target_offset64(arg3, arg4),
11632                                   target_offset64(arg5, arg6)));
11633 #else
11634         ret = get_errno(fallocate(arg1, arg2, arg3, arg4));
11635 #endif
11636         break;
11637 #endif
11638 #if defined(CONFIG_SYNC_FILE_RANGE)
11639 #if defined(TARGET_NR_sync_file_range)
11640     case TARGET_NR_sync_file_range:
11641 #if TARGET_ABI_BITS == 32
11642 #if defined(TARGET_MIPS)
11643         ret = get_errno(sync_file_range(arg1, target_offset64(arg3, arg4),
11644                                         target_offset64(arg5, arg6), arg7));
11645 #else
11646         ret = get_errno(sync_file_range(arg1, target_offset64(arg2, arg3),
11647                                         target_offset64(arg4, arg5), arg6));
11648 #endif /* !TARGET_MIPS */
11649 #else
11650         ret = get_errno(sync_file_range(arg1, arg2, arg3, arg4));
11651 #endif
11652         break;
11653 #endif
11654 #if defined(TARGET_NR_sync_file_range2)
11655     case TARGET_NR_sync_file_range2:
11656         /* This is like sync_file_range but the arguments are reordered */
11657 #if TARGET_ABI_BITS == 32
11658         ret = get_errno(sync_file_range(arg1, target_offset64(arg3, arg4),
11659                                         target_offset64(arg5, arg6), arg2));
11660 #else
11661         ret = get_errno(sync_file_range(arg1, arg3, arg4, arg2));
11662 #endif
11663         break;
11664 #endif
11665 #endif
11666 #if defined(TARGET_NR_signalfd4)
11667     case TARGET_NR_signalfd4:
11668         ret = do_signalfd4(arg1, arg2, arg4);
11669         break;
11670 #endif
11671 #if defined(TARGET_NR_signalfd)
11672     case TARGET_NR_signalfd:
11673         ret = do_signalfd4(arg1, arg2, 0);
11674         break;
11675 #endif
11676 #if defined(CONFIG_EPOLL)
11677 #if defined(TARGET_NR_epoll_create)
11678     case TARGET_NR_epoll_create:
11679         ret = get_errno(epoll_create(arg1));
11680         break;
11681 #endif
11682 #if defined(TARGET_NR_epoll_create1) && defined(CONFIG_EPOLL_CREATE1)
11683     case TARGET_NR_epoll_create1:
11684         ret = get_errno(epoll_create1(arg1));
11685         break;
11686 #endif
11687 #if defined(TARGET_NR_epoll_ctl)
11688     case TARGET_NR_epoll_ctl:
11689     {
11690         struct epoll_event ep;
11691         struct epoll_event *epp = 0;
11692         if (arg4) {
11693             struct target_epoll_event *target_ep;
11694             if (!lock_user_struct(VERIFY_READ, target_ep, arg4, 1)) {
11695                 goto efault;
11696             }
11697             ep.events = tswap32(target_ep->events);
11698             /* The epoll_data_t union is just opaque data to the kernel,
11699              * so we transfer all 64 bits across and need not worry what
11700              * actual data type it is.
11701              */
11702             ep.data.u64 = tswap64(target_ep->data.u64);
11703             unlock_user_struct(target_ep, arg4, 0);
11704             epp = &ep;
11705         }
11706         ret = get_errno(epoll_ctl(arg1, arg2, arg3, epp));
11707         break;
11708     }
11709 #endif
11710
11711 #if defined(TARGET_NR_epoll_wait) || defined(TARGET_NR_epoll_pwait)
11712 #if defined(TARGET_NR_epoll_wait)
11713     case TARGET_NR_epoll_wait:
11714 #endif
11715 #if defined(TARGET_NR_epoll_pwait)
11716     case TARGET_NR_epoll_pwait:
11717 #endif
11718     {
11719         struct target_epoll_event *target_ep;
11720         struct epoll_event *ep;
11721         int epfd = arg1;
11722         int maxevents = arg3;
11723         int timeout = arg4;
11724
11725         if (maxevents <= 0 || maxevents > TARGET_EP_MAX_EVENTS) {
11726             ret = -TARGET_EINVAL;
11727             break;
11728         }
11729
11730         target_ep = lock_user(VERIFY_WRITE, arg2,
11731                               maxevents * sizeof(struct target_epoll_event), 1);
11732         if (!target_ep) {
11733             goto efault;
11734         }
11735
11736         ep = alloca(maxevents * sizeof(struct epoll_event));
11737
11738         switch (num) {
11739 #if defined(TARGET_NR_epoll_pwait)
11740         case TARGET_NR_epoll_pwait:
11741         {
11742             target_sigset_t *target_set;
11743             sigset_t _set, *set = &_set;
11744
11745             if (arg5) {
11746                 if (arg6 != sizeof(target_sigset_t)) {
11747                     ret = -TARGET_EINVAL;
11748                     break;
11749                 }
11750
11751                 target_set = lock_user(VERIFY_READ, arg5,
11752                                        sizeof(target_sigset_t), 1);
11753                 if (!target_set) {
11754                     unlock_user(target_ep, arg2, 0);
11755                     goto efault;
11756                 }
11757                 target_to_host_sigset(set, target_set);
11758                 unlock_user(target_set, arg5, 0);
11759             } else {
11760                 set = NULL;
11761             }
11762
11763             ret = get_errno(safe_epoll_pwait(epfd, ep, maxevents, timeout,
11764                                              set, SIGSET_T_SIZE));
11765             break;
11766         }
11767 #endif
11768 #if defined(TARGET_NR_epoll_wait)
11769         case TARGET_NR_epoll_wait:
11770             ret = get_errno(safe_epoll_pwait(epfd, ep, maxevents, timeout,
11771                                              NULL, 0));
11772             break;
11773 #endif
11774         default:
11775             ret = -TARGET_ENOSYS;
11776         }
11777         if (!is_error(ret)) {
11778             int i;
11779             for (i = 0; i < ret; i++) {
11780                 target_ep[i].events = tswap32(ep[i].events);
11781                 target_ep[i].data.u64 = tswap64(ep[i].data.u64);
11782             }
11783         }
11784         unlock_user(target_ep, arg2, ret * sizeof(struct target_epoll_event));
11785         break;
11786     }
11787 #endif
11788 #endif
11789 #ifdef TARGET_NR_prlimit64
11790     case TARGET_NR_prlimit64:
11791     {
11792         /* args: pid, resource number, ptr to new rlimit, ptr to old rlimit */
11793         struct target_rlimit64 *target_rnew, *target_rold;
11794         struct host_rlimit64 rnew, rold, *rnewp = 0;
11795         int resource = target_to_host_resource(arg2);
11796         if (arg3) {
11797             if (!lock_user_struct(VERIFY_READ, target_rnew, arg3, 1)) {
11798                 goto efault;
11799             }
11800             rnew.rlim_cur = tswap64(target_rnew->rlim_cur);
11801             rnew.rlim_max = tswap64(target_rnew->rlim_max);
11802             unlock_user_struct(target_rnew, arg3, 0);
11803             rnewp = &rnew;
11804         }
11805
11806         ret = get_errno(sys_prlimit64(arg1, resource, rnewp, arg4 ? &rold : 0));
11807         if (!is_error(ret) && arg4) {
11808             if (!lock_user_struct(VERIFY_WRITE, target_rold, arg4, 1)) {
11809                 goto efault;
11810             }
11811             target_rold->rlim_cur = tswap64(rold.rlim_cur);
11812             target_rold->rlim_max = tswap64(rold.rlim_max);
11813             unlock_user_struct(target_rold, arg4, 1);
11814         }
11815         break;
11816     }
11817 #endif
11818 #ifdef TARGET_NR_gethostname
11819     case TARGET_NR_gethostname:
11820     {
11821         char *name = lock_user(VERIFY_WRITE, arg1, arg2, 0);
11822         if (name) {
11823             ret = get_errno(gethostname(name, arg2));
11824             unlock_user(name, arg1, arg2);
11825         } else {
11826             ret = -TARGET_EFAULT;
11827         }
11828         break;
11829     }
11830 #endif
11831 #ifdef TARGET_NR_atomic_cmpxchg_32
11832     case TARGET_NR_atomic_cmpxchg_32:
11833     {
11834         /* should use start_exclusive from main.c */
11835         abi_ulong mem_value;
11836         if (get_user_u32(mem_value, arg6)) {
11837             target_siginfo_t info;
11838             info.si_signo = SIGSEGV;
11839             info.si_errno = 0;
11840             info.si_code = TARGET_SEGV_MAPERR;
11841             info._sifields._sigfault._addr = arg6;
11842             queue_signal((CPUArchState *)cpu_env, info.si_signo,
11843                          QEMU_SI_FAULT, &info);
11844             ret = 0xdeadbeef;
11845
11846         }
11847         if (mem_value == arg2)
11848             put_user_u32(arg1, arg6);
11849         ret = mem_value;
11850         break;
11851     }
11852 #endif
11853 #ifdef TARGET_NR_atomic_barrier
11854     case TARGET_NR_atomic_barrier:
11855     {
11856         /* Like the kernel implementation and the qemu arm barrier, no-op this? */
11857         ret = 0;
11858         break;
11859     }
11860 #endif
11861
11862 #ifdef TARGET_NR_timer_create
11863     case TARGET_NR_timer_create:
11864     {
11865         /* args: clockid_t clockid, struct sigevent *sevp, timer_t *timerid */
11866
11867         struct sigevent host_sevp = { {0}, }, *phost_sevp = NULL;
11868
11869         int clkid = arg1;
11870         int timer_index = next_free_host_timer();
11871
11872         if (timer_index < 0) {
11873             ret = -TARGET_EAGAIN;
11874         } else {
11875             timer_t *phtimer = g_posix_timers  + timer_index;
11876
11877             if (arg2) {
11878                 phost_sevp = &host_sevp;
11879                 ret = target_to_host_sigevent(phost_sevp, arg2);
11880                 if (ret != 0) {
11881                     break;
11882                 }
11883             }
11884
11885             ret = get_errno(timer_create(clkid, phost_sevp, phtimer));
11886             if (ret) {
11887                 phtimer = NULL;
11888             } else {
11889                 if (put_user(TIMER_MAGIC | timer_index, arg3, target_timer_t)) {
11890                     goto efault;
11891                 }
11892             }
11893         }
11894         break;
11895     }
11896 #endif
11897
11898 #ifdef TARGET_NR_timer_settime
11899     case TARGET_NR_timer_settime:
11900     {
11901         /* args: timer_t timerid, int flags, const struct itimerspec *new_value,
11902          * struct itimerspec * old_value */
11903         target_timer_t timerid = get_timer_id(arg1);
11904
11905         if (timerid < 0) {
11906             ret = timerid;
11907         } else if (arg3 == 0) {
11908             ret = -TARGET_EINVAL;
11909         } else {
11910             timer_t htimer = g_posix_timers[timerid];
11911             struct itimerspec hspec_new = {{0},}, hspec_old = {{0},};
11912
11913             target_to_host_itimerspec(&hspec_new, arg3);
11914             ret = get_errno(
11915                           timer_settime(htimer, arg2, &hspec_new, &hspec_old));
11916             host_to_target_itimerspec(arg2, &hspec_old);
11917         }
11918         break;
11919     }
11920 #endif
11921
11922 #ifdef TARGET_NR_timer_gettime
11923     case TARGET_NR_timer_gettime:
11924     {
11925         /* args: timer_t timerid, struct itimerspec *curr_value */
11926         target_timer_t timerid = get_timer_id(arg1);
11927
11928         if (timerid < 0) {
11929             ret = timerid;
11930         } else if (!arg2) {
11931             ret = -TARGET_EFAULT;
11932         } else {
11933             timer_t htimer = g_posix_timers[timerid];
11934             struct itimerspec hspec;
11935             ret = get_errno(timer_gettime(htimer, &hspec));
11936
11937             if (host_to_target_itimerspec(arg2, &hspec)) {
11938                 ret = -TARGET_EFAULT;
11939             }
11940         }
11941         break;
11942     }
11943 #endif
11944
11945 #ifdef TARGET_NR_timer_getoverrun
11946     case TARGET_NR_timer_getoverrun:
11947     {
11948         /* args: timer_t timerid */
11949         target_timer_t timerid = get_timer_id(arg1);
11950
11951         if (timerid < 0) {
11952             ret = timerid;
11953         } else {
11954             timer_t htimer = g_posix_timers[timerid];
11955             ret = get_errno(timer_getoverrun(htimer));
11956         }
11957         fd_trans_unregister(ret);
11958         break;
11959     }
11960 #endif
11961
11962 #ifdef TARGET_NR_timer_delete
11963     case TARGET_NR_timer_delete:
11964     {
11965         /* args: timer_t timerid */
11966         target_timer_t timerid = get_timer_id(arg1);
11967
11968         if (timerid < 0) {
11969             ret = timerid;
11970         } else {
11971             timer_t htimer = g_posix_timers[timerid];
11972             ret = get_errno(timer_delete(htimer));
11973             g_posix_timers[timerid] = 0;
11974         }
11975         break;
11976     }
11977 #endif
11978
11979 #if defined(TARGET_NR_timerfd_create) && defined(CONFIG_TIMERFD)
11980     case TARGET_NR_timerfd_create:
11981         ret = get_errno(timerfd_create(arg1,
11982                 target_to_host_bitmask(arg2, fcntl_flags_tbl)));
11983         break;
11984 #endif
11985
11986 #if defined(TARGET_NR_timerfd_gettime) && defined(CONFIG_TIMERFD)
11987     case TARGET_NR_timerfd_gettime:
11988         {
11989             struct itimerspec its_curr;
11990
11991             ret = get_errno(timerfd_gettime(arg1, &its_curr));
11992
11993             if (arg2 && host_to_target_itimerspec(arg2, &its_curr)) {
11994                 goto efault;
11995             }
11996         }
11997         break;
11998 #endif
11999
12000 #if defined(TARGET_NR_timerfd_settime) && defined(CONFIG_TIMERFD)
12001     case TARGET_NR_timerfd_settime:
12002         {
12003             struct itimerspec its_new, its_old, *p_new;
12004
12005             if (arg3) {
12006                 if (target_to_host_itimerspec(&its_new, arg3)) {
12007                     goto efault;
12008                 }
12009                 p_new = &its_new;
12010             } else {
12011                 p_new = NULL;
12012             }
12013
12014             ret = get_errno(timerfd_settime(arg1, arg2, p_new, &its_old));
12015
12016             if (arg4 && host_to_target_itimerspec(arg4, &its_old)) {
12017                 goto efault;
12018             }
12019         }
12020         break;
12021 #endif
12022
12023 #if defined(TARGET_NR_ioprio_get) && defined(__NR_ioprio_get)
12024     case TARGET_NR_ioprio_get:
12025         ret = get_errno(ioprio_get(arg1, arg2));
12026         break;
12027 #endif
12028
12029 #if defined(TARGET_NR_ioprio_set) && defined(__NR_ioprio_set)
12030     case TARGET_NR_ioprio_set:
12031         ret = get_errno(ioprio_set(arg1, arg2, arg3));
12032         break;
12033 #endif
12034
12035 #if defined(TARGET_NR_setns) && defined(CONFIG_SETNS)
12036     case TARGET_NR_setns:
12037         ret = get_errno(setns(arg1, arg2));
12038         break;
12039 #endif
12040 #if defined(TARGET_NR_unshare) && defined(CONFIG_SETNS)
12041     case TARGET_NR_unshare:
12042         ret = get_errno(unshare(arg1));
12043         break;
12044 #endif
12045
12046     default:
12047     unimplemented:
12048         gemu_log("qemu: Unsupported syscall: %d\n", num);
12049 #if defined(TARGET_NR_setxattr) || defined(TARGET_NR_get_thread_area) || defined(TARGET_NR_getdomainname) || defined(TARGET_NR_set_robust_list)
12050     unimplemented_nowarn:
12051 #endif
12052         ret = -TARGET_ENOSYS;
12053         break;
12054     }
12055 fail:
12056 #ifdef DEBUG
12057     gemu_log(" = " TARGET_ABI_FMT_ld "\n", ret);
12058 #endif
12059     if(do_strace)
12060         print_syscall_ret(num, ret);
12061     trace_guest_user_syscall_ret(cpu, num, ret);
12062     return ret;
12063 efault:
12064     ret = -TARGET_EFAULT;
12065     goto fail;
12066 }
This page took 0.740743 seconds and 4 git commands to generate.