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