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