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