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