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