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