xref: /qemu/linux-user/syscall.c (revision 8a641ff6)
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 <stdlib.h>
21 #include <stdio.h>
22 #include <stdarg.h>
23 #include <string.h>
24 #include <elf.h>
25 #include <endian.h>
26 #include <errno.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <time.h>
30 #include <limits.h>
31 #include <grp.h>
32 #include <sys/types.h>
33 #include <sys/ipc.h>
34 #include <sys/msg.h>
35 #include <sys/wait.h>
36 #include <sys/time.h>
37 #include <sys/stat.h>
38 #include <sys/mount.h>
39 #include <sys/file.h>
40 #include <sys/fsuid.h>
41 #include <sys/personality.h>
42 #include <sys/prctl.h>
43 #include <sys/resource.h>
44 #include <sys/mman.h>
45 #include <sys/swap.h>
46 #include <linux/capability.h>
47 #include <signal.h>
48 #include <sched.h>
49 #ifdef __ia64__
50 int __clone2(int (*fn)(void *), void *child_stack_base,
51              size_t stack_size, int flags, void *arg, ...);
52 #endif
53 #include <sys/socket.h>
54 #include <sys/un.h>
55 #include <sys/uio.h>
56 #include <sys/poll.h>
57 #include <sys/times.h>
58 #include <sys/shm.h>
59 #include <sys/sem.h>
60 #include <sys/statfs.h>
61 #include <utime.h>
62 #include <sys/sysinfo.h>
63 //#include <sys/user.h>
64 #include <netinet/ip.h>
65 #include <netinet/tcp.h>
66 #include <linux/wireless.h>
67 #include <linux/icmp.h>
68 #include "qemu-common.h"
69 #ifdef CONFIG_TIMERFD
70 #include <sys/timerfd.h>
71 #endif
72 #ifdef TARGET_GPROF
73 #include <sys/gmon.h>
74 #endif
75 #ifdef CONFIG_EVENTFD
76 #include <sys/eventfd.h>
77 #endif
78 #ifdef CONFIG_EPOLL
79 #include <sys/epoll.h>
80 #endif
81 #ifdef CONFIG_ATTR
82 #include "qemu/xattr.h"
83 #endif
84 #ifdef CONFIG_SENDFILE
85 #include <sys/sendfile.h>
86 #endif
87 
88 #define termios host_termios
89 #define winsize host_winsize
90 #define termio host_termio
91 #define sgttyb host_sgttyb /* same as target */
92 #define tchars host_tchars /* same as target */
93 #define ltchars host_ltchars /* same as target */
94 
95 #include <linux/termios.h>
96 #include <linux/unistd.h>
97 #include <linux/cdrom.h>
98 #include <linux/hdreg.h>
99 #include <linux/soundcard.h>
100 #include <linux/kd.h>
101 #include <linux/mtio.h>
102 #include <linux/fs.h>
103 #if defined(CONFIG_FIEMAP)
104 #include <linux/fiemap.h>
105 #endif
106 #include <linux/fb.h>
107 #include <linux/vt.h>
108 #include <linux/dm-ioctl.h>
109 #include <linux/reboot.h>
110 #include <linux/route.h>
111 #include <linux/filter.h>
112 #include <linux/blkpg.h>
113 #include "linux_loop.h"
114 #include "uname.h"
115 
116 #include "qemu.h"
117 
118 #define CLONE_NPTL_FLAGS2 (CLONE_SETTLS | \
119     CLONE_PARENT_SETTID | CLONE_CHILD_SETTID | CLONE_CHILD_CLEARTID)
120 
121 //#define DEBUG
122 
123 //#include <linux/msdos_fs.h>
124 #define	VFAT_IOCTL_READDIR_BOTH		_IOR('r', 1, struct linux_dirent [2])
125 #define	VFAT_IOCTL_READDIR_SHORT	_IOR('r', 2, struct linux_dirent [2])
126 
127 
128 #undef _syscall0
129 #undef _syscall1
130 #undef _syscall2
131 #undef _syscall3
132 #undef _syscall4
133 #undef _syscall5
134 #undef _syscall6
135 
136 #define _syscall0(type,name)		\
137 static type name (void)			\
138 {					\
139 	return syscall(__NR_##name);	\
140 }
141 
142 #define _syscall1(type,name,type1,arg1)		\
143 static type name (type1 arg1)			\
144 {						\
145 	return syscall(__NR_##name, arg1);	\
146 }
147 
148 #define _syscall2(type,name,type1,arg1,type2,arg2)	\
149 static type name (type1 arg1,type2 arg2)		\
150 {							\
151 	return syscall(__NR_##name, arg1, arg2);	\
152 }
153 
154 #define _syscall3(type,name,type1,arg1,type2,arg2,type3,arg3)	\
155 static type name (type1 arg1,type2 arg2,type3 arg3)		\
156 {								\
157 	return syscall(__NR_##name, arg1, arg2, arg3);		\
158 }
159 
160 #define _syscall4(type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4)	\
161 static type name (type1 arg1,type2 arg2,type3 arg3,type4 arg4)			\
162 {										\
163 	return syscall(__NR_##name, arg1, arg2, arg3, arg4);			\
164 }
165 
166 #define _syscall5(type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4,	\
167 		  type5,arg5)							\
168 static type name (type1 arg1,type2 arg2,type3 arg3,type4 arg4,type5 arg5)	\
169 {										\
170 	return syscall(__NR_##name, arg1, arg2, arg3, arg4, arg5);		\
171 }
172 
173 
174 #define _syscall6(type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4,	\
175 		  type5,arg5,type6,arg6)					\
176 static type name (type1 arg1,type2 arg2,type3 arg3,type4 arg4,type5 arg5,	\
177                   type6 arg6)							\
178 {										\
179 	return syscall(__NR_##name, arg1, arg2, arg3, arg4, arg5, arg6);	\
180 }
181 
182 
183 #define __NR_sys_uname __NR_uname
184 #define __NR_sys_getcwd1 __NR_getcwd
185 #define __NR_sys_getdents __NR_getdents
186 #define __NR_sys_getdents64 __NR_getdents64
187 #define __NR_sys_getpriority __NR_getpriority
188 #define __NR_sys_rt_sigqueueinfo __NR_rt_sigqueueinfo
189 #define __NR_sys_syslog __NR_syslog
190 #define __NR_sys_tgkill __NR_tgkill
191 #define __NR_sys_tkill __NR_tkill
192 #define __NR_sys_futex __NR_futex
193 #define __NR_sys_inotify_init __NR_inotify_init
194 #define __NR_sys_inotify_add_watch __NR_inotify_add_watch
195 #define __NR_sys_inotify_rm_watch __NR_inotify_rm_watch
196 
197 #if defined(__alpha__) || defined (__ia64__) || defined(__x86_64__) || \
198     defined(__s390x__)
199 #define __NR__llseek __NR_lseek
200 #endif
201 
202 /* Newer kernel ports have llseek() instead of _llseek() */
203 #if defined(TARGET_NR_llseek) && !defined(TARGET_NR__llseek)
204 #define TARGET_NR__llseek TARGET_NR_llseek
205 #endif
206 
207 #ifdef __NR_gettid
208 _syscall0(int, gettid)
209 #else
210 /* This is a replacement for the host gettid() and must return a host
211    errno. */
212 static int gettid(void) {
213     return -ENOSYS;
214 }
215 #endif
216 #if defined(TARGET_NR_getdents) && defined(__NR_getdents)
217 _syscall3(int, sys_getdents, uint, fd, struct linux_dirent *, dirp, uint, count);
218 #endif
219 #if !defined(__NR_getdents) || \
220     (defined(TARGET_NR_getdents64) && defined(__NR_getdents64))
221 _syscall3(int, sys_getdents64, uint, fd, struct linux_dirent64 *, dirp, uint, count);
222 #endif
223 #if defined(TARGET_NR__llseek) && defined(__NR_llseek)
224 _syscall5(int, _llseek,  uint,  fd, ulong, hi, ulong, lo,
225           loff_t *, res, uint, wh);
226 #endif
227 _syscall3(int,sys_rt_sigqueueinfo,int,pid,int,sig,siginfo_t *,uinfo)
228 _syscall3(int,sys_syslog,int,type,char*,bufp,int,len)
229 #if defined(TARGET_NR_tgkill) && defined(__NR_tgkill)
230 _syscall3(int,sys_tgkill,int,tgid,int,pid,int,sig)
231 #endif
232 #if defined(TARGET_NR_tkill) && defined(__NR_tkill)
233 _syscall2(int,sys_tkill,int,tid,int,sig)
234 #endif
235 #ifdef __NR_exit_group
236 _syscall1(int,exit_group,int,error_code)
237 #endif
238 #if defined(TARGET_NR_set_tid_address) && defined(__NR_set_tid_address)
239 _syscall1(int,set_tid_address,int *,tidptr)
240 #endif
241 #if defined(TARGET_NR_futex) && defined(__NR_futex)
242 _syscall6(int,sys_futex,int *,uaddr,int,op,int,val,
243           const struct timespec *,timeout,int *,uaddr2,int,val3)
244 #endif
245 #define __NR_sys_sched_getaffinity __NR_sched_getaffinity
246 _syscall3(int, sys_sched_getaffinity, pid_t, pid, unsigned int, len,
247           unsigned long *, user_mask_ptr);
248 #define __NR_sys_sched_setaffinity __NR_sched_setaffinity
249 _syscall3(int, sys_sched_setaffinity, pid_t, pid, unsigned int, len,
250           unsigned long *, user_mask_ptr);
251 _syscall4(int, reboot, int, magic1, int, magic2, unsigned int, cmd,
252           void *, arg);
253 _syscall2(int, capget, struct __user_cap_header_struct *, header,
254           struct __user_cap_data_struct *, data);
255 _syscall2(int, capset, struct __user_cap_header_struct *, header,
256           struct __user_cap_data_struct *, data);
257 #if defined(TARGET_NR_ioprio_get) && defined(__NR_ioprio_get)
258 _syscall2(int, ioprio_get, int, which, int, who)
259 #endif
260 #if defined(TARGET_NR_ioprio_set) && defined(__NR_ioprio_set)
261 _syscall3(int, ioprio_set, int, which, int, who, int, ioprio)
262 #endif
263 
264 static bitmask_transtbl fcntl_flags_tbl[] = {
265   { TARGET_O_ACCMODE,   TARGET_O_WRONLY,    O_ACCMODE,   O_WRONLY,    },
266   { TARGET_O_ACCMODE,   TARGET_O_RDWR,      O_ACCMODE,   O_RDWR,      },
267   { TARGET_O_CREAT,     TARGET_O_CREAT,     O_CREAT,     O_CREAT,     },
268   { TARGET_O_EXCL,      TARGET_O_EXCL,      O_EXCL,      O_EXCL,      },
269   { TARGET_O_NOCTTY,    TARGET_O_NOCTTY,    O_NOCTTY,    O_NOCTTY,    },
270   { TARGET_O_TRUNC,     TARGET_O_TRUNC,     O_TRUNC,     O_TRUNC,     },
271   { TARGET_O_APPEND,    TARGET_O_APPEND,    O_APPEND,    O_APPEND,    },
272   { TARGET_O_NONBLOCK,  TARGET_O_NONBLOCK,  O_NONBLOCK,  O_NONBLOCK,  },
273   { TARGET_O_SYNC,      TARGET_O_DSYNC,     O_SYNC,      O_DSYNC,     },
274   { TARGET_O_SYNC,      TARGET_O_SYNC,      O_SYNC,      O_SYNC,      },
275   { TARGET_FASYNC,      TARGET_FASYNC,      FASYNC,      FASYNC,      },
276   { TARGET_O_DIRECTORY, TARGET_O_DIRECTORY, O_DIRECTORY, O_DIRECTORY, },
277   { TARGET_O_NOFOLLOW,  TARGET_O_NOFOLLOW,  O_NOFOLLOW,  O_NOFOLLOW,  },
278 #if defined(O_DIRECT)
279   { TARGET_O_DIRECT,    TARGET_O_DIRECT,    O_DIRECT,    O_DIRECT,    },
280 #endif
281 #if defined(O_NOATIME)
282   { TARGET_O_NOATIME,   TARGET_O_NOATIME,   O_NOATIME,   O_NOATIME    },
283 #endif
284 #if defined(O_CLOEXEC)
285   { TARGET_O_CLOEXEC,   TARGET_O_CLOEXEC,   O_CLOEXEC,   O_CLOEXEC    },
286 #endif
287 #if defined(O_PATH)
288   { TARGET_O_PATH,      TARGET_O_PATH,      O_PATH,      O_PATH       },
289 #endif
290   /* Don't terminate the list prematurely on 64-bit host+guest.  */
291 #if TARGET_O_LARGEFILE != 0 || O_LARGEFILE != 0
292   { TARGET_O_LARGEFILE, TARGET_O_LARGEFILE, O_LARGEFILE, O_LARGEFILE, },
293 #endif
294   { 0, 0, 0, 0 }
295 };
296 
297 static int sys_getcwd1(char *buf, size_t size)
298 {
299   if (getcwd(buf, size) == NULL) {
300       /* getcwd() sets errno */
301       return (-1);
302   }
303   return strlen(buf)+1;
304 }
305 
306 static int sys_openat(int dirfd, const char *pathname, int flags, mode_t mode)
307 {
308   /*
309    * open(2) has extra parameter 'mode' when called with
310    * flag O_CREAT.
311    */
312   if ((flags & O_CREAT) != 0) {
313       return (openat(dirfd, pathname, flags, mode));
314   }
315   return (openat(dirfd, pathname, flags));
316 }
317 
318 #ifdef TARGET_NR_utimensat
319 #ifdef CONFIG_UTIMENSAT
320 static int sys_utimensat(int dirfd, const char *pathname,
321     const struct timespec times[2], int flags)
322 {
323     if (pathname == NULL)
324         return futimens(dirfd, times);
325     else
326         return utimensat(dirfd, pathname, times, flags);
327 }
328 #elif defined(__NR_utimensat)
329 #define __NR_sys_utimensat __NR_utimensat
330 _syscall4(int,sys_utimensat,int,dirfd,const char *,pathname,
331           const struct timespec *,tsp,int,flags)
332 #else
333 static int sys_utimensat(int dirfd, const char *pathname,
334                          const struct timespec times[2], int flags)
335 {
336     errno = ENOSYS;
337     return -1;
338 }
339 #endif
340 #endif /* TARGET_NR_utimensat */
341 
342 #ifdef CONFIG_INOTIFY
343 #include <sys/inotify.h>
344 
345 #if defined(TARGET_NR_inotify_init) && defined(__NR_inotify_init)
346 static int sys_inotify_init(void)
347 {
348   return (inotify_init());
349 }
350 #endif
351 #if defined(TARGET_NR_inotify_add_watch) && defined(__NR_inotify_add_watch)
352 static int sys_inotify_add_watch(int fd,const char *pathname, int32_t mask)
353 {
354   return (inotify_add_watch(fd, pathname, mask));
355 }
356 #endif
357 #if defined(TARGET_NR_inotify_rm_watch) && defined(__NR_inotify_rm_watch)
358 static int sys_inotify_rm_watch(int fd, int32_t wd)
359 {
360   return (inotify_rm_watch(fd, wd));
361 }
362 #endif
363 #ifdef CONFIG_INOTIFY1
364 #if defined(TARGET_NR_inotify_init1) && defined(__NR_inotify_init1)
365 static int sys_inotify_init1(int flags)
366 {
367   return (inotify_init1(flags));
368 }
369 #endif
370 #endif
371 #else
372 /* Userspace can usually survive runtime without inotify */
373 #undef TARGET_NR_inotify_init
374 #undef TARGET_NR_inotify_init1
375 #undef TARGET_NR_inotify_add_watch
376 #undef TARGET_NR_inotify_rm_watch
377 #endif /* CONFIG_INOTIFY  */
378 
379 #if defined(TARGET_NR_ppoll)
380 #ifndef __NR_ppoll
381 # define __NR_ppoll -1
382 #endif
383 #define __NR_sys_ppoll __NR_ppoll
384 _syscall5(int, sys_ppoll, struct pollfd *, fds, nfds_t, nfds,
385           struct timespec *, timeout, const sigset_t *, sigmask,
386           size_t, sigsetsize)
387 #endif
388 
389 #if defined(TARGET_NR_pselect6)
390 #ifndef __NR_pselect6
391 # define __NR_pselect6 -1
392 #endif
393 #define __NR_sys_pselect6 __NR_pselect6
394 _syscall6(int, sys_pselect6, int, nfds, fd_set *, readfds, fd_set *, writefds,
395           fd_set *, exceptfds, struct timespec *, timeout, void *, sig);
396 #endif
397 
398 #if defined(TARGET_NR_prlimit64)
399 #ifndef __NR_prlimit64
400 # define __NR_prlimit64 -1
401 #endif
402 #define __NR_sys_prlimit64 __NR_prlimit64
403 /* The glibc rlimit structure may not be that used by the underlying syscall */
404 struct host_rlimit64 {
405     uint64_t rlim_cur;
406     uint64_t rlim_max;
407 };
408 _syscall4(int, sys_prlimit64, pid_t, pid, int, resource,
409           const struct host_rlimit64 *, new_limit,
410           struct host_rlimit64 *, old_limit)
411 #endif
412 
413 
414 #if defined(TARGET_NR_timer_create)
415 /* Maxiumum of 32 active POSIX timers allowed at any one time. */
416 static timer_t g_posix_timers[32] = { 0, } ;
417 
418 static inline int next_free_host_timer(void)
419 {
420     int k ;
421     /* FIXME: Does finding the next free slot require a lock? */
422     for (k = 0; k < ARRAY_SIZE(g_posix_timers); k++) {
423         if (g_posix_timers[k] == 0) {
424             g_posix_timers[k] = (timer_t) 1;
425             return k;
426         }
427     }
428     return -1;
429 }
430 #endif
431 
432 /* ARM EABI and MIPS expect 64bit types aligned even on pairs or registers */
433 #ifdef TARGET_ARM
434 static inline int regpairs_aligned(void *cpu_env) {
435     return ((((CPUARMState *)cpu_env)->eabi) == 1) ;
436 }
437 #elif defined(TARGET_MIPS)
438 static inline int regpairs_aligned(void *cpu_env) { return 1; }
439 #elif defined(TARGET_PPC) && !defined(TARGET_PPC64)
440 /* SysV AVI for PPC32 expects 64bit parameters to be passed on odd/even pairs
441  * of registers which translates to the same as ARM/MIPS, because we start with
442  * r3 as arg1 */
443 static inline int regpairs_aligned(void *cpu_env) { return 1; }
444 #else
445 static inline int regpairs_aligned(void *cpu_env) { return 0; }
446 #endif
447 
448 #define ERRNO_TABLE_SIZE 1200
449 
450 /* target_to_host_errno_table[] is initialized from
451  * host_to_target_errno_table[] in syscall_init(). */
452 static uint16_t target_to_host_errno_table[ERRNO_TABLE_SIZE] = {
453 };
454 
455 /*
456  * This list is the union of errno values overridden in asm-<arch>/errno.h
457  * minus the errnos that are not actually generic to all archs.
458  */
459 static uint16_t host_to_target_errno_table[ERRNO_TABLE_SIZE] = {
460     [EIDRM]		= TARGET_EIDRM,
461     [ECHRNG]		= TARGET_ECHRNG,
462     [EL2NSYNC]		= TARGET_EL2NSYNC,
463     [EL3HLT]		= TARGET_EL3HLT,
464     [EL3RST]		= TARGET_EL3RST,
465     [ELNRNG]		= TARGET_ELNRNG,
466     [EUNATCH]		= TARGET_EUNATCH,
467     [ENOCSI]		= TARGET_ENOCSI,
468     [EL2HLT]		= TARGET_EL2HLT,
469     [EDEADLK]		= TARGET_EDEADLK,
470     [ENOLCK]		= TARGET_ENOLCK,
471     [EBADE]		= TARGET_EBADE,
472     [EBADR]		= TARGET_EBADR,
473     [EXFULL]		= TARGET_EXFULL,
474     [ENOANO]		= TARGET_ENOANO,
475     [EBADRQC]		= TARGET_EBADRQC,
476     [EBADSLT]		= TARGET_EBADSLT,
477     [EBFONT]		= TARGET_EBFONT,
478     [ENOSTR]		= TARGET_ENOSTR,
479     [ENODATA]		= TARGET_ENODATA,
480     [ETIME]		= TARGET_ETIME,
481     [ENOSR]		= TARGET_ENOSR,
482     [ENONET]		= TARGET_ENONET,
483     [ENOPKG]		= TARGET_ENOPKG,
484     [EREMOTE]		= TARGET_EREMOTE,
485     [ENOLINK]		= TARGET_ENOLINK,
486     [EADV]		= TARGET_EADV,
487     [ESRMNT]		= TARGET_ESRMNT,
488     [ECOMM]		= TARGET_ECOMM,
489     [EPROTO]		= TARGET_EPROTO,
490     [EDOTDOT]		= TARGET_EDOTDOT,
491     [EMULTIHOP]		= TARGET_EMULTIHOP,
492     [EBADMSG]		= TARGET_EBADMSG,
493     [ENAMETOOLONG]	= TARGET_ENAMETOOLONG,
494     [EOVERFLOW]		= TARGET_EOVERFLOW,
495     [ENOTUNIQ]		= TARGET_ENOTUNIQ,
496     [EBADFD]		= TARGET_EBADFD,
497     [EREMCHG]		= TARGET_EREMCHG,
498     [ELIBACC]		= TARGET_ELIBACC,
499     [ELIBBAD]		= TARGET_ELIBBAD,
500     [ELIBSCN]		= TARGET_ELIBSCN,
501     [ELIBMAX]		= TARGET_ELIBMAX,
502     [ELIBEXEC]		= TARGET_ELIBEXEC,
503     [EILSEQ]		= TARGET_EILSEQ,
504     [ENOSYS]		= TARGET_ENOSYS,
505     [ELOOP]		= TARGET_ELOOP,
506     [ERESTART]		= TARGET_ERESTART,
507     [ESTRPIPE]		= TARGET_ESTRPIPE,
508     [ENOTEMPTY]		= TARGET_ENOTEMPTY,
509     [EUSERS]		= TARGET_EUSERS,
510     [ENOTSOCK]		= TARGET_ENOTSOCK,
511     [EDESTADDRREQ]	= TARGET_EDESTADDRREQ,
512     [EMSGSIZE]		= TARGET_EMSGSIZE,
513     [EPROTOTYPE]	= TARGET_EPROTOTYPE,
514     [ENOPROTOOPT]	= TARGET_ENOPROTOOPT,
515     [EPROTONOSUPPORT]	= TARGET_EPROTONOSUPPORT,
516     [ESOCKTNOSUPPORT]	= TARGET_ESOCKTNOSUPPORT,
517     [EOPNOTSUPP]	= TARGET_EOPNOTSUPP,
518     [EPFNOSUPPORT]	= TARGET_EPFNOSUPPORT,
519     [EAFNOSUPPORT]	= TARGET_EAFNOSUPPORT,
520     [EADDRINUSE]	= TARGET_EADDRINUSE,
521     [EADDRNOTAVAIL]	= TARGET_EADDRNOTAVAIL,
522     [ENETDOWN]		= TARGET_ENETDOWN,
523     [ENETUNREACH]	= TARGET_ENETUNREACH,
524     [ENETRESET]		= TARGET_ENETRESET,
525     [ECONNABORTED]	= TARGET_ECONNABORTED,
526     [ECONNRESET]	= TARGET_ECONNRESET,
527     [ENOBUFS]		= TARGET_ENOBUFS,
528     [EISCONN]		= TARGET_EISCONN,
529     [ENOTCONN]		= TARGET_ENOTCONN,
530     [EUCLEAN]		= TARGET_EUCLEAN,
531     [ENOTNAM]		= TARGET_ENOTNAM,
532     [ENAVAIL]		= TARGET_ENAVAIL,
533     [EISNAM]		= TARGET_EISNAM,
534     [EREMOTEIO]		= TARGET_EREMOTEIO,
535     [ESHUTDOWN]		= TARGET_ESHUTDOWN,
536     [ETOOMANYREFS]	= TARGET_ETOOMANYREFS,
537     [ETIMEDOUT]		= TARGET_ETIMEDOUT,
538     [ECONNREFUSED]	= TARGET_ECONNREFUSED,
539     [EHOSTDOWN]		= TARGET_EHOSTDOWN,
540     [EHOSTUNREACH]	= TARGET_EHOSTUNREACH,
541     [EALREADY]		= TARGET_EALREADY,
542     [EINPROGRESS]	= TARGET_EINPROGRESS,
543     [ESTALE]		= TARGET_ESTALE,
544     [ECANCELED]		= TARGET_ECANCELED,
545     [ENOMEDIUM]		= TARGET_ENOMEDIUM,
546     [EMEDIUMTYPE]	= TARGET_EMEDIUMTYPE,
547 #ifdef ENOKEY
548     [ENOKEY]		= TARGET_ENOKEY,
549 #endif
550 #ifdef EKEYEXPIRED
551     [EKEYEXPIRED]	= TARGET_EKEYEXPIRED,
552 #endif
553 #ifdef EKEYREVOKED
554     [EKEYREVOKED]	= TARGET_EKEYREVOKED,
555 #endif
556 #ifdef EKEYREJECTED
557     [EKEYREJECTED]	= TARGET_EKEYREJECTED,
558 #endif
559 #ifdef EOWNERDEAD
560     [EOWNERDEAD]	= TARGET_EOWNERDEAD,
561 #endif
562 #ifdef ENOTRECOVERABLE
563     [ENOTRECOVERABLE]	= TARGET_ENOTRECOVERABLE,
564 #endif
565 };
566 
567 static inline int host_to_target_errno(int err)
568 {
569     if(host_to_target_errno_table[err])
570         return host_to_target_errno_table[err];
571     return err;
572 }
573 
574 static inline int target_to_host_errno(int err)
575 {
576     if (target_to_host_errno_table[err])
577         return target_to_host_errno_table[err];
578     return err;
579 }
580 
581 static inline abi_long get_errno(abi_long ret)
582 {
583     if (ret == -1)
584         return -host_to_target_errno(errno);
585     else
586         return ret;
587 }
588 
589 static inline int is_error(abi_long ret)
590 {
591     return (abi_ulong)ret >= (abi_ulong)(-4096);
592 }
593 
594 char *target_strerror(int err)
595 {
596     if ((err >= ERRNO_TABLE_SIZE) || (err < 0)) {
597         return NULL;
598     }
599     return strerror(target_to_host_errno(err));
600 }
601 
602 static inline int host_to_target_sock_type(int host_type)
603 {
604     int target_type;
605 
606     switch (host_type & 0xf /* SOCK_TYPE_MASK */) {
607     case SOCK_DGRAM:
608         target_type = TARGET_SOCK_DGRAM;
609         break;
610     case SOCK_STREAM:
611         target_type = TARGET_SOCK_STREAM;
612         break;
613     default:
614         target_type = host_type & 0xf /* SOCK_TYPE_MASK */;
615         break;
616     }
617 
618 #if defined(SOCK_CLOEXEC)
619     if (host_type & SOCK_CLOEXEC) {
620         target_type |= TARGET_SOCK_CLOEXEC;
621     }
622 #endif
623 
624 #if defined(SOCK_NONBLOCK)
625     if (host_type & SOCK_NONBLOCK) {
626         target_type |= TARGET_SOCK_NONBLOCK;
627     }
628 #endif
629 
630     return target_type;
631 }
632 
633 static abi_ulong target_brk;
634 static abi_ulong target_original_brk;
635 static abi_ulong brk_page;
636 
637 void target_set_brk(abi_ulong new_brk)
638 {
639     target_original_brk = target_brk = HOST_PAGE_ALIGN(new_brk);
640     brk_page = HOST_PAGE_ALIGN(target_brk);
641 }
642 
643 //#define DEBUGF_BRK(message, args...) do { fprintf(stderr, (message), ## args); } while (0)
644 #define DEBUGF_BRK(message, args...)
645 
646 /* do_brk() must return target values and target errnos. */
647 abi_long do_brk(abi_ulong new_brk)
648 {
649     abi_long mapped_addr;
650     int	new_alloc_size;
651 
652     DEBUGF_BRK("do_brk(" TARGET_ABI_FMT_lx ") -> ", new_brk);
653 
654     if (!new_brk) {
655         DEBUGF_BRK(TARGET_ABI_FMT_lx " (!new_brk)\n", target_brk);
656         return target_brk;
657     }
658     if (new_brk < target_original_brk) {
659         DEBUGF_BRK(TARGET_ABI_FMT_lx " (new_brk < target_original_brk)\n",
660                    target_brk);
661         return target_brk;
662     }
663 
664     /* If the new brk is less than the highest page reserved to the
665      * target heap allocation, set it and we're almost done...  */
666     if (new_brk <= brk_page) {
667         /* Heap contents are initialized to zero, as for anonymous
668          * mapped pages.  */
669         if (new_brk > target_brk) {
670             memset(g2h(target_brk), 0, new_brk - target_brk);
671         }
672 	target_brk = new_brk;
673         DEBUGF_BRK(TARGET_ABI_FMT_lx " (new_brk <= brk_page)\n", target_brk);
674     	return target_brk;
675     }
676 
677     /* We need to allocate more memory after the brk... Note that
678      * we don't use MAP_FIXED because that will map over the top of
679      * any existing mapping (like the one with the host libc or qemu
680      * itself); instead we treat "mapped but at wrong address" as
681      * a failure and unmap again.
682      */
683     new_alloc_size = HOST_PAGE_ALIGN(new_brk - brk_page);
684     mapped_addr = get_errno(target_mmap(brk_page, new_alloc_size,
685                                         PROT_READ|PROT_WRITE,
686                                         MAP_ANON|MAP_PRIVATE, 0, 0));
687 
688     if (mapped_addr == brk_page) {
689         /* Heap contents are initialized to zero, as for anonymous
690          * mapped pages.  Technically the new pages are already
691          * initialized to zero since they *are* anonymous mapped
692          * pages, however we have to take care with the contents that
693          * come from the remaining part of the previous page: it may
694          * contains garbage data due to a previous heap usage (grown
695          * then shrunken).  */
696         memset(g2h(target_brk), 0, brk_page - target_brk);
697 
698         target_brk = new_brk;
699         brk_page = HOST_PAGE_ALIGN(target_brk);
700         DEBUGF_BRK(TARGET_ABI_FMT_lx " (mapped_addr == brk_page)\n",
701             target_brk);
702         return target_brk;
703     } else if (mapped_addr != -1) {
704         /* Mapped but at wrong address, meaning there wasn't actually
705          * enough space for this brk.
706          */
707         target_munmap(mapped_addr, new_alloc_size);
708         mapped_addr = -1;
709         DEBUGF_BRK(TARGET_ABI_FMT_lx " (mapped_addr != -1)\n", target_brk);
710     }
711     else {
712         DEBUGF_BRK(TARGET_ABI_FMT_lx " (otherwise)\n", target_brk);
713     }
714 
715 #if defined(TARGET_ALPHA)
716     /* We (partially) emulate OSF/1 on Alpha, which requires we
717        return a proper errno, not an unchanged brk value.  */
718     return -TARGET_ENOMEM;
719 #endif
720     /* For everything else, return the previous break. */
721     return target_brk;
722 }
723 
724 static inline abi_long copy_from_user_fdset(fd_set *fds,
725                                             abi_ulong target_fds_addr,
726                                             int n)
727 {
728     int i, nw, j, k;
729     abi_ulong b, *target_fds;
730 
731     nw = (n + TARGET_ABI_BITS - 1) / TARGET_ABI_BITS;
732     if (!(target_fds = lock_user(VERIFY_READ,
733                                  target_fds_addr,
734                                  sizeof(abi_ulong) * nw,
735                                  1)))
736         return -TARGET_EFAULT;
737 
738     FD_ZERO(fds);
739     k = 0;
740     for (i = 0; i < nw; i++) {
741         /* grab the abi_ulong */
742         __get_user(b, &target_fds[i]);
743         for (j = 0; j < TARGET_ABI_BITS; j++) {
744             /* check the bit inside the abi_ulong */
745             if ((b >> j) & 1)
746                 FD_SET(k, fds);
747             k++;
748         }
749     }
750 
751     unlock_user(target_fds, target_fds_addr, 0);
752 
753     return 0;
754 }
755 
756 static inline abi_ulong copy_from_user_fdset_ptr(fd_set *fds, fd_set **fds_ptr,
757                                                  abi_ulong target_fds_addr,
758                                                  int n)
759 {
760     if (target_fds_addr) {
761         if (copy_from_user_fdset(fds, target_fds_addr, n))
762             return -TARGET_EFAULT;
763         *fds_ptr = fds;
764     } else {
765         *fds_ptr = NULL;
766     }
767     return 0;
768 }
769 
770 static inline abi_long copy_to_user_fdset(abi_ulong target_fds_addr,
771                                           const fd_set *fds,
772                                           int n)
773 {
774     int i, nw, j, k;
775     abi_long v;
776     abi_ulong *target_fds;
777 
778     nw = (n + TARGET_ABI_BITS - 1) / TARGET_ABI_BITS;
779     if (!(target_fds = lock_user(VERIFY_WRITE,
780                                  target_fds_addr,
781                                  sizeof(abi_ulong) * nw,
782                                  0)))
783         return -TARGET_EFAULT;
784 
785     k = 0;
786     for (i = 0; i < nw; i++) {
787         v = 0;
788         for (j = 0; j < TARGET_ABI_BITS; j++) {
789             v |= ((abi_ulong)(FD_ISSET(k, fds) != 0) << j);
790             k++;
791         }
792         __put_user(v, &target_fds[i]);
793     }
794 
795     unlock_user(target_fds, target_fds_addr, sizeof(abi_ulong) * nw);
796 
797     return 0;
798 }
799 
800 #if defined(__alpha__)
801 #define HOST_HZ 1024
802 #else
803 #define HOST_HZ 100
804 #endif
805 
806 static inline abi_long host_to_target_clock_t(long ticks)
807 {
808 #if HOST_HZ == TARGET_HZ
809     return ticks;
810 #else
811     return ((int64_t)ticks * TARGET_HZ) / HOST_HZ;
812 #endif
813 }
814 
815 static inline abi_long host_to_target_rusage(abi_ulong target_addr,
816                                              const struct rusage *rusage)
817 {
818     struct target_rusage *target_rusage;
819 
820     if (!lock_user_struct(VERIFY_WRITE, target_rusage, target_addr, 0))
821         return -TARGET_EFAULT;
822     target_rusage->ru_utime.tv_sec = tswapal(rusage->ru_utime.tv_sec);
823     target_rusage->ru_utime.tv_usec = tswapal(rusage->ru_utime.tv_usec);
824     target_rusage->ru_stime.tv_sec = tswapal(rusage->ru_stime.tv_sec);
825     target_rusage->ru_stime.tv_usec = tswapal(rusage->ru_stime.tv_usec);
826     target_rusage->ru_maxrss = tswapal(rusage->ru_maxrss);
827     target_rusage->ru_ixrss = tswapal(rusage->ru_ixrss);
828     target_rusage->ru_idrss = tswapal(rusage->ru_idrss);
829     target_rusage->ru_isrss = tswapal(rusage->ru_isrss);
830     target_rusage->ru_minflt = tswapal(rusage->ru_minflt);
831     target_rusage->ru_majflt = tswapal(rusage->ru_majflt);
832     target_rusage->ru_nswap = tswapal(rusage->ru_nswap);
833     target_rusage->ru_inblock = tswapal(rusage->ru_inblock);
834     target_rusage->ru_oublock = tswapal(rusage->ru_oublock);
835     target_rusage->ru_msgsnd = tswapal(rusage->ru_msgsnd);
836     target_rusage->ru_msgrcv = tswapal(rusage->ru_msgrcv);
837     target_rusage->ru_nsignals = tswapal(rusage->ru_nsignals);
838     target_rusage->ru_nvcsw = tswapal(rusage->ru_nvcsw);
839     target_rusage->ru_nivcsw = tswapal(rusage->ru_nivcsw);
840     unlock_user_struct(target_rusage, target_addr, 1);
841 
842     return 0;
843 }
844 
845 static inline rlim_t target_to_host_rlim(abi_ulong target_rlim)
846 {
847     abi_ulong target_rlim_swap;
848     rlim_t result;
849 
850     target_rlim_swap = tswapal(target_rlim);
851     if (target_rlim_swap == TARGET_RLIM_INFINITY)
852         return RLIM_INFINITY;
853 
854     result = target_rlim_swap;
855     if (target_rlim_swap != (rlim_t)result)
856         return RLIM_INFINITY;
857 
858     return result;
859 }
860 
861 static inline abi_ulong host_to_target_rlim(rlim_t rlim)
862 {
863     abi_ulong target_rlim_swap;
864     abi_ulong result;
865 
866     if (rlim == RLIM_INFINITY || rlim != (abi_long)rlim)
867         target_rlim_swap = TARGET_RLIM_INFINITY;
868     else
869         target_rlim_swap = rlim;
870     result = tswapal(target_rlim_swap);
871 
872     return result;
873 }
874 
875 static inline int target_to_host_resource(int code)
876 {
877     switch (code) {
878     case TARGET_RLIMIT_AS:
879         return RLIMIT_AS;
880     case TARGET_RLIMIT_CORE:
881         return RLIMIT_CORE;
882     case TARGET_RLIMIT_CPU:
883         return RLIMIT_CPU;
884     case TARGET_RLIMIT_DATA:
885         return RLIMIT_DATA;
886     case TARGET_RLIMIT_FSIZE:
887         return RLIMIT_FSIZE;
888     case TARGET_RLIMIT_LOCKS:
889         return RLIMIT_LOCKS;
890     case TARGET_RLIMIT_MEMLOCK:
891         return RLIMIT_MEMLOCK;
892     case TARGET_RLIMIT_MSGQUEUE:
893         return RLIMIT_MSGQUEUE;
894     case TARGET_RLIMIT_NICE:
895         return RLIMIT_NICE;
896     case TARGET_RLIMIT_NOFILE:
897         return RLIMIT_NOFILE;
898     case TARGET_RLIMIT_NPROC:
899         return RLIMIT_NPROC;
900     case TARGET_RLIMIT_RSS:
901         return RLIMIT_RSS;
902     case TARGET_RLIMIT_RTPRIO:
903         return RLIMIT_RTPRIO;
904     case TARGET_RLIMIT_SIGPENDING:
905         return RLIMIT_SIGPENDING;
906     case TARGET_RLIMIT_STACK:
907         return RLIMIT_STACK;
908     default:
909         return code;
910     }
911 }
912 
913 static inline abi_long copy_from_user_timeval(struct timeval *tv,
914                                               abi_ulong target_tv_addr)
915 {
916     struct target_timeval *target_tv;
917 
918     if (!lock_user_struct(VERIFY_READ, target_tv, target_tv_addr, 1))
919         return -TARGET_EFAULT;
920 
921     __get_user(tv->tv_sec, &target_tv->tv_sec);
922     __get_user(tv->tv_usec, &target_tv->tv_usec);
923 
924     unlock_user_struct(target_tv, target_tv_addr, 0);
925 
926     return 0;
927 }
928 
929 static inline abi_long copy_to_user_timeval(abi_ulong target_tv_addr,
930                                             const struct timeval *tv)
931 {
932     struct target_timeval *target_tv;
933 
934     if (!lock_user_struct(VERIFY_WRITE, target_tv, target_tv_addr, 0))
935         return -TARGET_EFAULT;
936 
937     __put_user(tv->tv_sec, &target_tv->tv_sec);
938     __put_user(tv->tv_usec, &target_tv->tv_usec);
939 
940     unlock_user_struct(target_tv, target_tv_addr, 1);
941 
942     return 0;
943 }
944 
945 static inline abi_long copy_from_user_timezone(struct timezone *tz,
946                                                abi_ulong target_tz_addr)
947 {
948     struct target_timezone *target_tz;
949 
950     if (!lock_user_struct(VERIFY_READ, target_tz, target_tz_addr, 1)) {
951         return -TARGET_EFAULT;
952     }
953 
954     __get_user(tz->tz_minuteswest, &target_tz->tz_minuteswest);
955     __get_user(tz->tz_dsttime, &target_tz->tz_dsttime);
956 
957     unlock_user_struct(target_tz, target_tz_addr, 0);
958 
959     return 0;
960 }
961 
962 #if defined(TARGET_NR_mq_open) && defined(__NR_mq_open)
963 #include <mqueue.h>
964 
965 static inline abi_long copy_from_user_mq_attr(struct mq_attr *attr,
966                                               abi_ulong target_mq_attr_addr)
967 {
968     struct target_mq_attr *target_mq_attr;
969 
970     if (!lock_user_struct(VERIFY_READ, target_mq_attr,
971                           target_mq_attr_addr, 1))
972         return -TARGET_EFAULT;
973 
974     __get_user(attr->mq_flags, &target_mq_attr->mq_flags);
975     __get_user(attr->mq_maxmsg, &target_mq_attr->mq_maxmsg);
976     __get_user(attr->mq_msgsize, &target_mq_attr->mq_msgsize);
977     __get_user(attr->mq_curmsgs, &target_mq_attr->mq_curmsgs);
978 
979     unlock_user_struct(target_mq_attr, target_mq_attr_addr, 0);
980 
981     return 0;
982 }
983 
984 static inline abi_long copy_to_user_mq_attr(abi_ulong target_mq_attr_addr,
985                                             const struct mq_attr *attr)
986 {
987     struct target_mq_attr *target_mq_attr;
988 
989     if (!lock_user_struct(VERIFY_WRITE, target_mq_attr,
990                           target_mq_attr_addr, 0))
991         return -TARGET_EFAULT;
992 
993     __put_user(attr->mq_flags, &target_mq_attr->mq_flags);
994     __put_user(attr->mq_maxmsg, &target_mq_attr->mq_maxmsg);
995     __put_user(attr->mq_msgsize, &target_mq_attr->mq_msgsize);
996     __put_user(attr->mq_curmsgs, &target_mq_attr->mq_curmsgs);
997 
998     unlock_user_struct(target_mq_attr, target_mq_attr_addr, 1);
999 
1000     return 0;
1001 }
1002 #endif
1003 
1004 #if defined(TARGET_NR_select) || defined(TARGET_NR__newselect)
1005 /* do_select() must return target values and target errnos. */
1006 static abi_long do_select(int n,
1007                           abi_ulong rfd_addr, abi_ulong wfd_addr,
1008                           abi_ulong efd_addr, abi_ulong target_tv_addr)
1009 {
1010     fd_set rfds, wfds, efds;
1011     fd_set *rfds_ptr, *wfds_ptr, *efds_ptr;
1012     struct timeval tv, *tv_ptr;
1013     abi_long ret;
1014 
1015     ret = copy_from_user_fdset_ptr(&rfds, &rfds_ptr, rfd_addr, n);
1016     if (ret) {
1017         return ret;
1018     }
1019     ret = copy_from_user_fdset_ptr(&wfds, &wfds_ptr, wfd_addr, n);
1020     if (ret) {
1021         return ret;
1022     }
1023     ret = copy_from_user_fdset_ptr(&efds, &efds_ptr, efd_addr, n);
1024     if (ret) {
1025         return ret;
1026     }
1027 
1028     if (target_tv_addr) {
1029         if (copy_from_user_timeval(&tv, target_tv_addr))
1030             return -TARGET_EFAULT;
1031         tv_ptr = &tv;
1032     } else {
1033         tv_ptr = NULL;
1034     }
1035 
1036     ret = get_errno(select(n, rfds_ptr, wfds_ptr, efds_ptr, tv_ptr));
1037 
1038     if (!is_error(ret)) {
1039         if (rfd_addr && copy_to_user_fdset(rfd_addr, &rfds, n))
1040             return -TARGET_EFAULT;
1041         if (wfd_addr && copy_to_user_fdset(wfd_addr, &wfds, n))
1042             return -TARGET_EFAULT;
1043         if (efd_addr && copy_to_user_fdset(efd_addr, &efds, n))
1044             return -TARGET_EFAULT;
1045 
1046         if (target_tv_addr && copy_to_user_timeval(target_tv_addr, &tv))
1047             return -TARGET_EFAULT;
1048     }
1049 
1050     return ret;
1051 }
1052 #endif
1053 
1054 static abi_long do_pipe2(int host_pipe[], int flags)
1055 {
1056 #ifdef CONFIG_PIPE2
1057     return pipe2(host_pipe, flags);
1058 #else
1059     return -ENOSYS;
1060 #endif
1061 }
1062 
1063 static abi_long do_pipe(void *cpu_env, abi_ulong pipedes,
1064                         int flags, int is_pipe2)
1065 {
1066     int host_pipe[2];
1067     abi_long ret;
1068     ret = flags ? do_pipe2(host_pipe, flags) : pipe(host_pipe);
1069 
1070     if (is_error(ret))
1071         return get_errno(ret);
1072 
1073     /* Several targets have special calling conventions for the original
1074        pipe syscall, but didn't replicate this into the pipe2 syscall.  */
1075     if (!is_pipe2) {
1076 #if defined(TARGET_ALPHA)
1077         ((CPUAlphaState *)cpu_env)->ir[IR_A4] = host_pipe[1];
1078         return host_pipe[0];
1079 #elif defined(TARGET_MIPS)
1080         ((CPUMIPSState*)cpu_env)->active_tc.gpr[3] = host_pipe[1];
1081         return host_pipe[0];
1082 #elif defined(TARGET_SH4)
1083         ((CPUSH4State*)cpu_env)->gregs[1] = host_pipe[1];
1084         return host_pipe[0];
1085 #elif defined(TARGET_SPARC)
1086         ((CPUSPARCState*)cpu_env)->regwptr[1] = host_pipe[1];
1087         return host_pipe[0];
1088 #endif
1089     }
1090 
1091     if (put_user_s32(host_pipe[0], pipedes)
1092         || put_user_s32(host_pipe[1], pipedes + sizeof(host_pipe[0])))
1093         return -TARGET_EFAULT;
1094     return get_errno(ret);
1095 }
1096 
1097 static inline abi_long target_to_host_ip_mreq(struct ip_mreqn *mreqn,
1098                                               abi_ulong target_addr,
1099                                               socklen_t len)
1100 {
1101     struct target_ip_mreqn *target_smreqn;
1102 
1103     target_smreqn = lock_user(VERIFY_READ, target_addr, len, 1);
1104     if (!target_smreqn)
1105         return -TARGET_EFAULT;
1106     mreqn->imr_multiaddr.s_addr = target_smreqn->imr_multiaddr.s_addr;
1107     mreqn->imr_address.s_addr = target_smreqn->imr_address.s_addr;
1108     if (len == sizeof(struct target_ip_mreqn))
1109         mreqn->imr_ifindex = tswapal(target_smreqn->imr_ifindex);
1110     unlock_user(target_smreqn, target_addr, 0);
1111 
1112     return 0;
1113 }
1114 
1115 static inline abi_long target_to_host_sockaddr(struct sockaddr *addr,
1116                                                abi_ulong target_addr,
1117                                                socklen_t len)
1118 {
1119     const socklen_t unix_maxlen = sizeof (struct sockaddr_un);
1120     sa_family_t sa_family;
1121     struct target_sockaddr *target_saddr;
1122 
1123     target_saddr = lock_user(VERIFY_READ, target_addr, len, 1);
1124     if (!target_saddr)
1125         return -TARGET_EFAULT;
1126 
1127     sa_family = tswap16(target_saddr->sa_family);
1128 
1129     /* Oops. The caller might send a incomplete sun_path; sun_path
1130      * must be terminated by \0 (see the manual page), but
1131      * unfortunately it is quite common to specify sockaddr_un
1132      * length as "strlen(x->sun_path)" while it should be
1133      * "strlen(...) + 1". We'll fix that here if needed.
1134      * Linux kernel has a similar feature.
1135      */
1136 
1137     if (sa_family == AF_UNIX) {
1138         if (len < unix_maxlen && len > 0) {
1139             char *cp = (char*)target_saddr;
1140 
1141             if ( cp[len-1] && !cp[len] )
1142                 len++;
1143         }
1144         if (len > unix_maxlen)
1145             len = unix_maxlen;
1146     }
1147 
1148     memcpy(addr, target_saddr, len);
1149     addr->sa_family = sa_family;
1150     if (sa_family == AF_PACKET) {
1151 	struct target_sockaddr_ll *lladdr;
1152 
1153 	lladdr = (struct target_sockaddr_ll *)addr;
1154 	lladdr->sll_ifindex = tswap32(lladdr->sll_ifindex);
1155 	lladdr->sll_hatype = tswap16(lladdr->sll_hatype);
1156     }
1157     unlock_user(target_saddr, target_addr, 0);
1158 
1159     return 0;
1160 }
1161 
1162 static inline abi_long host_to_target_sockaddr(abi_ulong target_addr,
1163                                                struct sockaddr *addr,
1164                                                socklen_t len)
1165 {
1166     struct target_sockaddr *target_saddr;
1167 
1168     target_saddr = lock_user(VERIFY_WRITE, target_addr, len, 0);
1169     if (!target_saddr)
1170         return -TARGET_EFAULT;
1171     memcpy(target_saddr, addr, len);
1172     target_saddr->sa_family = tswap16(addr->sa_family);
1173     unlock_user(target_saddr, target_addr, len);
1174 
1175     return 0;
1176 }
1177 
1178 static inline abi_long target_to_host_cmsg(struct msghdr *msgh,
1179                                            struct target_msghdr *target_msgh)
1180 {
1181     struct cmsghdr *cmsg = CMSG_FIRSTHDR(msgh);
1182     abi_long msg_controllen;
1183     abi_ulong target_cmsg_addr;
1184     struct target_cmsghdr *target_cmsg;
1185     socklen_t space = 0;
1186 
1187     msg_controllen = tswapal(target_msgh->msg_controllen);
1188     if (msg_controllen < sizeof (struct target_cmsghdr))
1189         goto the_end;
1190     target_cmsg_addr = tswapal(target_msgh->msg_control);
1191     target_cmsg = lock_user(VERIFY_READ, target_cmsg_addr, msg_controllen, 1);
1192     if (!target_cmsg)
1193         return -TARGET_EFAULT;
1194 
1195     while (cmsg && target_cmsg) {
1196         void *data = CMSG_DATA(cmsg);
1197         void *target_data = TARGET_CMSG_DATA(target_cmsg);
1198 
1199         int len = tswapal(target_cmsg->cmsg_len)
1200                   - TARGET_CMSG_ALIGN(sizeof (struct target_cmsghdr));
1201 
1202         space += CMSG_SPACE(len);
1203         if (space > msgh->msg_controllen) {
1204             space -= CMSG_SPACE(len);
1205             /* This is a QEMU bug, since we allocated the payload
1206              * area ourselves (unlike overflow in host-to-target
1207              * conversion, which is just the guest giving us a buffer
1208              * that's too small). It can't happen for the payload types
1209              * we currently support; if it becomes an issue in future
1210              * we would need to improve our allocation strategy to
1211              * something more intelligent than "twice the size of the
1212              * target buffer we're reading from".
1213              */
1214             gemu_log("Host cmsg overflow\n");
1215             break;
1216         }
1217 
1218         if (tswap32(target_cmsg->cmsg_level) == TARGET_SOL_SOCKET) {
1219             cmsg->cmsg_level = SOL_SOCKET;
1220         } else {
1221             cmsg->cmsg_level = tswap32(target_cmsg->cmsg_level);
1222         }
1223         cmsg->cmsg_type = tswap32(target_cmsg->cmsg_type);
1224         cmsg->cmsg_len = CMSG_LEN(len);
1225 
1226         if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
1227             int *fd = (int *)data;
1228             int *target_fd = (int *)target_data;
1229             int i, numfds = len / sizeof(int);
1230 
1231             for (i = 0; i < numfds; i++) {
1232                 __get_user(fd[i], target_fd + i);
1233             }
1234         } else if (cmsg->cmsg_level == SOL_SOCKET
1235                &&  cmsg->cmsg_type == SCM_CREDENTIALS) {
1236             struct ucred *cred = (struct ucred *)data;
1237             struct target_ucred *target_cred =
1238                 (struct target_ucred *)target_data;
1239 
1240             __get_user(cred->pid, &target_cred->pid);
1241             __get_user(cred->uid, &target_cred->uid);
1242             __get_user(cred->gid, &target_cred->gid);
1243         } else {
1244             gemu_log("Unsupported ancillary data: %d/%d\n",
1245                                         cmsg->cmsg_level, cmsg->cmsg_type);
1246             memcpy(data, target_data, len);
1247         }
1248 
1249         cmsg = CMSG_NXTHDR(msgh, cmsg);
1250         target_cmsg = TARGET_CMSG_NXTHDR(target_msgh, target_cmsg);
1251     }
1252     unlock_user(target_cmsg, target_cmsg_addr, 0);
1253  the_end:
1254     msgh->msg_controllen = space;
1255     return 0;
1256 }
1257 
1258 static inline abi_long host_to_target_cmsg(struct target_msghdr *target_msgh,
1259                                            struct msghdr *msgh)
1260 {
1261     struct cmsghdr *cmsg = CMSG_FIRSTHDR(msgh);
1262     abi_long msg_controllen;
1263     abi_ulong target_cmsg_addr;
1264     struct target_cmsghdr *target_cmsg;
1265     socklen_t space = 0;
1266 
1267     msg_controllen = tswapal(target_msgh->msg_controllen);
1268     if (msg_controllen < sizeof (struct target_cmsghdr))
1269         goto the_end;
1270     target_cmsg_addr = tswapal(target_msgh->msg_control);
1271     target_cmsg = lock_user(VERIFY_WRITE, target_cmsg_addr, msg_controllen, 0);
1272     if (!target_cmsg)
1273         return -TARGET_EFAULT;
1274 
1275     while (cmsg && target_cmsg) {
1276         void *data = CMSG_DATA(cmsg);
1277         void *target_data = TARGET_CMSG_DATA(target_cmsg);
1278 
1279         int len = cmsg->cmsg_len - CMSG_ALIGN(sizeof (struct cmsghdr));
1280         int tgt_len, tgt_space;
1281 
1282         /* We never copy a half-header but may copy half-data;
1283          * this is Linux's behaviour in put_cmsg(). Note that
1284          * truncation here is a guest problem (which we report
1285          * to the guest via the CTRUNC bit), unlike truncation
1286          * in target_to_host_cmsg, which is a QEMU bug.
1287          */
1288         if (msg_controllen < sizeof(struct cmsghdr)) {
1289             target_msgh->msg_flags |= tswap32(MSG_CTRUNC);
1290             break;
1291         }
1292 
1293         if (cmsg->cmsg_level == SOL_SOCKET) {
1294             target_cmsg->cmsg_level = tswap32(TARGET_SOL_SOCKET);
1295         } else {
1296             target_cmsg->cmsg_level = tswap32(cmsg->cmsg_level);
1297         }
1298         target_cmsg->cmsg_type = tswap32(cmsg->cmsg_type);
1299 
1300         tgt_len = TARGET_CMSG_LEN(len);
1301 
1302         /* Payload types which need a different size of payload on
1303          * the target must adjust tgt_len here.
1304          */
1305         switch (cmsg->cmsg_level) {
1306         case SOL_SOCKET:
1307             switch (cmsg->cmsg_type) {
1308             case SO_TIMESTAMP:
1309                 tgt_len = sizeof(struct target_timeval);
1310                 break;
1311             default:
1312                 break;
1313             }
1314         default:
1315             break;
1316         }
1317 
1318         if (msg_controllen < tgt_len) {
1319             target_msgh->msg_flags |= tswap32(MSG_CTRUNC);
1320             tgt_len = msg_controllen;
1321         }
1322 
1323         /* We must now copy-and-convert len bytes of payload
1324          * into tgt_len bytes of destination space. Bear in mind
1325          * that in both source and destination we may be dealing
1326          * with a truncated value!
1327          */
1328         switch (cmsg->cmsg_level) {
1329         case SOL_SOCKET:
1330             switch (cmsg->cmsg_type) {
1331             case SCM_RIGHTS:
1332             {
1333                 int *fd = (int *)data;
1334                 int *target_fd = (int *)target_data;
1335                 int i, numfds = tgt_len / sizeof(int);
1336 
1337                 for (i = 0; i < numfds; i++) {
1338                     __put_user(fd[i], target_fd + i);
1339                 }
1340                 break;
1341             }
1342             case SO_TIMESTAMP:
1343             {
1344                 struct timeval *tv = (struct timeval *)data;
1345                 struct target_timeval *target_tv =
1346                     (struct target_timeval *)target_data;
1347 
1348                 if (len != sizeof(struct timeval) ||
1349                     tgt_len != sizeof(struct target_timeval)) {
1350                     goto unimplemented;
1351                 }
1352 
1353                 /* copy struct timeval to target */
1354                 __put_user(tv->tv_sec, &target_tv->tv_sec);
1355                 __put_user(tv->tv_usec, &target_tv->tv_usec);
1356                 break;
1357             }
1358             case SCM_CREDENTIALS:
1359             {
1360                 struct ucred *cred = (struct ucred *)data;
1361                 struct target_ucred *target_cred =
1362                     (struct target_ucred *)target_data;
1363 
1364                 __put_user(cred->pid, &target_cred->pid);
1365                 __put_user(cred->uid, &target_cred->uid);
1366                 __put_user(cred->gid, &target_cred->gid);
1367                 break;
1368             }
1369             default:
1370                 goto unimplemented;
1371             }
1372             break;
1373 
1374         default:
1375         unimplemented:
1376             gemu_log("Unsupported ancillary data: %d/%d\n",
1377                                         cmsg->cmsg_level, cmsg->cmsg_type);
1378             memcpy(target_data, data, MIN(len, tgt_len));
1379             if (tgt_len > len) {
1380                 memset(target_data + len, 0, tgt_len - len);
1381             }
1382         }
1383 
1384         target_cmsg->cmsg_len = tswapal(tgt_len);
1385         tgt_space = TARGET_CMSG_SPACE(tgt_len);
1386         if (msg_controllen < tgt_space) {
1387             tgt_space = msg_controllen;
1388         }
1389         msg_controllen -= tgt_space;
1390         space += tgt_space;
1391         cmsg = CMSG_NXTHDR(msgh, cmsg);
1392         target_cmsg = TARGET_CMSG_NXTHDR(target_msgh, target_cmsg);
1393     }
1394     unlock_user(target_cmsg, target_cmsg_addr, space);
1395  the_end:
1396     target_msgh->msg_controllen = tswapal(space);
1397     return 0;
1398 }
1399 
1400 /* do_setsockopt() Must return target values and target errnos. */
1401 static abi_long do_setsockopt(int sockfd, int level, int optname,
1402                               abi_ulong optval_addr, socklen_t optlen)
1403 {
1404     abi_long ret;
1405     int val;
1406     struct ip_mreqn *ip_mreq;
1407     struct ip_mreq_source *ip_mreq_source;
1408 
1409     switch(level) {
1410     case SOL_TCP:
1411         /* TCP options all take an 'int' value.  */
1412         if (optlen < sizeof(uint32_t))
1413             return -TARGET_EINVAL;
1414 
1415         if (get_user_u32(val, optval_addr))
1416             return -TARGET_EFAULT;
1417         ret = get_errno(setsockopt(sockfd, level, optname, &val, sizeof(val)));
1418         break;
1419     case SOL_IP:
1420         switch(optname) {
1421         case IP_TOS:
1422         case IP_TTL:
1423         case IP_HDRINCL:
1424         case IP_ROUTER_ALERT:
1425         case IP_RECVOPTS:
1426         case IP_RETOPTS:
1427         case IP_PKTINFO:
1428         case IP_MTU_DISCOVER:
1429         case IP_RECVERR:
1430         case IP_RECVTOS:
1431 #ifdef IP_FREEBIND
1432         case IP_FREEBIND:
1433 #endif
1434         case IP_MULTICAST_TTL:
1435         case IP_MULTICAST_LOOP:
1436             val = 0;
1437             if (optlen >= sizeof(uint32_t)) {
1438                 if (get_user_u32(val, optval_addr))
1439                     return -TARGET_EFAULT;
1440             } else if (optlen >= 1) {
1441                 if (get_user_u8(val, optval_addr))
1442                     return -TARGET_EFAULT;
1443             }
1444             ret = get_errno(setsockopt(sockfd, level, optname, &val, sizeof(val)));
1445             break;
1446         case IP_ADD_MEMBERSHIP:
1447         case IP_DROP_MEMBERSHIP:
1448             if (optlen < sizeof (struct target_ip_mreq) ||
1449                 optlen > sizeof (struct target_ip_mreqn))
1450                 return -TARGET_EINVAL;
1451 
1452             ip_mreq = (struct ip_mreqn *) alloca(optlen);
1453             target_to_host_ip_mreq(ip_mreq, optval_addr, optlen);
1454             ret = get_errno(setsockopt(sockfd, level, optname, ip_mreq, optlen));
1455             break;
1456 
1457         case IP_BLOCK_SOURCE:
1458         case IP_UNBLOCK_SOURCE:
1459         case IP_ADD_SOURCE_MEMBERSHIP:
1460         case IP_DROP_SOURCE_MEMBERSHIP:
1461             if (optlen != sizeof (struct target_ip_mreq_source))
1462                 return -TARGET_EINVAL;
1463 
1464             ip_mreq_source = lock_user(VERIFY_READ, optval_addr, optlen, 1);
1465             ret = get_errno(setsockopt(sockfd, level, optname, ip_mreq_source, optlen));
1466             unlock_user (ip_mreq_source, optval_addr, 0);
1467             break;
1468 
1469         default:
1470             goto unimplemented;
1471         }
1472         break;
1473     case SOL_IPV6:
1474         switch (optname) {
1475         case IPV6_MTU_DISCOVER:
1476         case IPV6_MTU:
1477         case IPV6_V6ONLY:
1478         case IPV6_RECVPKTINFO:
1479             val = 0;
1480             if (optlen < sizeof(uint32_t)) {
1481                 return -TARGET_EINVAL;
1482             }
1483             if (get_user_u32(val, optval_addr)) {
1484                 return -TARGET_EFAULT;
1485             }
1486             ret = get_errno(setsockopt(sockfd, level, optname,
1487                                        &val, sizeof(val)));
1488             break;
1489         default:
1490             goto unimplemented;
1491         }
1492         break;
1493     case SOL_RAW:
1494         switch (optname) {
1495         case ICMP_FILTER:
1496             /* struct icmp_filter takes an u32 value */
1497             if (optlen < sizeof(uint32_t)) {
1498                 return -TARGET_EINVAL;
1499             }
1500 
1501             if (get_user_u32(val, optval_addr)) {
1502                 return -TARGET_EFAULT;
1503             }
1504             ret = get_errno(setsockopt(sockfd, level, optname,
1505                                        &val, sizeof(val)));
1506             break;
1507 
1508         default:
1509             goto unimplemented;
1510         }
1511         break;
1512     case TARGET_SOL_SOCKET:
1513         switch (optname) {
1514         case TARGET_SO_RCVTIMEO:
1515         {
1516                 struct timeval tv;
1517 
1518                 optname = SO_RCVTIMEO;
1519 
1520 set_timeout:
1521                 if (optlen != sizeof(struct target_timeval)) {
1522                     return -TARGET_EINVAL;
1523                 }
1524 
1525                 if (copy_from_user_timeval(&tv, optval_addr)) {
1526                     return -TARGET_EFAULT;
1527                 }
1528 
1529                 ret = get_errno(setsockopt(sockfd, SOL_SOCKET, optname,
1530                                 &tv, sizeof(tv)));
1531                 return ret;
1532         }
1533         case TARGET_SO_SNDTIMEO:
1534                 optname = SO_SNDTIMEO;
1535                 goto set_timeout;
1536         case TARGET_SO_ATTACH_FILTER:
1537         {
1538                 struct target_sock_fprog *tfprog;
1539                 struct target_sock_filter *tfilter;
1540                 struct sock_fprog fprog;
1541                 struct sock_filter *filter;
1542                 int i;
1543 
1544                 if (optlen != sizeof(*tfprog)) {
1545                     return -TARGET_EINVAL;
1546                 }
1547                 if (!lock_user_struct(VERIFY_READ, tfprog, optval_addr, 0)) {
1548                     return -TARGET_EFAULT;
1549                 }
1550                 if (!lock_user_struct(VERIFY_READ, tfilter,
1551                                       tswapal(tfprog->filter), 0)) {
1552                     unlock_user_struct(tfprog, optval_addr, 1);
1553                     return -TARGET_EFAULT;
1554                 }
1555 
1556                 fprog.len = tswap16(tfprog->len);
1557                 filter = malloc(fprog.len * sizeof(*filter));
1558                 if (filter == NULL) {
1559                     unlock_user_struct(tfilter, tfprog->filter, 1);
1560                     unlock_user_struct(tfprog, optval_addr, 1);
1561                     return -TARGET_ENOMEM;
1562                 }
1563                 for (i = 0; i < fprog.len; i++) {
1564                     filter[i].code = tswap16(tfilter[i].code);
1565                     filter[i].jt = tfilter[i].jt;
1566                     filter[i].jf = tfilter[i].jf;
1567                     filter[i].k = tswap32(tfilter[i].k);
1568                 }
1569                 fprog.filter = filter;
1570 
1571                 ret = get_errno(setsockopt(sockfd, SOL_SOCKET,
1572                                 SO_ATTACH_FILTER, &fprog, sizeof(fprog)));
1573                 free(filter);
1574 
1575                 unlock_user_struct(tfilter, tfprog->filter, 1);
1576                 unlock_user_struct(tfprog, optval_addr, 1);
1577                 return ret;
1578         }
1579 	case TARGET_SO_BINDTODEVICE:
1580 	{
1581 		char *dev_ifname, *addr_ifname;
1582 
1583 		if (optlen > IFNAMSIZ - 1) {
1584 		    optlen = IFNAMSIZ - 1;
1585 		}
1586 		dev_ifname = lock_user(VERIFY_READ, optval_addr, optlen, 1);
1587 		if (!dev_ifname) {
1588 		    return -TARGET_EFAULT;
1589 		}
1590 		optname = SO_BINDTODEVICE;
1591 		addr_ifname = alloca(IFNAMSIZ);
1592 		memcpy(addr_ifname, dev_ifname, optlen);
1593 		addr_ifname[optlen] = 0;
1594 		ret = get_errno(setsockopt(sockfd, level, optname, addr_ifname, optlen));
1595 		unlock_user (dev_ifname, optval_addr, 0);
1596 		return ret;
1597 	}
1598             /* Options with 'int' argument.  */
1599         case TARGET_SO_DEBUG:
1600 		optname = SO_DEBUG;
1601 		break;
1602         case TARGET_SO_REUSEADDR:
1603 		optname = SO_REUSEADDR;
1604 		break;
1605         case TARGET_SO_TYPE:
1606 		optname = SO_TYPE;
1607 		break;
1608         case TARGET_SO_ERROR:
1609 		optname = SO_ERROR;
1610 		break;
1611         case TARGET_SO_DONTROUTE:
1612 		optname = SO_DONTROUTE;
1613 		break;
1614         case TARGET_SO_BROADCAST:
1615 		optname = SO_BROADCAST;
1616 		break;
1617         case TARGET_SO_SNDBUF:
1618 		optname = SO_SNDBUF;
1619 		break;
1620         case TARGET_SO_SNDBUFFORCE:
1621                 optname = SO_SNDBUFFORCE;
1622                 break;
1623         case TARGET_SO_RCVBUF:
1624 		optname = SO_RCVBUF;
1625 		break;
1626         case TARGET_SO_RCVBUFFORCE:
1627                 optname = SO_RCVBUFFORCE;
1628                 break;
1629         case TARGET_SO_KEEPALIVE:
1630 		optname = SO_KEEPALIVE;
1631 		break;
1632         case TARGET_SO_OOBINLINE:
1633 		optname = SO_OOBINLINE;
1634 		break;
1635         case TARGET_SO_NO_CHECK:
1636 		optname = SO_NO_CHECK;
1637 		break;
1638         case TARGET_SO_PRIORITY:
1639 		optname = SO_PRIORITY;
1640 		break;
1641 #ifdef SO_BSDCOMPAT
1642         case TARGET_SO_BSDCOMPAT:
1643 		optname = SO_BSDCOMPAT;
1644 		break;
1645 #endif
1646         case TARGET_SO_PASSCRED:
1647 		optname = SO_PASSCRED;
1648 		break;
1649         case TARGET_SO_PASSSEC:
1650                 optname = SO_PASSSEC;
1651                 break;
1652         case TARGET_SO_TIMESTAMP:
1653 		optname = SO_TIMESTAMP;
1654 		break;
1655         case TARGET_SO_RCVLOWAT:
1656 		optname = SO_RCVLOWAT;
1657 		break;
1658             break;
1659         default:
1660             goto unimplemented;
1661         }
1662 	if (optlen < sizeof(uint32_t))
1663             return -TARGET_EINVAL;
1664 
1665 	if (get_user_u32(val, optval_addr))
1666             return -TARGET_EFAULT;
1667 	ret = get_errno(setsockopt(sockfd, SOL_SOCKET, optname, &val, sizeof(val)));
1668         break;
1669     default:
1670     unimplemented:
1671         gemu_log("Unsupported setsockopt level=%d optname=%d\n", level, optname);
1672         ret = -TARGET_ENOPROTOOPT;
1673     }
1674     return ret;
1675 }
1676 
1677 /* do_getsockopt() Must return target values and target errnos. */
1678 static abi_long do_getsockopt(int sockfd, int level, int optname,
1679                               abi_ulong optval_addr, abi_ulong optlen)
1680 {
1681     abi_long ret;
1682     int len, val;
1683     socklen_t lv;
1684 
1685     switch(level) {
1686     case TARGET_SOL_SOCKET:
1687         level = SOL_SOCKET;
1688         switch (optname) {
1689         /* These don't just return a single integer */
1690         case TARGET_SO_LINGER:
1691         case TARGET_SO_RCVTIMEO:
1692         case TARGET_SO_SNDTIMEO:
1693         case TARGET_SO_PEERNAME:
1694             goto unimplemented;
1695         case TARGET_SO_PEERCRED: {
1696             struct ucred cr;
1697             socklen_t crlen;
1698             struct target_ucred *tcr;
1699 
1700             if (get_user_u32(len, optlen)) {
1701                 return -TARGET_EFAULT;
1702             }
1703             if (len < 0) {
1704                 return -TARGET_EINVAL;
1705             }
1706 
1707             crlen = sizeof(cr);
1708             ret = get_errno(getsockopt(sockfd, level, SO_PEERCRED,
1709                                        &cr, &crlen));
1710             if (ret < 0) {
1711                 return ret;
1712             }
1713             if (len > crlen) {
1714                 len = crlen;
1715             }
1716             if (!lock_user_struct(VERIFY_WRITE, tcr, optval_addr, 0)) {
1717                 return -TARGET_EFAULT;
1718             }
1719             __put_user(cr.pid, &tcr->pid);
1720             __put_user(cr.uid, &tcr->uid);
1721             __put_user(cr.gid, &tcr->gid);
1722             unlock_user_struct(tcr, optval_addr, 1);
1723             if (put_user_u32(len, optlen)) {
1724                 return -TARGET_EFAULT;
1725             }
1726             break;
1727         }
1728         /* Options with 'int' argument.  */
1729         case TARGET_SO_DEBUG:
1730             optname = SO_DEBUG;
1731             goto int_case;
1732         case TARGET_SO_REUSEADDR:
1733             optname = SO_REUSEADDR;
1734             goto int_case;
1735         case TARGET_SO_TYPE:
1736             optname = SO_TYPE;
1737             goto int_case;
1738         case TARGET_SO_ERROR:
1739             optname = SO_ERROR;
1740             goto int_case;
1741         case TARGET_SO_DONTROUTE:
1742             optname = SO_DONTROUTE;
1743             goto int_case;
1744         case TARGET_SO_BROADCAST:
1745             optname = SO_BROADCAST;
1746             goto int_case;
1747         case TARGET_SO_SNDBUF:
1748             optname = SO_SNDBUF;
1749             goto int_case;
1750         case TARGET_SO_RCVBUF:
1751             optname = SO_RCVBUF;
1752             goto int_case;
1753         case TARGET_SO_KEEPALIVE:
1754             optname = SO_KEEPALIVE;
1755             goto int_case;
1756         case TARGET_SO_OOBINLINE:
1757             optname = SO_OOBINLINE;
1758             goto int_case;
1759         case TARGET_SO_NO_CHECK:
1760             optname = SO_NO_CHECK;
1761             goto int_case;
1762         case TARGET_SO_PRIORITY:
1763             optname = SO_PRIORITY;
1764             goto int_case;
1765 #ifdef SO_BSDCOMPAT
1766         case TARGET_SO_BSDCOMPAT:
1767             optname = SO_BSDCOMPAT;
1768             goto int_case;
1769 #endif
1770         case TARGET_SO_PASSCRED:
1771             optname = SO_PASSCRED;
1772             goto int_case;
1773         case TARGET_SO_TIMESTAMP:
1774             optname = SO_TIMESTAMP;
1775             goto int_case;
1776         case TARGET_SO_RCVLOWAT:
1777             optname = SO_RCVLOWAT;
1778             goto int_case;
1779         case TARGET_SO_ACCEPTCONN:
1780             optname = SO_ACCEPTCONN;
1781             goto int_case;
1782         default:
1783             goto int_case;
1784         }
1785         break;
1786     case SOL_TCP:
1787         /* TCP options all take an 'int' value.  */
1788     int_case:
1789         if (get_user_u32(len, optlen))
1790             return -TARGET_EFAULT;
1791         if (len < 0)
1792             return -TARGET_EINVAL;
1793         lv = sizeof(lv);
1794         ret = get_errno(getsockopt(sockfd, level, optname, &val, &lv));
1795         if (ret < 0)
1796             return ret;
1797         if (optname == SO_TYPE) {
1798             val = host_to_target_sock_type(val);
1799         }
1800         if (len > lv)
1801             len = lv;
1802         if (len == 4) {
1803             if (put_user_u32(val, optval_addr))
1804                 return -TARGET_EFAULT;
1805         } else {
1806             if (put_user_u8(val, optval_addr))
1807                 return -TARGET_EFAULT;
1808         }
1809         if (put_user_u32(len, optlen))
1810             return -TARGET_EFAULT;
1811         break;
1812     case SOL_IP:
1813         switch(optname) {
1814         case IP_TOS:
1815         case IP_TTL:
1816         case IP_HDRINCL:
1817         case IP_ROUTER_ALERT:
1818         case IP_RECVOPTS:
1819         case IP_RETOPTS:
1820         case IP_PKTINFO:
1821         case IP_MTU_DISCOVER:
1822         case IP_RECVERR:
1823         case IP_RECVTOS:
1824 #ifdef IP_FREEBIND
1825         case IP_FREEBIND:
1826 #endif
1827         case IP_MULTICAST_TTL:
1828         case IP_MULTICAST_LOOP:
1829             if (get_user_u32(len, optlen))
1830                 return -TARGET_EFAULT;
1831             if (len < 0)
1832                 return -TARGET_EINVAL;
1833             lv = sizeof(lv);
1834             ret = get_errno(getsockopt(sockfd, level, optname, &val, &lv));
1835             if (ret < 0)
1836                 return ret;
1837             if (len < sizeof(int) && len > 0 && val >= 0 && val < 255) {
1838                 len = 1;
1839                 if (put_user_u32(len, optlen)
1840                     || put_user_u8(val, optval_addr))
1841                     return -TARGET_EFAULT;
1842             } else {
1843                 if (len > sizeof(int))
1844                     len = sizeof(int);
1845                 if (put_user_u32(len, optlen)
1846                     || put_user_u32(val, optval_addr))
1847                     return -TARGET_EFAULT;
1848             }
1849             break;
1850         default:
1851             ret = -TARGET_ENOPROTOOPT;
1852             break;
1853         }
1854         break;
1855     default:
1856     unimplemented:
1857         gemu_log("getsockopt level=%d optname=%d not yet supported\n",
1858                  level, optname);
1859         ret = -TARGET_EOPNOTSUPP;
1860         break;
1861     }
1862     return ret;
1863 }
1864 
1865 static struct iovec *lock_iovec(int type, abi_ulong target_addr,
1866                                 int count, int copy)
1867 {
1868     struct target_iovec *target_vec;
1869     struct iovec *vec;
1870     abi_ulong total_len, max_len;
1871     int i;
1872     int err = 0;
1873     bool bad_address = false;
1874 
1875     if (count == 0) {
1876         errno = 0;
1877         return NULL;
1878     }
1879     if (count < 0 || count > IOV_MAX) {
1880         errno = EINVAL;
1881         return NULL;
1882     }
1883 
1884     vec = calloc(count, sizeof(struct iovec));
1885     if (vec == NULL) {
1886         errno = ENOMEM;
1887         return NULL;
1888     }
1889 
1890     target_vec = lock_user(VERIFY_READ, target_addr,
1891                            count * sizeof(struct target_iovec), 1);
1892     if (target_vec == NULL) {
1893         err = EFAULT;
1894         goto fail2;
1895     }
1896 
1897     /* ??? If host page size > target page size, this will result in a
1898        value larger than what we can actually support.  */
1899     max_len = 0x7fffffff & TARGET_PAGE_MASK;
1900     total_len = 0;
1901 
1902     for (i = 0; i < count; i++) {
1903         abi_ulong base = tswapal(target_vec[i].iov_base);
1904         abi_long len = tswapal(target_vec[i].iov_len);
1905 
1906         if (len < 0) {
1907             err = EINVAL;
1908             goto fail;
1909         } else if (len == 0) {
1910             /* Zero length pointer is ignored.  */
1911             vec[i].iov_base = 0;
1912         } else {
1913             vec[i].iov_base = lock_user(type, base, len, copy);
1914             /* If the first buffer pointer is bad, this is a fault.  But
1915              * subsequent bad buffers will result in a partial write; this
1916              * is realized by filling the vector with null pointers and
1917              * zero lengths. */
1918             if (!vec[i].iov_base) {
1919                 if (i == 0) {
1920                     err = EFAULT;
1921                     goto fail;
1922                 } else {
1923                     bad_address = true;
1924                 }
1925             }
1926             if (bad_address) {
1927                 len = 0;
1928             }
1929             if (len > max_len - total_len) {
1930                 len = max_len - total_len;
1931             }
1932         }
1933         vec[i].iov_len = len;
1934         total_len += len;
1935     }
1936 
1937     unlock_user(target_vec, target_addr, 0);
1938     return vec;
1939 
1940  fail:
1941     while (--i >= 0) {
1942         if (tswapal(target_vec[i].iov_len) > 0) {
1943             unlock_user(vec[i].iov_base, tswapal(target_vec[i].iov_base), 0);
1944         }
1945     }
1946     unlock_user(target_vec, target_addr, 0);
1947  fail2:
1948     free(vec);
1949     errno = err;
1950     return NULL;
1951 }
1952 
1953 static void unlock_iovec(struct iovec *vec, abi_ulong target_addr,
1954                          int count, int copy)
1955 {
1956     struct target_iovec *target_vec;
1957     int i;
1958 
1959     target_vec = lock_user(VERIFY_READ, target_addr,
1960                            count * sizeof(struct target_iovec), 1);
1961     if (target_vec) {
1962         for (i = 0; i < count; i++) {
1963             abi_ulong base = tswapal(target_vec[i].iov_base);
1964             abi_long len = tswapal(target_vec[i].iov_len);
1965             if (len < 0) {
1966                 break;
1967             }
1968             unlock_user(vec[i].iov_base, base, copy ? vec[i].iov_len : 0);
1969         }
1970         unlock_user(target_vec, target_addr, 0);
1971     }
1972 
1973     free(vec);
1974 }
1975 
1976 static inline int target_to_host_sock_type(int *type)
1977 {
1978     int host_type = 0;
1979     int target_type = *type;
1980 
1981     switch (target_type & TARGET_SOCK_TYPE_MASK) {
1982     case TARGET_SOCK_DGRAM:
1983         host_type = SOCK_DGRAM;
1984         break;
1985     case TARGET_SOCK_STREAM:
1986         host_type = SOCK_STREAM;
1987         break;
1988     default:
1989         host_type = target_type & TARGET_SOCK_TYPE_MASK;
1990         break;
1991     }
1992     if (target_type & TARGET_SOCK_CLOEXEC) {
1993 #if defined(SOCK_CLOEXEC)
1994         host_type |= SOCK_CLOEXEC;
1995 #else
1996         return -TARGET_EINVAL;
1997 #endif
1998     }
1999     if (target_type & TARGET_SOCK_NONBLOCK) {
2000 #if defined(SOCK_NONBLOCK)
2001         host_type |= SOCK_NONBLOCK;
2002 #elif !defined(O_NONBLOCK)
2003         return -TARGET_EINVAL;
2004 #endif
2005     }
2006     *type = host_type;
2007     return 0;
2008 }
2009 
2010 /* Try to emulate socket type flags after socket creation.  */
2011 static int sock_flags_fixup(int fd, int target_type)
2012 {
2013 #if !defined(SOCK_NONBLOCK) && defined(O_NONBLOCK)
2014     if (target_type & TARGET_SOCK_NONBLOCK) {
2015         int flags = fcntl(fd, F_GETFL);
2016         if (fcntl(fd, F_SETFL, O_NONBLOCK | flags) == -1) {
2017             close(fd);
2018             return -TARGET_EINVAL;
2019         }
2020     }
2021 #endif
2022     return fd;
2023 }
2024 
2025 /* do_socket() Must return target values and target errnos. */
2026 static abi_long do_socket(int domain, int type, int protocol)
2027 {
2028     int target_type = type;
2029     int ret;
2030 
2031     ret = target_to_host_sock_type(&type);
2032     if (ret) {
2033         return ret;
2034     }
2035 
2036     if (domain == PF_NETLINK)
2037         return -TARGET_EAFNOSUPPORT;
2038     ret = get_errno(socket(domain, type, protocol));
2039     if (ret >= 0) {
2040         ret = sock_flags_fixup(ret, target_type);
2041     }
2042     return ret;
2043 }
2044 
2045 /* do_bind() Must return target values and target errnos. */
2046 static abi_long do_bind(int sockfd, abi_ulong target_addr,
2047                         socklen_t addrlen)
2048 {
2049     void *addr;
2050     abi_long ret;
2051 
2052     if ((int)addrlen < 0) {
2053         return -TARGET_EINVAL;
2054     }
2055 
2056     addr = alloca(addrlen+1);
2057 
2058     ret = target_to_host_sockaddr(addr, target_addr, addrlen);
2059     if (ret)
2060         return ret;
2061 
2062     return get_errno(bind(sockfd, addr, addrlen));
2063 }
2064 
2065 /* do_connect() Must return target values and target errnos. */
2066 static abi_long do_connect(int sockfd, abi_ulong target_addr,
2067                            socklen_t addrlen)
2068 {
2069     void *addr;
2070     abi_long ret;
2071 
2072     if ((int)addrlen < 0) {
2073         return -TARGET_EINVAL;
2074     }
2075 
2076     addr = alloca(addrlen+1);
2077 
2078     ret = target_to_host_sockaddr(addr, target_addr, addrlen);
2079     if (ret)
2080         return ret;
2081 
2082     return get_errno(connect(sockfd, addr, addrlen));
2083 }
2084 
2085 /* do_sendrecvmsg_locked() Must return target values and target errnos. */
2086 static abi_long do_sendrecvmsg_locked(int fd, struct target_msghdr *msgp,
2087                                       int flags, int send)
2088 {
2089     abi_long ret, len;
2090     struct msghdr msg;
2091     int count;
2092     struct iovec *vec;
2093     abi_ulong target_vec;
2094 
2095     if (msgp->msg_name) {
2096         msg.msg_namelen = tswap32(msgp->msg_namelen);
2097         msg.msg_name = alloca(msg.msg_namelen+1);
2098         ret = target_to_host_sockaddr(msg.msg_name, tswapal(msgp->msg_name),
2099                                 msg.msg_namelen);
2100         if (ret) {
2101             goto out2;
2102         }
2103     } else {
2104         msg.msg_name = NULL;
2105         msg.msg_namelen = 0;
2106     }
2107     msg.msg_controllen = 2 * tswapal(msgp->msg_controllen);
2108     msg.msg_control = alloca(msg.msg_controllen);
2109     msg.msg_flags = tswap32(msgp->msg_flags);
2110 
2111     count = tswapal(msgp->msg_iovlen);
2112     target_vec = tswapal(msgp->msg_iov);
2113     vec = lock_iovec(send ? VERIFY_READ : VERIFY_WRITE,
2114                      target_vec, count, send);
2115     if (vec == NULL) {
2116         ret = -host_to_target_errno(errno);
2117         goto out2;
2118     }
2119     msg.msg_iovlen = count;
2120     msg.msg_iov = vec;
2121 
2122     if (send) {
2123         ret = target_to_host_cmsg(&msg, msgp);
2124         if (ret == 0)
2125             ret = get_errno(sendmsg(fd, &msg, flags));
2126     } else {
2127         ret = get_errno(recvmsg(fd, &msg, flags));
2128         if (!is_error(ret)) {
2129             len = ret;
2130             ret = host_to_target_cmsg(msgp, &msg);
2131             if (!is_error(ret)) {
2132                 msgp->msg_namelen = tswap32(msg.msg_namelen);
2133                 if (msg.msg_name != NULL) {
2134                     ret = host_to_target_sockaddr(tswapal(msgp->msg_name),
2135                                     msg.msg_name, msg.msg_namelen);
2136                     if (ret) {
2137                         goto out;
2138                     }
2139                 }
2140 
2141                 ret = len;
2142             }
2143         }
2144     }
2145 
2146 out:
2147     unlock_iovec(vec, target_vec, count, !send);
2148 out2:
2149     return ret;
2150 }
2151 
2152 static abi_long do_sendrecvmsg(int fd, abi_ulong target_msg,
2153                                int flags, int send)
2154 {
2155     abi_long ret;
2156     struct target_msghdr *msgp;
2157 
2158     if (!lock_user_struct(send ? VERIFY_READ : VERIFY_WRITE,
2159                           msgp,
2160                           target_msg,
2161                           send ? 1 : 0)) {
2162         return -TARGET_EFAULT;
2163     }
2164     ret = do_sendrecvmsg_locked(fd, msgp, flags, send);
2165     unlock_user_struct(msgp, target_msg, send ? 0 : 1);
2166     return ret;
2167 }
2168 
2169 #ifdef TARGET_NR_sendmmsg
2170 /* We don't rely on the C library to have sendmmsg/recvmmsg support,
2171  * so it might not have this *mmsg-specific flag either.
2172  */
2173 #ifndef MSG_WAITFORONE
2174 #define MSG_WAITFORONE 0x10000
2175 #endif
2176 
2177 static abi_long do_sendrecvmmsg(int fd, abi_ulong target_msgvec,
2178                                 unsigned int vlen, unsigned int flags,
2179                                 int send)
2180 {
2181     struct target_mmsghdr *mmsgp;
2182     abi_long ret = 0;
2183     int i;
2184 
2185     if (vlen > UIO_MAXIOV) {
2186         vlen = UIO_MAXIOV;
2187     }
2188 
2189     mmsgp = lock_user(VERIFY_WRITE, target_msgvec, sizeof(*mmsgp) * vlen, 1);
2190     if (!mmsgp) {
2191         return -TARGET_EFAULT;
2192     }
2193 
2194     for (i = 0; i < vlen; i++) {
2195         ret = do_sendrecvmsg_locked(fd, &mmsgp[i].msg_hdr, flags, send);
2196         if (is_error(ret)) {
2197             break;
2198         }
2199         mmsgp[i].msg_len = tswap32(ret);
2200         /* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */
2201         if (flags & MSG_WAITFORONE) {
2202             flags |= MSG_DONTWAIT;
2203         }
2204     }
2205 
2206     unlock_user(mmsgp, target_msgvec, sizeof(*mmsgp) * i);
2207 
2208     /* Return number of datagrams sent if we sent any at all;
2209      * otherwise return the error.
2210      */
2211     if (i) {
2212         return i;
2213     }
2214     return ret;
2215 }
2216 #endif
2217 
2218 /* If we don't have a system accept4() then just call accept.
2219  * The callsites to do_accept4() will ensure that they don't
2220  * pass a non-zero flags argument in this config.
2221  */
2222 #ifndef CONFIG_ACCEPT4
2223 static inline int accept4(int sockfd, struct sockaddr *addr,
2224                           socklen_t *addrlen, int flags)
2225 {
2226     assert(flags == 0);
2227     return accept(sockfd, addr, addrlen);
2228 }
2229 #endif
2230 
2231 /* do_accept4() Must return target values and target errnos. */
2232 static abi_long do_accept4(int fd, abi_ulong target_addr,
2233                            abi_ulong target_addrlen_addr, int flags)
2234 {
2235     socklen_t addrlen;
2236     void *addr;
2237     abi_long ret;
2238     int host_flags;
2239 
2240     host_flags = target_to_host_bitmask(flags, fcntl_flags_tbl);
2241 
2242     if (target_addr == 0) {
2243         return get_errno(accept4(fd, NULL, NULL, host_flags));
2244     }
2245 
2246     /* linux returns EINVAL if addrlen pointer is invalid */
2247     if (get_user_u32(addrlen, target_addrlen_addr))
2248         return -TARGET_EINVAL;
2249 
2250     if ((int)addrlen < 0) {
2251         return -TARGET_EINVAL;
2252     }
2253 
2254     if (!access_ok(VERIFY_WRITE, target_addr, addrlen))
2255         return -TARGET_EINVAL;
2256 
2257     addr = alloca(addrlen);
2258 
2259     ret = get_errno(accept4(fd, addr, &addrlen, host_flags));
2260     if (!is_error(ret)) {
2261         host_to_target_sockaddr(target_addr, addr, addrlen);
2262         if (put_user_u32(addrlen, target_addrlen_addr))
2263             ret = -TARGET_EFAULT;
2264     }
2265     return ret;
2266 }
2267 
2268 /* do_getpeername() Must return target values and target errnos. */
2269 static abi_long do_getpeername(int fd, abi_ulong target_addr,
2270                                abi_ulong target_addrlen_addr)
2271 {
2272     socklen_t addrlen;
2273     void *addr;
2274     abi_long ret;
2275 
2276     if (get_user_u32(addrlen, target_addrlen_addr))
2277         return -TARGET_EFAULT;
2278 
2279     if ((int)addrlen < 0) {
2280         return -TARGET_EINVAL;
2281     }
2282 
2283     if (!access_ok(VERIFY_WRITE, target_addr, addrlen))
2284         return -TARGET_EFAULT;
2285 
2286     addr = alloca(addrlen);
2287 
2288     ret = get_errno(getpeername(fd, addr, &addrlen));
2289     if (!is_error(ret)) {
2290         host_to_target_sockaddr(target_addr, addr, addrlen);
2291         if (put_user_u32(addrlen, target_addrlen_addr))
2292             ret = -TARGET_EFAULT;
2293     }
2294     return ret;
2295 }
2296 
2297 /* do_getsockname() Must return target values and target errnos. */
2298 static abi_long do_getsockname(int fd, abi_ulong target_addr,
2299                                abi_ulong target_addrlen_addr)
2300 {
2301     socklen_t addrlen;
2302     void *addr;
2303     abi_long ret;
2304 
2305     if (get_user_u32(addrlen, target_addrlen_addr))
2306         return -TARGET_EFAULT;
2307 
2308     if ((int)addrlen < 0) {
2309         return -TARGET_EINVAL;
2310     }
2311 
2312     if (!access_ok(VERIFY_WRITE, target_addr, addrlen))
2313         return -TARGET_EFAULT;
2314 
2315     addr = alloca(addrlen);
2316 
2317     ret = get_errno(getsockname(fd, addr, &addrlen));
2318     if (!is_error(ret)) {
2319         host_to_target_sockaddr(target_addr, addr, addrlen);
2320         if (put_user_u32(addrlen, target_addrlen_addr))
2321             ret = -TARGET_EFAULT;
2322     }
2323     return ret;
2324 }
2325 
2326 /* do_socketpair() Must return target values and target errnos. */
2327 static abi_long do_socketpair(int domain, int type, int protocol,
2328                               abi_ulong target_tab_addr)
2329 {
2330     int tab[2];
2331     abi_long ret;
2332 
2333     target_to_host_sock_type(&type);
2334 
2335     ret = get_errno(socketpair(domain, type, protocol, tab));
2336     if (!is_error(ret)) {
2337         if (put_user_s32(tab[0], target_tab_addr)
2338             || put_user_s32(tab[1], target_tab_addr + sizeof(tab[0])))
2339             ret = -TARGET_EFAULT;
2340     }
2341     return ret;
2342 }
2343 
2344 /* do_sendto() Must return target values and target errnos. */
2345 static abi_long do_sendto(int fd, abi_ulong msg, size_t len, int flags,
2346                           abi_ulong target_addr, socklen_t addrlen)
2347 {
2348     void *addr;
2349     void *host_msg;
2350     abi_long ret;
2351 
2352     if ((int)addrlen < 0) {
2353         return -TARGET_EINVAL;
2354     }
2355 
2356     host_msg = lock_user(VERIFY_READ, msg, len, 1);
2357     if (!host_msg)
2358         return -TARGET_EFAULT;
2359     if (target_addr) {
2360         addr = alloca(addrlen+1);
2361         ret = target_to_host_sockaddr(addr, target_addr, addrlen);
2362         if (ret) {
2363             unlock_user(host_msg, msg, 0);
2364             return ret;
2365         }
2366         ret = get_errno(sendto(fd, host_msg, len, flags, addr, addrlen));
2367     } else {
2368         ret = get_errno(send(fd, host_msg, len, flags));
2369     }
2370     unlock_user(host_msg, msg, 0);
2371     return ret;
2372 }
2373 
2374 /* do_recvfrom() Must return target values and target errnos. */
2375 static abi_long do_recvfrom(int fd, abi_ulong msg, size_t len, int flags,
2376                             abi_ulong target_addr,
2377                             abi_ulong target_addrlen)
2378 {
2379     socklen_t addrlen;
2380     void *addr;
2381     void *host_msg;
2382     abi_long ret;
2383 
2384     host_msg = lock_user(VERIFY_WRITE, msg, len, 0);
2385     if (!host_msg)
2386         return -TARGET_EFAULT;
2387     if (target_addr) {
2388         if (get_user_u32(addrlen, target_addrlen)) {
2389             ret = -TARGET_EFAULT;
2390             goto fail;
2391         }
2392         if ((int)addrlen < 0) {
2393             ret = -TARGET_EINVAL;
2394             goto fail;
2395         }
2396         addr = alloca(addrlen);
2397         ret = get_errno(recvfrom(fd, host_msg, len, flags, addr, &addrlen));
2398     } else {
2399         addr = NULL; /* To keep compiler quiet.  */
2400         ret = get_errno(qemu_recv(fd, host_msg, len, flags));
2401     }
2402     if (!is_error(ret)) {
2403         if (target_addr) {
2404             host_to_target_sockaddr(target_addr, addr, addrlen);
2405             if (put_user_u32(addrlen, target_addrlen)) {
2406                 ret = -TARGET_EFAULT;
2407                 goto fail;
2408             }
2409         }
2410         unlock_user(host_msg, msg, len);
2411     } else {
2412 fail:
2413         unlock_user(host_msg, msg, 0);
2414     }
2415     return ret;
2416 }
2417 
2418 #ifdef TARGET_NR_socketcall
2419 /* do_socketcall() Must return target values and target errnos. */
2420 static abi_long do_socketcall(int num, abi_ulong vptr)
2421 {
2422     static const unsigned ac[] = { /* number of arguments per call */
2423         [SOCKOP_socket] = 3,      /* domain, type, protocol */
2424         [SOCKOP_bind] = 3,        /* sockfd, addr, addrlen */
2425         [SOCKOP_connect] = 3,     /* sockfd, addr, addrlen */
2426         [SOCKOP_listen] = 2,      /* sockfd, backlog */
2427         [SOCKOP_accept] = 3,      /* sockfd, addr, addrlen */
2428         [SOCKOP_accept4] = 4,     /* sockfd, addr, addrlen, flags */
2429         [SOCKOP_getsockname] = 3, /* sockfd, addr, addrlen */
2430         [SOCKOP_getpeername] = 3, /* sockfd, addr, addrlen */
2431         [SOCKOP_socketpair] = 4,  /* domain, type, protocol, tab */
2432         [SOCKOP_send] = 4,        /* sockfd, msg, len, flags */
2433         [SOCKOP_recv] = 4,        /* sockfd, msg, len, flags */
2434         [SOCKOP_sendto] = 6,      /* sockfd, msg, len, flags, addr, addrlen */
2435         [SOCKOP_recvfrom] = 6,    /* sockfd, msg, len, flags, addr, addrlen */
2436         [SOCKOP_shutdown] = 2,    /* sockfd, how */
2437         [SOCKOP_sendmsg] = 3,     /* sockfd, msg, flags */
2438         [SOCKOP_recvmsg] = 3,     /* sockfd, msg, flags */
2439         [SOCKOP_setsockopt] = 5,  /* sockfd, level, optname, optval, optlen */
2440         [SOCKOP_getsockopt] = 5,  /* sockfd, level, optname, optval, optlen */
2441     };
2442     abi_long a[6]; /* max 6 args */
2443 
2444     /* first, collect the arguments in a[] according to ac[] */
2445     if (num >= 0 && num < ARRAY_SIZE(ac)) {
2446         unsigned i;
2447         assert(ARRAY_SIZE(a) >= ac[num]); /* ensure we have space for args */
2448         for (i = 0; i < ac[num]; ++i) {
2449             if (get_user_ual(a[i], vptr + i * sizeof(abi_long)) != 0) {
2450                 return -TARGET_EFAULT;
2451             }
2452         }
2453     }
2454 
2455     /* now when we have the args, actually handle the call */
2456     switch (num) {
2457     case SOCKOP_socket: /* domain, type, protocol */
2458         return do_socket(a[0], a[1], a[2]);
2459     case SOCKOP_bind: /* sockfd, addr, addrlen */
2460         return do_bind(a[0], a[1], a[2]);
2461     case SOCKOP_connect: /* sockfd, addr, addrlen */
2462         return do_connect(a[0], a[1], a[2]);
2463     case SOCKOP_listen: /* sockfd, backlog */
2464         return get_errno(listen(a[0], a[1]));
2465     case SOCKOP_accept: /* sockfd, addr, addrlen */
2466         return do_accept4(a[0], a[1], a[2], 0);
2467     case SOCKOP_accept4: /* sockfd, addr, addrlen, flags */
2468         return do_accept4(a[0], a[1], a[2], a[3]);
2469     case SOCKOP_getsockname: /* sockfd, addr, addrlen */
2470         return do_getsockname(a[0], a[1], a[2]);
2471     case SOCKOP_getpeername: /* sockfd, addr, addrlen */
2472         return do_getpeername(a[0], a[1], a[2]);
2473     case SOCKOP_socketpair: /* domain, type, protocol, tab */
2474         return do_socketpair(a[0], a[1], a[2], a[3]);
2475     case SOCKOP_send: /* sockfd, msg, len, flags */
2476         return do_sendto(a[0], a[1], a[2], a[3], 0, 0);
2477     case SOCKOP_recv: /* sockfd, msg, len, flags */
2478         return do_recvfrom(a[0], a[1], a[2], a[3], 0, 0);
2479     case SOCKOP_sendto: /* sockfd, msg, len, flags, addr, addrlen */
2480         return do_sendto(a[0], a[1], a[2], a[3], a[4], a[5]);
2481     case SOCKOP_recvfrom: /* sockfd, msg, len, flags, addr, addrlen */
2482         return do_recvfrom(a[0], a[1], a[2], a[3], a[4], a[5]);
2483     case SOCKOP_shutdown: /* sockfd, how */
2484         return get_errno(shutdown(a[0], a[1]));
2485     case SOCKOP_sendmsg: /* sockfd, msg, flags */
2486         return do_sendrecvmsg(a[0], a[1], a[2], 1);
2487     case SOCKOP_recvmsg: /* sockfd, msg, flags */
2488         return do_sendrecvmsg(a[0], a[1], a[2], 0);
2489     case SOCKOP_setsockopt: /* sockfd, level, optname, optval, optlen */
2490         return do_setsockopt(a[0], a[1], a[2], a[3], a[4]);
2491     case SOCKOP_getsockopt: /* sockfd, level, optname, optval, optlen */
2492         return do_getsockopt(a[0], a[1], a[2], a[3], a[4]);
2493     default:
2494         gemu_log("Unsupported socketcall: %d\n", num);
2495         return -TARGET_ENOSYS;
2496     }
2497 }
2498 #endif
2499 
2500 #define N_SHM_REGIONS	32
2501 
2502 static struct shm_region {
2503     abi_ulong	start;
2504     abi_ulong	size;
2505 } shm_regions[N_SHM_REGIONS];
2506 
2507 struct target_semid_ds
2508 {
2509   struct target_ipc_perm sem_perm;
2510   abi_ulong sem_otime;
2511 #if !defined(TARGET_PPC64)
2512   abi_ulong __unused1;
2513 #endif
2514   abi_ulong sem_ctime;
2515 #if !defined(TARGET_PPC64)
2516   abi_ulong __unused2;
2517 #endif
2518   abi_ulong sem_nsems;
2519   abi_ulong __unused3;
2520   abi_ulong __unused4;
2521 };
2522 
2523 static inline abi_long target_to_host_ipc_perm(struct ipc_perm *host_ip,
2524                                                abi_ulong target_addr)
2525 {
2526     struct target_ipc_perm *target_ip;
2527     struct target_semid_ds *target_sd;
2528 
2529     if (!lock_user_struct(VERIFY_READ, target_sd, target_addr, 1))
2530         return -TARGET_EFAULT;
2531     target_ip = &(target_sd->sem_perm);
2532     host_ip->__key = tswap32(target_ip->__key);
2533     host_ip->uid = tswap32(target_ip->uid);
2534     host_ip->gid = tswap32(target_ip->gid);
2535     host_ip->cuid = tswap32(target_ip->cuid);
2536     host_ip->cgid = tswap32(target_ip->cgid);
2537 #if defined(TARGET_ALPHA) || defined(TARGET_MIPS) || defined(TARGET_PPC)
2538     host_ip->mode = tswap32(target_ip->mode);
2539 #else
2540     host_ip->mode = tswap16(target_ip->mode);
2541 #endif
2542 #if defined(TARGET_PPC)
2543     host_ip->__seq = tswap32(target_ip->__seq);
2544 #else
2545     host_ip->__seq = tswap16(target_ip->__seq);
2546 #endif
2547     unlock_user_struct(target_sd, target_addr, 0);
2548     return 0;
2549 }
2550 
2551 static inline abi_long host_to_target_ipc_perm(abi_ulong target_addr,
2552                                                struct ipc_perm *host_ip)
2553 {
2554     struct target_ipc_perm *target_ip;
2555     struct target_semid_ds *target_sd;
2556 
2557     if (!lock_user_struct(VERIFY_WRITE, target_sd, target_addr, 0))
2558         return -TARGET_EFAULT;
2559     target_ip = &(target_sd->sem_perm);
2560     target_ip->__key = tswap32(host_ip->__key);
2561     target_ip->uid = tswap32(host_ip->uid);
2562     target_ip->gid = tswap32(host_ip->gid);
2563     target_ip->cuid = tswap32(host_ip->cuid);
2564     target_ip->cgid = tswap32(host_ip->cgid);
2565 #if defined(TARGET_ALPHA) || defined(TARGET_MIPS) || defined(TARGET_PPC)
2566     target_ip->mode = tswap32(host_ip->mode);
2567 #else
2568     target_ip->mode = tswap16(host_ip->mode);
2569 #endif
2570 #if defined(TARGET_PPC)
2571     target_ip->__seq = tswap32(host_ip->__seq);
2572 #else
2573     target_ip->__seq = tswap16(host_ip->__seq);
2574 #endif
2575     unlock_user_struct(target_sd, target_addr, 1);
2576     return 0;
2577 }
2578 
2579 static inline abi_long target_to_host_semid_ds(struct semid_ds *host_sd,
2580                                                abi_ulong target_addr)
2581 {
2582     struct target_semid_ds *target_sd;
2583 
2584     if (!lock_user_struct(VERIFY_READ, target_sd, target_addr, 1))
2585         return -TARGET_EFAULT;
2586     if (target_to_host_ipc_perm(&(host_sd->sem_perm),target_addr))
2587         return -TARGET_EFAULT;
2588     host_sd->sem_nsems = tswapal(target_sd->sem_nsems);
2589     host_sd->sem_otime = tswapal(target_sd->sem_otime);
2590     host_sd->sem_ctime = tswapal(target_sd->sem_ctime);
2591     unlock_user_struct(target_sd, target_addr, 0);
2592     return 0;
2593 }
2594 
2595 static inline abi_long host_to_target_semid_ds(abi_ulong target_addr,
2596                                                struct semid_ds *host_sd)
2597 {
2598     struct target_semid_ds *target_sd;
2599 
2600     if (!lock_user_struct(VERIFY_WRITE, target_sd, target_addr, 0))
2601         return -TARGET_EFAULT;
2602     if (host_to_target_ipc_perm(target_addr,&(host_sd->sem_perm)))
2603         return -TARGET_EFAULT;
2604     target_sd->sem_nsems = tswapal(host_sd->sem_nsems);
2605     target_sd->sem_otime = tswapal(host_sd->sem_otime);
2606     target_sd->sem_ctime = tswapal(host_sd->sem_ctime);
2607     unlock_user_struct(target_sd, target_addr, 1);
2608     return 0;
2609 }
2610 
2611 struct target_seminfo {
2612     int semmap;
2613     int semmni;
2614     int semmns;
2615     int semmnu;
2616     int semmsl;
2617     int semopm;
2618     int semume;
2619     int semusz;
2620     int semvmx;
2621     int semaem;
2622 };
2623 
2624 static inline abi_long host_to_target_seminfo(abi_ulong target_addr,
2625                                               struct seminfo *host_seminfo)
2626 {
2627     struct target_seminfo *target_seminfo;
2628     if (!lock_user_struct(VERIFY_WRITE, target_seminfo, target_addr, 0))
2629         return -TARGET_EFAULT;
2630     __put_user(host_seminfo->semmap, &target_seminfo->semmap);
2631     __put_user(host_seminfo->semmni, &target_seminfo->semmni);
2632     __put_user(host_seminfo->semmns, &target_seminfo->semmns);
2633     __put_user(host_seminfo->semmnu, &target_seminfo->semmnu);
2634     __put_user(host_seminfo->semmsl, &target_seminfo->semmsl);
2635     __put_user(host_seminfo->semopm, &target_seminfo->semopm);
2636     __put_user(host_seminfo->semume, &target_seminfo->semume);
2637     __put_user(host_seminfo->semusz, &target_seminfo->semusz);
2638     __put_user(host_seminfo->semvmx, &target_seminfo->semvmx);
2639     __put_user(host_seminfo->semaem, &target_seminfo->semaem);
2640     unlock_user_struct(target_seminfo, target_addr, 1);
2641     return 0;
2642 }
2643 
2644 union semun {
2645 	int val;
2646 	struct semid_ds *buf;
2647 	unsigned short *array;
2648 	struct seminfo *__buf;
2649 };
2650 
2651 union target_semun {
2652 	int val;
2653 	abi_ulong buf;
2654 	abi_ulong array;
2655 	abi_ulong __buf;
2656 };
2657 
2658 static inline abi_long target_to_host_semarray(int semid, unsigned short **host_array,
2659                                                abi_ulong target_addr)
2660 {
2661     int nsems;
2662     unsigned short *array;
2663     union semun semun;
2664     struct semid_ds semid_ds;
2665     int i, ret;
2666 
2667     semun.buf = &semid_ds;
2668 
2669     ret = semctl(semid, 0, IPC_STAT, semun);
2670     if (ret == -1)
2671         return get_errno(ret);
2672 
2673     nsems = semid_ds.sem_nsems;
2674 
2675     *host_array = malloc(nsems*sizeof(unsigned short));
2676     if (!*host_array) {
2677         return -TARGET_ENOMEM;
2678     }
2679     array = lock_user(VERIFY_READ, target_addr,
2680                       nsems*sizeof(unsigned short), 1);
2681     if (!array) {
2682         free(*host_array);
2683         return -TARGET_EFAULT;
2684     }
2685 
2686     for(i=0; i<nsems; i++) {
2687         __get_user((*host_array)[i], &array[i]);
2688     }
2689     unlock_user(array, target_addr, 0);
2690 
2691     return 0;
2692 }
2693 
2694 static inline abi_long host_to_target_semarray(int semid, abi_ulong target_addr,
2695                                                unsigned short **host_array)
2696 {
2697     int nsems;
2698     unsigned short *array;
2699     union semun semun;
2700     struct semid_ds semid_ds;
2701     int i, ret;
2702 
2703     semun.buf = &semid_ds;
2704 
2705     ret = semctl(semid, 0, IPC_STAT, semun);
2706     if (ret == -1)
2707         return get_errno(ret);
2708 
2709     nsems = semid_ds.sem_nsems;
2710 
2711     array = lock_user(VERIFY_WRITE, target_addr,
2712                       nsems*sizeof(unsigned short), 0);
2713     if (!array)
2714         return -TARGET_EFAULT;
2715 
2716     for(i=0; i<nsems; i++) {
2717         __put_user((*host_array)[i], &array[i]);
2718     }
2719     free(*host_array);
2720     unlock_user(array, target_addr, 1);
2721 
2722     return 0;
2723 }
2724 
2725 static inline abi_long do_semctl(int semid, int semnum, int cmd,
2726                                  union target_semun target_su)
2727 {
2728     union semun arg;
2729     struct semid_ds dsarg;
2730     unsigned short *array = NULL;
2731     struct seminfo seminfo;
2732     abi_long ret = -TARGET_EINVAL;
2733     abi_long err;
2734     cmd &= 0xff;
2735 
2736     switch( cmd ) {
2737 	case GETVAL:
2738 	case SETVAL:
2739             /* In 64 bit cross-endian situations, we will erroneously pick up
2740              * the wrong half of the union for the "val" element.  To rectify
2741              * this, the entire 8-byte structure is byteswapped, followed by
2742 	     * a swap of the 4 byte val field. In other cases, the data is
2743 	     * already in proper host byte order. */
2744 	    if (sizeof(target_su.val) != (sizeof(target_su.buf))) {
2745 		target_su.buf = tswapal(target_su.buf);
2746 		arg.val = tswap32(target_su.val);
2747 	    } else {
2748 		arg.val = target_su.val;
2749 	    }
2750             ret = get_errno(semctl(semid, semnum, cmd, arg));
2751             break;
2752 	case GETALL:
2753 	case SETALL:
2754             err = target_to_host_semarray(semid, &array, target_su.array);
2755             if (err)
2756                 return err;
2757             arg.array = array;
2758             ret = get_errno(semctl(semid, semnum, cmd, arg));
2759             err = host_to_target_semarray(semid, target_su.array, &array);
2760             if (err)
2761                 return err;
2762             break;
2763 	case IPC_STAT:
2764 	case IPC_SET:
2765 	case SEM_STAT:
2766             err = target_to_host_semid_ds(&dsarg, target_su.buf);
2767             if (err)
2768                 return err;
2769             arg.buf = &dsarg;
2770             ret = get_errno(semctl(semid, semnum, cmd, arg));
2771             err = host_to_target_semid_ds(target_su.buf, &dsarg);
2772             if (err)
2773                 return err;
2774             break;
2775 	case IPC_INFO:
2776 	case SEM_INFO:
2777             arg.__buf = &seminfo;
2778             ret = get_errno(semctl(semid, semnum, cmd, arg));
2779             err = host_to_target_seminfo(target_su.__buf, &seminfo);
2780             if (err)
2781                 return err;
2782             break;
2783 	case IPC_RMID:
2784 	case GETPID:
2785 	case GETNCNT:
2786 	case GETZCNT:
2787             ret = get_errno(semctl(semid, semnum, cmd, NULL));
2788             break;
2789     }
2790 
2791     return ret;
2792 }
2793 
2794 struct target_sembuf {
2795     unsigned short sem_num;
2796     short sem_op;
2797     short sem_flg;
2798 };
2799 
2800 static inline abi_long target_to_host_sembuf(struct sembuf *host_sembuf,
2801                                              abi_ulong target_addr,
2802                                              unsigned nsops)
2803 {
2804     struct target_sembuf *target_sembuf;
2805     int i;
2806 
2807     target_sembuf = lock_user(VERIFY_READ, target_addr,
2808                               nsops*sizeof(struct target_sembuf), 1);
2809     if (!target_sembuf)
2810         return -TARGET_EFAULT;
2811 
2812     for(i=0; i<nsops; i++) {
2813         __get_user(host_sembuf[i].sem_num, &target_sembuf[i].sem_num);
2814         __get_user(host_sembuf[i].sem_op, &target_sembuf[i].sem_op);
2815         __get_user(host_sembuf[i].sem_flg, &target_sembuf[i].sem_flg);
2816     }
2817 
2818     unlock_user(target_sembuf, target_addr, 0);
2819 
2820     return 0;
2821 }
2822 
2823 static inline abi_long do_semop(int semid, abi_long ptr, unsigned nsops)
2824 {
2825     struct sembuf sops[nsops];
2826 
2827     if (target_to_host_sembuf(sops, ptr, nsops))
2828         return -TARGET_EFAULT;
2829 
2830     return get_errno(semop(semid, sops, nsops));
2831 }
2832 
2833 struct target_msqid_ds
2834 {
2835     struct target_ipc_perm msg_perm;
2836     abi_ulong msg_stime;
2837 #if TARGET_ABI_BITS == 32
2838     abi_ulong __unused1;
2839 #endif
2840     abi_ulong msg_rtime;
2841 #if TARGET_ABI_BITS == 32
2842     abi_ulong __unused2;
2843 #endif
2844     abi_ulong msg_ctime;
2845 #if TARGET_ABI_BITS == 32
2846     abi_ulong __unused3;
2847 #endif
2848     abi_ulong __msg_cbytes;
2849     abi_ulong msg_qnum;
2850     abi_ulong msg_qbytes;
2851     abi_ulong msg_lspid;
2852     abi_ulong msg_lrpid;
2853     abi_ulong __unused4;
2854     abi_ulong __unused5;
2855 };
2856 
2857 static inline abi_long target_to_host_msqid_ds(struct msqid_ds *host_md,
2858                                                abi_ulong target_addr)
2859 {
2860     struct target_msqid_ds *target_md;
2861 
2862     if (!lock_user_struct(VERIFY_READ, target_md, target_addr, 1))
2863         return -TARGET_EFAULT;
2864     if (target_to_host_ipc_perm(&(host_md->msg_perm),target_addr))
2865         return -TARGET_EFAULT;
2866     host_md->msg_stime = tswapal(target_md->msg_stime);
2867     host_md->msg_rtime = tswapal(target_md->msg_rtime);
2868     host_md->msg_ctime = tswapal(target_md->msg_ctime);
2869     host_md->__msg_cbytes = tswapal(target_md->__msg_cbytes);
2870     host_md->msg_qnum = tswapal(target_md->msg_qnum);
2871     host_md->msg_qbytes = tswapal(target_md->msg_qbytes);
2872     host_md->msg_lspid = tswapal(target_md->msg_lspid);
2873     host_md->msg_lrpid = tswapal(target_md->msg_lrpid);
2874     unlock_user_struct(target_md, target_addr, 0);
2875     return 0;
2876 }
2877 
2878 static inline abi_long host_to_target_msqid_ds(abi_ulong target_addr,
2879                                                struct msqid_ds *host_md)
2880 {
2881     struct target_msqid_ds *target_md;
2882 
2883     if (!lock_user_struct(VERIFY_WRITE, target_md, target_addr, 0))
2884         return -TARGET_EFAULT;
2885     if (host_to_target_ipc_perm(target_addr,&(host_md->msg_perm)))
2886         return -TARGET_EFAULT;
2887     target_md->msg_stime = tswapal(host_md->msg_stime);
2888     target_md->msg_rtime = tswapal(host_md->msg_rtime);
2889     target_md->msg_ctime = tswapal(host_md->msg_ctime);
2890     target_md->__msg_cbytes = tswapal(host_md->__msg_cbytes);
2891     target_md->msg_qnum = tswapal(host_md->msg_qnum);
2892     target_md->msg_qbytes = tswapal(host_md->msg_qbytes);
2893     target_md->msg_lspid = tswapal(host_md->msg_lspid);
2894     target_md->msg_lrpid = tswapal(host_md->msg_lrpid);
2895     unlock_user_struct(target_md, target_addr, 1);
2896     return 0;
2897 }
2898 
2899 struct target_msginfo {
2900     int msgpool;
2901     int msgmap;
2902     int msgmax;
2903     int msgmnb;
2904     int msgmni;
2905     int msgssz;
2906     int msgtql;
2907     unsigned short int msgseg;
2908 };
2909 
2910 static inline abi_long host_to_target_msginfo(abi_ulong target_addr,
2911                                               struct msginfo *host_msginfo)
2912 {
2913     struct target_msginfo *target_msginfo;
2914     if (!lock_user_struct(VERIFY_WRITE, target_msginfo, target_addr, 0))
2915         return -TARGET_EFAULT;
2916     __put_user(host_msginfo->msgpool, &target_msginfo->msgpool);
2917     __put_user(host_msginfo->msgmap, &target_msginfo->msgmap);
2918     __put_user(host_msginfo->msgmax, &target_msginfo->msgmax);
2919     __put_user(host_msginfo->msgmnb, &target_msginfo->msgmnb);
2920     __put_user(host_msginfo->msgmni, &target_msginfo->msgmni);
2921     __put_user(host_msginfo->msgssz, &target_msginfo->msgssz);
2922     __put_user(host_msginfo->msgtql, &target_msginfo->msgtql);
2923     __put_user(host_msginfo->msgseg, &target_msginfo->msgseg);
2924     unlock_user_struct(target_msginfo, target_addr, 1);
2925     return 0;
2926 }
2927 
2928 static inline abi_long do_msgctl(int msgid, int cmd, abi_long ptr)
2929 {
2930     struct msqid_ds dsarg;
2931     struct msginfo msginfo;
2932     abi_long ret = -TARGET_EINVAL;
2933 
2934     cmd &= 0xff;
2935 
2936     switch (cmd) {
2937     case IPC_STAT:
2938     case IPC_SET:
2939     case MSG_STAT:
2940         if (target_to_host_msqid_ds(&dsarg,ptr))
2941             return -TARGET_EFAULT;
2942         ret = get_errno(msgctl(msgid, cmd, &dsarg));
2943         if (host_to_target_msqid_ds(ptr,&dsarg))
2944             return -TARGET_EFAULT;
2945         break;
2946     case IPC_RMID:
2947         ret = get_errno(msgctl(msgid, cmd, NULL));
2948         break;
2949     case IPC_INFO:
2950     case MSG_INFO:
2951         ret = get_errno(msgctl(msgid, cmd, (struct msqid_ds *)&msginfo));
2952         if (host_to_target_msginfo(ptr, &msginfo))
2953             return -TARGET_EFAULT;
2954         break;
2955     }
2956 
2957     return ret;
2958 }
2959 
2960 struct target_msgbuf {
2961     abi_long mtype;
2962     char	mtext[1];
2963 };
2964 
2965 static inline abi_long do_msgsnd(int msqid, abi_long msgp,
2966                                  ssize_t msgsz, int msgflg)
2967 {
2968     struct target_msgbuf *target_mb;
2969     struct msgbuf *host_mb;
2970     abi_long ret = 0;
2971 
2972     if (msgsz < 0) {
2973         return -TARGET_EINVAL;
2974     }
2975 
2976     if (!lock_user_struct(VERIFY_READ, target_mb, msgp, 0))
2977         return -TARGET_EFAULT;
2978     host_mb = malloc(msgsz+sizeof(long));
2979     if (!host_mb) {
2980         unlock_user_struct(target_mb, msgp, 0);
2981         return -TARGET_ENOMEM;
2982     }
2983     host_mb->mtype = (abi_long) tswapal(target_mb->mtype);
2984     memcpy(host_mb->mtext, target_mb->mtext, msgsz);
2985     ret = get_errno(msgsnd(msqid, host_mb, msgsz, msgflg));
2986     free(host_mb);
2987     unlock_user_struct(target_mb, msgp, 0);
2988 
2989     return ret;
2990 }
2991 
2992 static inline abi_long do_msgrcv(int msqid, abi_long msgp,
2993                                  unsigned int msgsz, abi_long msgtyp,
2994                                  int msgflg)
2995 {
2996     struct target_msgbuf *target_mb;
2997     char *target_mtext;
2998     struct msgbuf *host_mb;
2999     abi_long ret = 0;
3000 
3001     if (!lock_user_struct(VERIFY_WRITE, target_mb, msgp, 0))
3002         return -TARGET_EFAULT;
3003 
3004     host_mb = g_malloc(msgsz+sizeof(long));
3005     ret = get_errno(msgrcv(msqid, host_mb, msgsz, msgtyp, msgflg));
3006 
3007     if (ret > 0) {
3008         abi_ulong target_mtext_addr = msgp + sizeof(abi_ulong);
3009         target_mtext = lock_user(VERIFY_WRITE, target_mtext_addr, ret, 0);
3010         if (!target_mtext) {
3011             ret = -TARGET_EFAULT;
3012             goto end;
3013         }
3014         memcpy(target_mb->mtext, host_mb->mtext, ret);
3015         unlock_user(target_mtext, target_mtext_addr, ret);
3016     }
3017 
3018     target_mb->mtype = tswapal(host_mb->mtype);
3019 
3020 end:
3021     if (target_mb)
3022         unlock_user_struct(target_mb, msgp, 1);
3023     g_free(host_mb);
3024     return ret;
3025 }
3026 
3027 static inline abi_long target_to_host_shmid_ds(struct shmid_ds *host_sd,
3028                                                abi_ulong target_addr)
3029 {
3030     struct target_shmid_ds *target_sd;
3031 
3032     if (!lock_user_struct(VERIFY_READ, target_sd, target_addr, 1))
3033         return -TARGET_EFAULT;
3034     if (target_to_host_ipc_perm(&(host_sd->shm_perm), target_addr))
3035         return -TARGET_EFAULT;
3036     __get_user(host_sd->shm_segsz, &target_sd->shm_segsz);
3037     __get_user(host_sd->shm_atime, &target_sd->shm_atime);
3038     __get_user(host_sd->shm_dtime, &target_sd->shm_dtime);
3039     __get_user(host_sd->shm_ctime, &target_sd->shm_ctime);
3040     __get_user(host_sd->shm_cpid, &target_sd->shm_cpid);
3041     __get_user(host_sd->shm_lpid, &target_sd->shm_lpid);
3042     __get_user(host_sd->shm_nattch, &target_sd->shm_nattch);
3043     unlock_user_struct(target_sd, target_addr, 0);
3044     return 0;
3045 }
3046 
3047 static inline abi_long host_to_target_shmid_ds(abi_ulong target_addr,
3048                                                struct shmid_ds *host_sd)
3049 {
3050     struct target_shmid_ds *target_sd;
3051 
3052     if (!lock_user_struct(VERIFY_WRITE, target_sd, target_addr, 0))
3053         return -TARGET_EFAULT;
3054     if (host_to_target_ipc_perm(target_addr, &(host_sd->shm_perm)))
3055         return -TARGET_EFAULT;
3056     __put_user(host_sd->shm_segsz, &target_sd->shm_segsz);
3057     __put_user(host_sd->shm_atime, &target_sd->shm_atime);
3058     __put_user(host_sd->shm_dtime, &target_sd->shm_dtime);
3059     __put_user(host_sd->shm_ctime, &target_sd->shm_ctime);
3060     __put_user(host_sd->shm_cpid, &target_sd->shm_cpid);
3061     __put_user(host_sd->shm_lpid, &target_sd->shm_lpid);
3062     __put_user(host_sd->shm_nattch, &target_sd->shm_nattch);
3063     unlock_user_struct(target_sd, target_addr, 1);
3064     return 0;
3065 }
3066 
3067 struct  target_shminfo {
3068     abi_ulong shmmax;
3069     abi_ulong shmmin;
3070     abi_ulong shmmni;
3071     abi_ulong shmseg;
3072     abi_ulong shmall;
3073 };
3074 
3075 static inline abi_long host_to_target_shminfo(abi_ulong target_addr,
3076                                               struct shminfo *host_shminfo)
3077 {
3078     struct target_shminfo *target_shminfo;
3079     if (!lock_user_struct(VERIFY_WRITE, target_shminfo, target_addr, 0))
3080         return -TARGET_EFAULT;
3081     __put_user(host_shminfo->shmmax, &target_shminfo->shmmax);
3082     __put_user(host_shminfo->shmmin, &target_shminfo->shmmin);
3083     __put_user(host_shminfo->shmmni, &target_shminfo->shmmni);
3084     __put_user(host_shminfo->shmseg, &target_shminfo->shmseg);
3085     __put_user(host_shminfo->shmall, &target_shminfo->shmall);
3086     unlock_user_struct(target_shminfo, target_addr, 1);
3087     return 0;
3088 }
3089 
3090 struct target_shm_info {
3091     int used_ids;
3092     abi_ulong shm_tot;
3093     abi_ulong shm_rss;
3094     abi_ulong shm_swp;
3095     abi_ulong swap_attempts;
3096     abi_ulong swap_successes;
3097 };
3098 
3099 static inline abi_long host_to_target_shm_info(abi_ulong target_addr,
3100                                                struct shm_info *host_shm_info)
3101 {
3102     struct target_shm_info *target_shm_info;
3103     if (!lock_user_struct(VERIFY_WRITE, target_shm_info, target_addr, 0))
3104         return -TARGET_EFAULT;
3105     __put_user(host_shm_info->used_ids, &target_shm_info->used_ids);
3106     __put_user(host_shm_info->shm_tot, &target_shm_info->shm_tot);
3107     __put_user(host_shm_info->shm_rss, &target_shm_info->shm_rss);
3108     __put_user(host_shm_info->shm_swp, &target_shm_info->shm_swp);
3109     __put_user(host_shm_info->swap_attempts, &target_shm_info->swap_attempts);
3110     __put_user(host_shm_info->swap_successes, &target_shm_info->swap_successes);
3111     unlock_user_struct(target_shm_info, target_addr, 1);
3112     return 0;
3113 }
3114 
3115 static inline abi_long do_shmctl(int shmid, int cmd, abi_long buf)
3116 {
3117     struct shmid_ds dsarg;
3118     struct shminfo shminfo;
3119     struct shm_info shm_info;
3120     abi_long ret = -TARGET_EINVAL;
3121 
3122     cmd &= 0xff;
3123 
3124     switch(cmd) {
3125     case IPC_STAT:
3126     case IPC_SET:
3127     case SHM_STAT:
3128         if (target_to_host_shmid_ds(&dsarg, buf))
3129             return -TARGET_EFAULT;
3130         ret = get_errno(shmctl(shmid, cmd, &dsarg));
3131         if (host_to_target_shmid_ds(buf, &dsarg))
3132             return -TARGET_EFAULT;
3133         break;
3134     case IPC_INFO:
3135         ret = get_errno(shmctl(shmid, cmd, (struct shmid_ds *)&shminfo));
3136         if (host_to_target_shminfo(buf, &shminfo))
3137             return -TARGET_EFAULT;
3138         break;
3139     case SHM_INFO:
3140         ret = get_errno(shmctl(shmid, cmd, (struct shmid_ds *)&shm_info));
3141         if (host_to_target_shm_info(buf, &shm_info))
3142             return -TARGET_EFAULT;
3143         break;
3144     case IPC_RMID:
3145     case SHM_LOCK:
3146     case SHM_UNLOCK:
3147         ret = get_errno(shmctl(shmid, cmd, NULL));
3148         break;
3149     }
3150 
3151     return ret;
3152 }
3153 
3154 static inline abi_ulong do_shmat(int shmid, abi_ulong shmaddr, int shmflg)
3155 {
3156     abi_long raddr;
3157     void *host_raddr;
3158     struct shmid_ds shm_info;
3159     int i,ret;
3160 
3161     /* find out the length of the shared memory segment */
3162     ret = get_errno(shmctl(shmid, IPC_STAT, &shm_info));
3163     if (is_error(ret)) {
3164         /* can't get length, bail out */
3165         return ret;
3166     }
3167 
3168     mmap_lock();
3169 
3170     if (shmaddr)
3171         host_raddr = shmat(shmid, (void *)g2h(shmaddr), shmflg);
3172     else {
3173         abi_ulong mmap_start;
3174 
3175         mmap_start = mmap_find_vma(0, shm_info.shm_segsz);
3176 
3177         if (mmap_start == -1) {
3178             errno = ENOMEM;
3179             host_raddr = (void *)-1;
3180         } else
3181             host_raddr = shmat(shmid, g2h(mmap_start), shmflg | SHM_REMAP);
3182     }
3183 
3184     if (host_raddr == (void *)-1) {
3185         mmap_unlock();
3186         return get_errno((long)host_raddr);
3187     }
3188     raddr=h2g((unsigned long)host_raddr);
3189 
3190     page_set_flags(raddr, raddr + shm_info.shm_segsz,
3191                    PAGE_VALID | PAGE_READ |
3192                    ((shmflg & SHM_RDONLY)? 0 : PAGE_WRITE));
3193 
3194     for (i = 0; i < N_SHM_REGIONS; i++) {
3195         if (shm_regions[i].start == 0) {
3196             shm_regions[i].start = raddr;
3197             shm_regions[i].size = shm_info.shm_segsz;
3198             break;
3199         }
3200     }
3201 
3202     mmap_unlock();
3203     return raddr;
3204 
3205 }
3206 
3207 static inline abi_long do_shmdt(abi_ulong shmaddr)
3208 {
3209     int i;
3210 
3211     for (i = 0; i < N_SHM_REGIONS; ++i) {
3212         if (shm_regions[i].start == shmaddr) {
3213             shm_regions[i].start = 0;
3214             page_set_flags(shmaddr, shmaddr + shm_regions[i].size, 0);
3215             break;
3216         }
3217     }
3218 
3219     return get_errno(shmdt(g2h(shmaddr)));
3220 }
3221 
3222 #ifdef TARGET_NR_ipc
3223 /* ??? This only works with linear mappings.  */
3224 /* do_ipc() must return target values and target errnos. */
3225 static abi_long do_ipc(unsigned int call, abi_long first,
3226                        abi_long second, abi_long third,
3227                        abi_long ptr, abi_long fifth)
3228 {
3229     int version;
3230     abi_long ret = 0;
3231 
3232     version = call >> 16;
3233     call &= 0xffff;
3234 
3235     switch (call) {
3236     case IPCOP_semop:
3237         ret = do_semop(first, ptr, second);
3238         break;
3239 
3240     case IPCOP_semget:
3241         ret = get_errno(semget(first, second, third));
3242         break;
3243 
3244     case IPCOP_semctl: {
3245         /* The semun argument to semctl is passed by value, so dereference the
3246          * ptr argument. */
3247         abi_ulong atptr;
3248         get_user_ual(atptr, ptr);
3249         ret = do_semctl(first, second, third,
3250                 (union target_semun) atptr);
3251         break;
3252     }
3253 
3254     case IPCOP_msgget:
3255         ret = get_errno(msgget(first, second));
3256         break;
3257 
3258     case IPCOP_msgsnd:
3259         ret = do_msgsnd(first, ptr, second, third);
3260         break;
3261 
3262     case IPCOP_msgctl:
3263         ret = do_msgctl(first, second, ptr);
3264         break;
3265 
3266     case IPCOP_msgrcv:
3267         switch (version) {
3268         case 0:
3269             {
3270                 struct target_ipc_kludge {
3271                     abi_long msgp;
3272                     abi_long msgtyp;
3273                 } *tmp;
3274 
3275                 if (!lock_user_struct(VERIFY_READ, tmp, ptr, 1)) {
3276                     ret = -TARGET_EFAULT;
3277                     break;
3278                 }
3279 
3280                 ret = do_msgrcv(first, tswapal(tmp->msgp), second, tswapal(tmp->msgtyp), third);
3281 
3282                 unlock_user_struct(tmp, ptr, 0);
3283                 break;
3284             }
3285         default:
3286             ret = do_msgrcv(first, ptr, second, fifth, third);
3287         }
3288         break;
3289 
3290     case IPCOP_shmat:
3291         switch (version) {
3292         default:
3293         {
3294             abi_ulong raddr;
3295             raddr = do_shmat(first, ptr, second);
3296             if (is_error(raddr))
3297                 return get_errno(raddr);
3298             if (put_user_ual(raddr, third))
3299                 return -TARGET_EFAULT;
3300             break;
3301         }
3302         case 1:
3303             ret = -TARGET_EINVAL;
3304             break;
3305         }
3306 	break;
3307     case IPCOP_shmdt:
3308         ret = do_shmdt(ptr);
3309 	break;
3310 
3311     case IPCOP_shmget:
3312 	/* IPC_* flag values are the same on all linux platforms */
3313 	ret = get_errno(shmget(first, second, third));
3314 	break;
3315 
3316 	/* IPC_* and SHM_* command values are the same on all linux platforms */
3317     case IPCOP_shmctl:
3318         ret = do_shmctl(first, second, ptr);
3319         break;
3320     default:
3321 	gemu_log("Unsupported ipc call: %d (version %d)\n", call, version);
3322 	ret = -TARGET_ENOSYS;
3323 	break;
3324     }
3325     return ret;
3326 }
3327 #endif
3328 
3329 /* kernel structure types definitions */
3330 
3331 #define STRUCT(name, ...) STRUCT_ ## name,
3332 #define STRUCT_SPECIAL(name) STRUCT_ ## name,
3333 enum {
3334 #include "syscall_types.h"
3335 STRUCT_MAX
3336 };
3337 #undef STRUCT
3338 #undef STRUCT_SPECIAL
3339 
3340 #define STRUCT(name, ...) static const argtype struct_ ## name ## _def[] = {  __VA_ARGS__, TYPE_NULL };
3341 #define STRUCT_SPECIAL(name)
3342 #include "syscall_types.h"
3343 #undef STRUCT
3344 #undef STRUCT_SPECIAL
3345 
3346 typedef struct IOCTLEntry IOCTLEntry;
3347 
3348 typedef abi_long do_ioctl_fn(const IOCTLEntry *ie, uint8_t *buf_temp,
3349                              int fd, int cmd, abi_long arg);
3350 
3351 struct IOCTLEntry {
3352     int target_cmd;
3353     unsigned int host_cmd;
3354     const char *name;
3355     int access;
3356     do_ioctl_fn *do_ioctl;
3357     const argtype arg_type[5];
3358 };
3359 
3360 #define IOC_R 0x0001
3361 #define IOC_W 0x0002
3362 #define IOC_RW (IOC_R | IOC_W)
3363 
3364 #define MAX_STRUCT_SIZE 4096
3365 
3366 #ifdef CONFIG_FIEMAP
3367 /* So fiemap access checks don't overflow on 32 bit systems.
3368  * This is very slightly smaller than the limit imposed by
3369  * the underlying kernel.
3370  */
3371 #define FIEMAP_MAX_EXTENTS ((UINT_MAX - sizeof(struct fiemap))  \
3372                             / sizeof(struct fiemap_extent))
3373 
3374 static abi_long do_ioctl_fs_ioc_fiemap(const IOCTLEntry *ie, uint8_t *buf_temp,
3375                                        int fd, int cmd, abi_long arg)
3376 {
3377     /* The parameter for this ioctl is a struct fiemap followed
3378      * by an array of struct fiemap_extent whose size is set
3379      * in fiemap->fm_extent_count. The array is filled in by the
3380      * ioctl.
3381      */
3382     int target_size_in, target_size_out;
3383     struct fiemap *fm;
3384     const argtype *arg_type = ie->arg_type;
3385     const argtype extent_arg_type[] = { MK_STRUCT(STRUCT_fiemap_extent) };
3386     void *argptr, *p;
3387     abi_long ret;
3388     int i, extent_size = thunk_type_size(extent_arg_type, 0);
3389     uint32_t outbufsz;
3390     int free_fm = 0;
3391 
3392     assert(arg_type[0] == TYPE_PTR);
3393     assert(ie->access == IOC_RW);
3394     arg_type++;
3395     target_size_in = thunk_type_size(arg_type, 0);
3396     argptr = lock_user(VERIFY_READ, arg, target_size_in, 1);
3397     if (!argptr) {
3398         return -TARGET_EFAULT;
3399     }
3400     thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
3401     unlock_user(argptr, arg, 0);
3402     fm = (struct fiemap *)buf_temp;
3403     if (fm->fm_extent_count > FIEMAP_MAX_EXTENTS) {
3404         return -TARGET_EINVAL;
3405     }
3406 
3407     outbufsz = sizeof (*fm) +
3408         (sizeof(struct fiemap_extent) * fm->fm_extent_count);
3409 
3410     if (outbufsz > MAX_STRUCT_SIZE) {
3411         /* We can't fit all the extents into the fixed size buffer.
3412          * Allocate one that is large enough and use it instead.
3413          */
3414         fm = malloc(outbufsz);
3415         if (!fm) {
3416             return -TARGET_ENOMEM;
3417         }
3418         memcpy(fm, buf_temp, sizeof(struct fiemap));
3419         free_fm = 1;
3420     }
3421     ret = get_errno(ioctl(fd, ie->host_cmd, fm));
3422     if (!is_error(ret)) {
3423         target_size_out = target_size_in;
3424         /* An extent_count of 0 means we were only counting the extents
3425          * so there are no structs to copy
3426          */
3427         if (fm->fm_extent_count != 0) {
3428             target_size_out += fm->fm_mapped_extents * extent_size;
3429         }
3430         argptr = lock_user(VERIFY_WRITE, arg, target_size_out, 0);
3431         if (!argptr) {
3432             ret = -TARGET_EFAULT;
3433         } else {
3434             /* Convert the struct fiemap */
3435             thunk_convert(argptr, fm, arg_type, THUNK_TARGET);
3436             if (fm->fm_extent_count != 0) {
3437                 p = argptr + target_size_in;
3438                 /* ...and then all the struct fiemap_extents */
3439                 for (i = 0; i < fm->fm_mapped_extents; i++) {
3440                     thunk_convert(p, &fm->fm_extents[i], extent_arg_type,
3441                                   THUNK_TARGET);
3442                     p += extent_size;
3443                 }
3444             }
3445             unlock_user(argptr, arg, target_size_out);
3446         }
3447     }
3448     if (free_fm) {
3449         free(fm);
3450     }
3451     return ret;
3452 }
3453 #endif
3454 
3455 static abi_long do_ioctl_ifconf(const IOCTLEntry *ie, uint8_t *buf_temp,
3456                                 int fd, int cmd, abi_long arg)
3457 {
3458     const argtype *arg_type = ie->arg_type;
3459     int target_size;
3460     void *argptr;
3461     int ret;
3462     struct ifconf *host_ifconf;
3463     uint32_t outbufsz;
3464     const argtype ifreq_arg_type[] = { MK_STRUCT(STRUCT_sockaddr_ifreq) };
3465     int target_ifreq_size;
3466     int nb_ifreq;
3467     int free_buf = 0;
3468     int i;
3469     int target_ifc_len;
3470     abi_long target_ifc_buf;
3471     int host_ifc_len;
3472     char *host_ifc_buf;
3473 
3474     assert(arg_type[0] == TYPE_PTR);
3475     assert(ie->access == IOC_RW);
3476 
3477     arg_type++;
3478     target_size = thunk_type_size(arg_type, 0);
3479 
3480     argptr = lock_user(VERIFY_READ, arg, target_size, 1);
3481     if (!argptr)
3482         return -TARGET_EFAULT;
3483     thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
3484     unlock_user(argptr, arg, 0);
3485 
3486     host_ifconf = (struct ifconf *)(unsigned long)buf_temp;
3487     target_ifc_len = host_ifconf->ifc_len;
3488     target_ifc_buf = (abi_long)(unsigned long)host_ifconf->ifc_buf;
3489 
3490     target_ifreq_size = thunk_type_size(ifreq_arg_type, 0);
3491     nb_ifreq = target_ifc_len / target_ifreq_size;
3492     host_ifc_len = nb_ifreq * sizeof(struct ifreq);
3493 
3494     outbufsz = sizeof(*host_ifconf) + host_ifc_len;
3495     if (outbufsz > MAX_STRUCT_SIZE) {
3496         /* We can't fit all the extents into the fixed size buffer.
3497          * Allocate one that is large enough and use it instead.
3498          */
3499         host_ifconf = malloc(outbufsz);
3500         if (!host_ifconf) {
3501             return -TARGET_ENOMEM;
3502         }
3503         memcpy(host_ifconf, buf_temp, sizeof(*host_ifconf));
3504         free_buf = 1;
3505     }
3506     host_ifc_buf = (char*)host_ifconf + sizeof(*host_ifconf);
3507 
3508     host_ifconf->ifc_len = host_ifc_len;
3509     host_ifconf->ifc_buf = host_ifc_buf;
3510 
3511     ret = get_errno(ioctl(fd, ie->host_cmd, host_ifconf));
3512     if (!is_error(ret)) {
3513 	/* convert host ifc_len to target ifc_len */
3514 
3515         nb_ifreq = host_ifconf->ifc_len / sizeof(struct ifreq);
3516         target_ifc_len = nb_ifreq * target_ifreq_size;
3517         host_ifconf->ifc_len = target_ifc_len;
3518 
3519 	/* restore target ifc_buf */
3520 
3521         host_ifconf->ifc_buf = (char *)(unsigned long)target_ifc_buf;
3522 
3523 	/* copy struct ifconf to target user */
3524 
3525         argptr = lock_user(VERIFY_WRITE, arg, target_size, 0);
3526         if (!argptr)
3527             return -TARGET_EFAULT;
3528         thunk_convert(argptr, host_ifconf, arg_type, THUNK_TARGET);
3529         unlock_user(argptr, arg, target_size);
3530 
3531 	/* copy ifreq[] to target user */
3532 
3533         argptr = lock_user(VERIFY_WRITE, target_ifc_buf, target_ifc_len, 0);
3534         for (i = 0; i < nb_ifreq ; i++) {
3535             thunk_convert(argptr + i * target_ifreq_size,
3536                           host_ifc_buf + i * sizeof(struct ifreq),
3537                           ifreq_arg_type, THUNK_TARGET);
3538         }
3539         unlock_user(argptr, target_ifc_buf, target_ifc_len);
3540     }
3541 
3542     if (free_buf) {
3543         free(host_ifconf);
3544     }
3545 
3546     return ret;
3547 }
3548 
3549 static abi_long do_ioctl_dm(const IOCTLEntry *ie, uint8_t *buf_temp, int fd,
3550                             int cmd, abi_long arg)
3551 {
3552     void *argptr;
3553     struct dm_ioctl *host_dm;
3554     abi_long guest_data;
3555     uint32_t guest_data_size;
3556     int target_size;
3557     const argtype *arg_type = ie->arg_type;
3558     abi_long ret;
3559     void *big_buf = NULL;
3560     char *host_data;
3561 
3562     arg_type++;
3563     target_size = thunk_type_size(arg_type, 0);
3564     argptr = lock_user(VERIFY_READ, arg, target_size, 1);
3565     if (!argptr) {
3566         ret = -TARGET_EFAULT;
3567         goto out;
3568     }
3569     thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
3570     unlock_user(argptr, arg, 0);
3571 
3572     /* buf_temp is too small, so fetch things into a bigger buffer */
3573     big_buf = g_malloc0(((struct dm_ioctl*)buf_temp)->data_size * 2);
3574     memcpy(big_buf, buf_temp, target_size);
3575     buf_temp = big_buf;
3576     host_dm = big_buf;
3577 
3578     guest_data = arg + host_dm->data_start;
3579     if ((guest_data - arg) < 0) {
3580         ret = -EINVAL;
3581         goto out;
3582     }
3583     guest_data_size = host_dm->data_size - host_dm->data_start;
3584     host_data = (char*)host_dm + host_dm->data_start;
3585 
3586     argptr = lock_user(VERIFY_READ, guest_data, guest_data_size, 1);
3587     switch (ie->host_cmd) {
3588     case DM_REMOVE_ALL:
3589     case DM_LIST_DEVICES:
3590     case DM_DEV_CREATE:
3591     case DM_DEV_REMOVE:
3592     case DM_DEV_SUSPEND:
3593     case DM_DEV_STATUS:
3594     case DM_DEV_WAIT:
3595     case DM_TABLE_STATUS:
3596     case DM_TABLE_CLEAR:
3597     case DM_TABLE_DEPS:
3598     case DM_LIST_VERSIONS:
3599         /* no input data */
3600         break;
3601     case DM_DEV_RENAME:
3602     case DM_DEV_SET_GEOMETRY:
3603         /* data contains only strings */
3604         memcpy(host_data, argptr, guest_data_size);
3605         break;
3606     case DM_TARGET_MSG:
3607         memcpy(host_data, argptr, guest_data_size);
3608         *(uint64_t*)host_data = tswap64(*(uint64_t*)argptr);
3609         break;
3610     case DM_TABLE_LOAD:
3611     {
3612         void *gspec = argptr;
3613         void *cur_data = host_data;
3614         const argtype arg_type[] = { MK_STRUCT(STRUCT_dm_target_spec) };
3615         int spec_size = thunk_type_size(arg_type, 0);
3616         int i;
3617 
3618         for (i = 0; i < host_dm->target_count; i++) {
3619             struct dm_target_spec *spec = cur_data;
3620             uint32_t next;
3621             int slen;
3622 
3623             thunk_convert(spec, gspec, arg_type, THUNK_HOST);
3624             slen = strlen((char*)gspec + spec_size) + 1;
3625             next = spec->next;
3626             spec->next = sizeof(*spec) + slen;
3627             strcpy((char*)&spec[1], gspec + spec_size);
3628             gspec += next;
3629             cur_data += spec->next;
3630         }
3631         break;
3632     }
3633     default:
3634         ret = -TARGET_EINVAL;
3635         unlock_user(argptr, guest_data, 0);
3636         goto out;
3637     }
3638     unlock_user(argptr, guest_data, 0);
3639 
3640     ret = get_errno(ioctl(fd, ie->host_cmd, buf_temp));
3641     if (!is_error(ret)) {
3642         guest_data = arg + host_dm->data_start;
3643         guest_data_size = host_dm->data_size - host_dm->data_start;
3644         argptr = lock_user(VERIFY_WRITE, guest_data, guest_data_size, 0);
3645         switch (ie->host_cmd) {
3646         case DM_REMOVE_ALL:
3647         case DM_DEV_CREATE:
3648         case DM_DEV_REMOVE:
3649         case DM_DEV_RENAME:
3650         case DM_DEV_SUSPEND:
3651         case DM_DEV_STATUS:
3652         case DM_TABLE_LOAD:
3653         case DM_TABLE_CLEAR:
3654         case DM_TARGET_MSG:
3655         case DM_DEV_SET_GEOMETRY:
3656             /* no return data */
3657             break;
3658         case DM_LIST_DEVICES:
3659         {
3660             struct dm_name_list *nl = (void*)host_dm + host_dm->data_start;
3661             uint32_t remaining_data = guest_data_size;
3662             void *cur_data = argptr;
3663             const argtype arg_type[] = { MK_STRUCT(STRUCT_dm_name_list) };
3664             int nl_size = 12; /* can't use thunk_size due to alignment */
3665 
3666             while (1) {
3667                 uint32_t next = nl->next;
3668                 if (next) {
3669                     nl->next = nl_size + (strlen(nl->name) + 1);
3670                 }
3671                 if (remaining_data < nl->next) {
3672                     host_dm->flags |= DM_BUFFER_FULL_FLAG;
3673                     break;
3674                 }
3675                 thunk_convert(cur_data, nl, arg_type, THUNK_TARGET);
3676                 strcpy(cur_data + nl_size, nl->name);
3677                 cur_data += nl->next;
3678                 remaining_data -= nl->next;
3679                 if (!next) {
3680                     break;
3681                 }
3682                 nl = (void*)nl + next;
3683             }
3684             break;
3685         }
3686         case DM_DEV_WAIT:
3687         case DM_TABLE_STATUS:
3688         {
3689             struct dm_target_spec *spec = (void*)host_dm + host_dm->data_start;
3690             void *cur_data = argptr;
3691             const argtype arg_type[] = { MK_STRUCT(STRUCT_dm_target_spec) };
3692             int spec_size = thunk_type_size(arg_type, 0);
3693             int i;
3694 
3695             for (i = 0; i < host_dm->target_count; i++) {
3696                 uint32_t next = spec->next;
3697                 int slen = strlen((char*)&spec[1]) + 1;
3698                 spec->next = (cur_data - argptr) + spec_size + slen;
3699                 if (guest_data_size < spec->next) {
3700                     host_dm->flags |= DM_BUFFER_FULL_FLAG;
3701                     break;
3702                 }
3703                 thunk_convert(cur_data, spec, arg_type, THUNK_TARGET);
3704                 strcpy(cur_data + spec_size, (char*)&spec[1]);
3705                 cur_data = argptr + spec->next;
3706                 spec = (void*)host_dm + host_dm->data_start + next;
3707             }
3708             break;
3709         }
3710         case DM_TABLE_DEPS:
3711         {
3712             void *hdata = (void*)host_dm + host_dm->data_start;
3713             int count = *(uint32_t*)hdata;
3714             uint64_t *hdev = hdata + 8;
3715             uint64_t *gdev = argptr + 8;
3716             int i;
3717 
3718             *(uint32_t*)argptr = tswap32(count);
3719             for (i = 0; i < count; i++) {
3720                 *gdev = tswap64(*hdev);
3721                 gdev++;
3722                 hdev++;
3723             }
3724             break;
3725         }
3726         case DM_LIST_VERSIONS:
3727         {
3728             struct dm_target_versions *vers = (void*)host_dm + host_dm->data_start;
3729             uint32_t remaining_data = guest_data_size;
3730             void *cur_data = argptr;
3731             const argtype arg_type[] = { MK_STRUCT(STRUCT_dm_target_versions) };
3732             int vers_size = thunk_type_size(arg_type, 0);
3733 
3734             while (1) {
3735                 uint32_t next = vers->next;
3736                 if (next) {
3737                     vers->next = vers_size + (strlen(vers->name) + 1);
3738                 }
3739                 if (remaining_data < vers->next) {
3740                     host_dm->flags |= DM_BUFFER_FULL_FLAG;
3741                     break;
3742                 }
3743                 thunk_convert(cur_data, vers, arg_type, THUNK_TARGET);
3744                 strcpy(cur_data + vers_size, vers->name);
3745                 cur_data += vers->next;
3746                 remaining_data -= vers->next;
3747                 if (!next) {
3748                     break;
3749                 }
3750                 vers = (void*)vers + next;
3751             }
3752             break;
3753         }
3754         default:
3755             unlock_user(argptr, guest_data, 0);
3756             ret = -TARGET_EINVAL;
3757             goto out;
3758         }
3759         unlock_user(argptr, guest_data, guest_data_size);
3760 
3761         argptr = lock_user(VERIFY_WRITE, arg, target_size, 0);
3762         if (!argptr) {
3763             ret = -TARGET_EFAULT;
3764             goto out;
3765         }
3766         thunk_convert(argptr, buf_temp, arg_type, THUNK_TARGET);
3767         unlock_user(argptr, arg, target_size);
3768     }
3769 out:
3770     g_free(big_buf);
3771     return ret;
3772 }
3773 
3774 static abi_long do_ioctl_blkpg(const IOCTLEntry *ie, uint8_t *buf_temp, int fd,
3775                                int cmd, abi_long arg)
3776 {
3777     void *argptr;
3778     int target_size;
3779     const argtype *arg_type = ie->arg_type;
3780     const argtype part_arg_type[] = { MK_STRUCT(STRUCT_blkpg_partition) };
3781     abi_long ret;
3782 
3783     struct blkpg_ioctl_arg *host_blkpg = (void*)buf_temp;
3784     struct blkpg_partition host_part;
3785 
3786     /* Read and convert blkpg */
3787     arg_type++;
3788     target_size = thunk_type_size(arg_type, 0);
3789     argptr = lock_user(VERIFY_READ, arg, target_size, 1);
3790     if (!argptr) {
3791         ret = -TARGET_EFAULT;
3792         goto out;
3793     }
3794     thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
3795     unlock_user(argptr, arg, 0);
3796 
3797     switch (host_blkpg->op) {
3798     case BLKPG_ADD_PARTITION:
3799     case BLKPG_DEL_PARTITION:
3800         /* payload is struct blkpg_partition */
3801         break;
3802     default:
3803         /* Unknown opcode */
3804         ret = -TARGET_EINVAL;
3805         goto out;
3806     }
3807 
3808     /* Read and convert blkpg->data */
3809     arg = (abi_long)(uintptr_t)host_blkpg->data;
3810     target_size = thunk_type_size(part_arg_type, 0);
3811     argptr = lock_user(VERIFY_READ, arg, target_size, 1);
3812     if (!argptr) {
3813         ret = -TARGET_EFAULT;
3814         goto out;
3815     }
3816     thunk_convert(&host_part, argptr, part_arg_type, THUNK_HOST);
3817     unlock_user(argptr, arg, 0);
3818 
3819     /* Swizzle the data pointer to our local copy and call! */
3820     host_blkpg->data = &host_part;
3821     ret = get_errno(ioctl(fd, ie->host_cmd, host_blkpg));
3822 
3823 out:
3824     return ret;
3825 }
3826 
3827 static abi_long do_ioctl_rt(const IOCTLEntry *ie, uint8_t *buf_temp,
3828                                 int fd, int cmd, abi_long arg)
3829 {
3830     const argtype *arg_type = ie->arg_type;
3831     const StructEntry *se;
3832     const argtype *field_types;
3833     const int *dst_offsets, *src_offsets;
3834     int target_size;
3835     void *argptr;
3836     abi_ulong *target_rt_dev_ptr;
3837     unsigned long *host_rt_dev_ptr;
3838     abi_long ret;
3839     int i;
3840 
3841     assert(ie->access == IOC_W);
3842     assert(*arg_type == TYPE_PTR);
3843     arg_type++;
3844     assert(*arg_type == TYPE_STRUCT);
3845     target_size = thunk_type_size(arg_type, 0);
3846     argptr = lock_user(VERIFY_READ, arg, target_size, 1);
3847     if (!argptr) {
3848         return -TARGET_EFAULT;
3849     }
3850     arg_type++;
3851     assert(*arg_type == (int)STRUCT_rtentry);
3852     se = struct_entries + *arg_type++;
3853     assert(se->convert[0] == NULL);
3854     /* convert struct here to be able to catch rt_dev string */
3855     field_types = se->field_types;
3856     dst_offsets = se->field_offsets[THUNK_HOST];
3857     src_offsets = se->field_offsets[THUNK_TARGET];
3858     for (i = 0; i < se->nb_fields; i++) {
3859         if (dst_offsets[i] == offsetof(struct rtentry, rt_dev)) {
3860             assert(*field_types == TYPE_PTRVOID);
3861             target_rt_dev_ptr = (abi_ulong *)(argptr + src_offsets[i]);
3862             host_rt_dev_ptr = (unsigned long *)(buf_temp + dst_offsets[i]);
3863             if (*target_rt_dev_ptr != 0) {
3864                 *host_rt_dev_ptr = (unsigned long)lock_user_string(
3865                                                   tswapal(*target_rt_dev_ptr));
3866                 if (!*host_rt_dev_ptr) {
3867                     unlock_user(argptr, arg, 0);
3868                     return -TARGET_EFAULT;
3869                 }
3870             } else {
3871                 *host_rt_dev_ptr = 0;
3872             }
3873             field_types++;
3874             continue;
3875         }
3876         field_types = thunk_convert(buf_temp + dst_offsets[i],
3877                                     argptr + src_offsets[i],
3878                                     field_types, THUNK_HOST);
3879     }
3880     unlock_user(argptr, arg, 0);
3881 
3882     ret = get_errno(ioctl(fd, ie->host_cmd, buf_temp));
3883     if (*host_rt_dev_ptr != 0) {
3884         unlock_user((void *)*host_rt_dev_ptr,
3885                     *target_rt_dev_ptr, 0);
3886     }
3887     return ret;
3888 }
3889 
3890 static abi_long do_ioctl_kdsigaccept(const IOCTLEntry *ie, uint8_t *buf_temp,
3891                                      int fd, int cmd, abi_long arg)
3892 {
3893     int sig = target_to_host_signal(arg);
3894     return get_errno(ioctl(fd, ie->host_cmd, sig));
3895 }
3896 
3897 static IOCTLEntry ioctl_entries[] = {
3898 #define IOCTL(cmd, access, ...) \
3899     { TARGET_ ## cmd, cmd, #cmd, access, 0, {  __VA_ARGS__ } },
3900 #define IOCTL_SPECIAL(cmd, access, dofn, ...)                      \
3901     { TARGET_ ## cmd, cmd, #cmd, access, dofn, {  __VA_ARGS__ } },
3902 #include "ioctls.h"
3903     { 0, 0, },
3904 };
3905 
3906 /* ??? Implement proper locking for ioctls.  */
3907 /* do_ioctl() Must return target values and target errnos. */
3908 static abi_long do_ioctl(int fd, int cmd, abi_long arg)
3909 {
3910     const IOCTLEntry *ie;
3911     const argtype *arg_type;
3912     abi_long ret;
3913     uint8_t buf_temp[MAX_STRUCT_SIZE];
3914     int target_size;
3915     void *argptr;
3916 
3917     ie = ioctl_entries;
3918     for(;;) {
3919         if (ie->target_cmd == 0) {
3920             gemu_log("Unsupported ioctl: cmd=0x%04lx\n", (long)cmd);
3921             return -TARGET_ENOSYS;
3922         }
3923         if (ie->target_cmd == cmd)
3924             break;
3925         ie++;
3926     }
3927     arg_type = ie->arg_type;
3928 #if defined(DEBUG)
3929     gemu_log("ioctl: cmd=0x%04lx (%s)\n", (long)cmd, ie->name);
3930 #endif
3931     if (ie->do_ioctl) {
3932         return ie->do_ioctl(ie, buf_temp, fd, cmd, arg);
3933     }
3934 
3935     switch(arg_type[0]) {
3936     case TYPE_NULL:
3937         /* no argument */
3938         ret = get_errno(ioctl(fd, ie->host_cmd));
3939         break;
3940     case TYPE_PTRVOID:
3941     case TYPE_INT:
3942         ret = get_errno(ioctl(fd, ie->host_cmd, arg));
3943         break;
3944     case TYPE_PTR:
3945         arg_type++;
3946         target_size = thunk_type_size(arg_type, 0);
3947         switch(ie->access) {
3948         case IOC_R:
3949             ret = get_errno(ioctl(fd, ie->host_cmd, buf_temp));
3950             if (!is_error(ret)) {
3951                 argptr = lock_user(VERIFY_WRITE, arg, target_size, 0);
3952                 if (!argptr)
3953                     return -TARGET_EFAULT;
3954                 thunk_convert(argptr, buf_temp, arg_type, THUNK_TARGET);
3955                 unlock_user(argptr, arg, target_size);
3956             }
3957             break;
3958         case IOC_W:
3959             argptr = lock_user(VERIFY_READ, arg, target_size, 1);
3960             if (!argptr)
3961                 return -TARGET_EFAULT;
3962             thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
3963             unlock_user(argptr, arg, 0);
3964             ret = get_errno(ioctl(fd, ie->host_cmd, buf_temp));
3965             break;
3966         default:
3967         case IOC_RW:
3968             argptr = lock_user(VERIFY_READ, arg, target_size, 1);
3969             if (!argptr)
3970                 return -TARGET_EFAULT;
3971             thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
3972             unlock_user(argptr, arg, 0);
3973             ret = get_errno(ioctl(fd, ie->host_cmd, buf_temp));
3974             if (!is_error(ret)) {
3975                 argptr = lock_user(VERIFY_WRITE, arg, target_size, 0);
3976                 if (!argptr)
3977                     return -TARGET_EFAULT;
3978                 thunk_convert(argptr, buf_temp, arg_type, THUNK_TARGET);
3979                 unlock_user(argptr, arg, target_size);
3980             }
3981             break;
3982         }
3983         break;
3984     default:
3985         gemu_log("Unsupported ioctl type: cmd=0x%04lx type=%d\n",
3986                  (long)cmd, arg_type[0]);
3987         ret = -TARGET_ENOSYS;
3988         break;
3989     }
3990     return ret;
3991 }
3992 
3993 static const bitmask_transtbl iflag_tbl[] = {
3994         { TARGET_IGNBRK, TARGET_IGNBRK, IGNBRK, IGNBRK },
3995         { TARGET_BRKINT, TARGET_BRKINT, BRKINT, BRKINT },
3996         { TARGET_IGNPAR, TARGET_IGNPAR, IGNPAR, IGNPAR },
3997         { TARGET_PARMRK, TARGET_PARMRK, PARMRK, PARMRK },
3998         { TARGET_INPCK, TARGET_INPCK, INPCK, INPCK },
3999         { TARGET_ISTRIP, TARGET_ISTRIP, ISTRIP, ISTRIP },
4000         { TARGET_INLCR, TARGET_INLCR, INLCR, INLCR },
4001         { TARGET_IGNCR, TARGET_IGNCR, IGNCR, IGNCR },
4002         { TARGET_ICRNL, TARGET_ICRNL, ICRNL, ICRNL },
4003         { TARGET_IUCLC, TARGET_IUCLC, IUCLC, IUCLC },
4004         { TARGET_IXON, TARGET_IXON, IXON, IXON },
4005         { TARGET_IXANY, TARGET_IXANY, IXANY, IXANY },
4006         { TARGET_IXOFF, TARGET_IXOFF, IXOFF, IXOFF },
4007         { TARGET_IMAXBEL, TARGET_IMAXBEL, IMAXBEL, IMAXBEL },
4008         { 0, 0, 0, 0 }
4009 };
4010 
4011 static const bitmask_transtbl oflag_tbl[] = {
4012 	{ TARGET_OPOST, TARGET_OPOST, OPOST, OPOST },
4013 	{ TARGET_OLCUC, TARGET_OLCUC, OLCUC, OLCUC },
4014 	{ TARGET_ONLCR, TARGET_ONLCR, ONLCR, ONLCR },
4015 	{ TARGET_OCRNL, TARGET_OCRNL, OCRNL, OCRNL },
4016 	{ TARGET_ONOCR, TARGET_ONOCR, ONOCR, ONOCR },
4017 	{ TARGET_ONLRET, TARGET_ONLRET, ONLRET, ONLRET },
4018 	{ TARGET_OFILL, TARGET_OFILL, OFILL, OFILL },
4019 	{ TARGET_OFDEL, TARGET_OFDEL, OFDEL, OFDEL },
4020 	{ TARGET_NLDLY, TARGET_NL0, NLDLY, NL0 },
4021 	{ TARGET_NLDLY, TARGET_NL1, NLDLY, NL1 },
4022 	{ TARGET_CRDLY, TARGET_CR0, CRDLY, CR0 },
4023 	{ TARGET_CRDLY, TARGET_CR1, CRDLY, CR1 },
4024 	{ TARGET_CRDLY, TARGET_CR2, CRDLY, CR2 },
4025 	{ TARGET_CRDLY, TARGET_CR3, CRDLY, CR3 },
4026 	{ TARGET_TABDLY, TARGET_TAB0, TABDLY, TAB0 },
4027 	{ TARGET_TABDLY, TARGET_TAB1, TABDLY, TAB1 },
4028 	{ TARGET_TABDLY, TARGET_TAB2, TABDLY, TAB2 },
4029 	{ TARGET_TABDLY, TARGET_TAB3, TABDLY, TAB3 },
4030 	{ TARGET_BSDLY, TARGET_BS0, BSDLY, BS0 },
4031 	{ TARGET_BSDLY, TARGET_BS1, BSDLY, BS1 },
4032 	{ TARGET_VTDLY, TARGET_VT0, VTDLY, VT0 },
4033 	{ TARGET_VTDLY, TARGET_VT1, VTDLY, VT1 },
4034 	{ TARGET_FFDLY, TARGET_FF0, FFDLY, FF0 },
4035 	{ TARGET_FFDLY, TARGET_FF1, FFDLY, FF1 },
4036 	{ 0, 0, 0, 0 }
4037 };
4038 
4039 static const bitmask_transtbl cflag_tbl[] = {
4040 	{ TARGET_CBAUD, TARGET_B0, CBAUD, B0 },
4041 	{ TARGET_CBAUD, TARGET_B50, CBAUD, B50 },
4042 	{ TARGET_CBAUD, TARGET_B75, CBAUD, B75 },
4043 	{ TARGET_CBAUD, TARGET_B110, CBAUD, B110 },
4044 	{ TARGET_CBAUD, TARGET_B134, CBAUD, B134 },
4045 	{ TARGET_CBAUD, TARGET_B150, CBAUD, B150 },
4046 	{ TARGET_CBAUD, TARGET_B200, CBAUD, B200 },
4047 	{ TARGET_CBAUD, TARGET_B300, CBAUD, B300 },
4048 	{ TARGET_CBAUD, TARGET_B600, CBAUD, B600 },
4049 	{ TARGET_CBAUD, TARGET_B1200, CBAUD, B1200 },
4050 	{ TARGET_CBAUD, TARGET_B1800, CBAUD, B1800 },
4051 	{ TARGET_CBAUD, TARGET_B2400, CBAUD, B2400 },
4052 	{ TARGET_CBAUD, TARGET_B4800, CBAUD, B4800 },
4053 	{ TARGET_CBAUD, TARGET_B9600, CBAUD, B9600 },
4054 	{ TARGET_CBAUD, TARGET_B19200, CBAUD, B19200 },
4055 	{ TARGET_CBAUD, TARGET_B38400, CBAUD, B38400 },
4056 	{ TARGET_CBAUD, TARGET_B57600, CBAUD, B57600 },
4057 	{ TARGET_CBAUD, TARGET_B115200, CBAUD, B115200 },
4058 	{ TARGET_CBAUD, TARGET_B230400, CBAUD, B230400 },
4059 	{ TARGET_CBAUD, TARGET_B460800, CBAUD, B460800 },
4060 	{ TARGET_CSIZE, TARGET_CS5, CSIZE, CS5 },
4061 	{ TARGET_CSIZE, TARGET_CS6, CSIZE, CS6 },
4062 	{ TARGET_CSIZE, TARGET_CS7, CSIZE, CS7 },
4063 	{ TARGET_CSIZE, TARGET_CS8, CSIZE, CS8 },
4064 	{ TARGET_CSTOPB, TARGET_CSTOPB, CSTOPB, CSTOPB },
4065 	{ TARGET_CREAD, TARGET_CREAD, CREAD, CREAD },
4066 	{ TARGET_PARENB, TARGET_PARENB, PARENB, PARENB },
4067 	{ TARGET_PARODD, TARGET_PARODD, PARODD, PARODD },
4068 	{ TARGET_HUPCL, TARGET_HUPCL, HUPCL, HUPCL },
4069 	{ TARGET_CLOCAL, TARGET_CLOCAL, CLOCAL, CLOCAL },
4070 	{ TARGET_CRTSCTS, TARGET_CRTSCTS, CRTSCTS, CRTSCTS },
4071 	{ 0, 0, 0, 0 }
4072 };
4073 
4074 static const bitmask_transtbl lflag_tbl[] = {
4075 	{ TARGET_ISIG, TARGET_ISIG, ISIG, ISIG },
4076 	{ TARGET_ICANON, TARGET_ICANON, ICANON, ICANON },
4077 	{ TARGET_XCASE, TARGET_XCASE, XCASE, XCASE },
4078 	{ TARGET_ECHO, TARGET_ECHO, ECHO, ECHO },
4079 	{ TARGET_ECHOE, TARGET_ECHOE, ECHOE, ECHOE },
4080 	{ TARGET_ECHOK, TARGET_ECHOK, ECHOK, ECHOK },
4081 	{ TARGET_ECHONL, TARGET_ECHONL, ECHONL, ECHONL },
4082 	{ TARGET_NOFLSH, TARGET_NOFLSH, NOFLSH, NOFLSH },
4083 	{ TARGET_TOSTOP, TARGET_TOSTOP, TOSTOP, TOSTOP },
4084 	{ TARGET_ECHOCTL, TARGET_ECHOCTL, ECHOCTL, ECHOCTL },
4085 	{ TARGET_ECHOPRT, TARGET_ECHOPRT, ECHOPRT, ECHOPRT },
4086 	{ TARGET_ECHOKE, TARGET_ECHOKE, ECHOKE, ECHOKE },
4087 	{ TARGET_FLUSHO, TARGET_FLUSHO, FLUSHO, FLUSHO },
4088 	{ TARGET_PENDIN, TARGET_PENDIN, PENDIN, PENDIN },
4089 	{ TARGET_IEXTEN, TARGET_IEXTEN, IEXTEN, IEXTEN },
4090 	{ 0, 0, 0, 0 }
4091 };
4092 
4093 static void target_to_host_termios (void *dst, const void *src)
4094 {
4095     struct host_termios *host = dst;
4096     const struct target_termios *target = src;
4097 
4098     host->c_iflag =
4099         target_to_host_bitmask(tswap32(target->c_iflag), iflag_tbl);
4100     host->c_oflag =
4101         target_to_host_bitmask(tswap32(target->c_oflag), oflag_tbl);
4102     host->c_cflag =
4103         target_to_host_bitmask(tswap32(target->c_cflag), cflag_tbl);
4104     host->c_lflag =
4105         target_to_host_bitmask(tswap32(target->c_lflag), lflag_tbl);
4106     host->c_line = target->c_line;
4107 
4108     memset(host->c_cc, 0, sizeof(host->c_cc));
4109     host->c_cc[VINTR] = target->c_cc[TARGET_VINTR];
4110     host->c_cc[VQUIT] = target->c_cc[TARGET_VQUIT];
4111     host->c_cc[VERASE] = target->c_cc[TARGET_VERASE];
4112     host->c_cc[VKILL] = target->c_cc[TARGET_VKILL];
4113     host->c_cc[VEOF] = target->c_cc[TARGET_VEOF];
4114     host->c_cc[VTIME] = target->c_cc[TARGET_VTIME];
4115     host->c_cc[VMIN] = target->c_cc[TARGET_VMIN];
4116     host->c_cc[VSWTC] = target->c_cc[TARGET_VSWTC];
4117     host->c_cc[VSTART] = target->c_cc[TARGET_VSTART];
4118     host->c_cc[VSTOP] = target->c_cc[TARGET_VSTOP];
4119     host->c_cc[VSUSP] = target->c_cc[TARGET_VSUSP];
4120     host->c_cc[VEOL] = target->c_cc[TARGET_VEOL];
4121     host->c_cc[VREPRINT] = target->c_cc[TARGET_VREPRINT];
4122     host->c_cc[VDISCARD] = target->c_cc[TARGET_VDISCARD];
4123     host->c_cc[VWERASE] = target->c_cc[TARGET_VWERASE];
4124     host->c_cc[VLNEXT] = target->c_cc[TARGET_VLNEXT];
4125     host->c_cc[VEOL2] = target->c_cc[TARGET_VEOL2];
4126 }
4127 
4128 static void host_to_target_termios (void *dst, const void *src)
4129 {
4130     struct target_termios *target = dst;
4131     const struct host_termios *host = src;
4132 
4133     target->c_iflag =
4134         tswap32(host_to_target_bitmask(host->c_iflag, iflag_tbl));
4135     target->c_oflag =
4136         tswap32(host_to_target_bitmask(host->c_oflag, oflag_tbl));
4137     target->c_cflag =
4138         tswap32(host_to_target_bitmask(host->c_cflag, cflag_tbl));
4139     target->c_lflag =
4140         tswap32(host_to_target_bitmask(host->c_lflag, lflag_tbl));
4141     target->c_line = host->c_line;
4142 
4143     memset(target->c_cc, 0, sizeof(target->c_cc));
4144     target->c_cc[TARGET_VINTR] = host->c_cc[VINTR];
4145     target->c_cc[TARGET_VQUIT] = host->c_cc[VQUIT];
4146     target->c_cc[TARGET_VERASE] = host->c_cc[VERASE];
4147     target->c_cc[TARGET_VKILL] = host->c_cc[VKILL];
4148     target->c_cc[TARGET_VEOF] = host->c_cc[VEOF];
4149     target->c_cc[TARGET_VTIME] = host->c_cc[VTIME];
4150     target->c_cc[TARGET_VMIN] = host->c_cc[VMIN];
4151     target->c_cc[TARGET_VSWTC] = host->c_cc[VSWTC];
4152     target->c_cc[TARGET_VSTART] = host->c_cc[VSTART];
4153     target->c_cc[TARGET_VSTOP] = host->c_cc[VSTOP];
4154     target->c_cc[TARGET_VSUSP] = host->c_cc[VSUSP];
4155     target->c_cc[TARGET_VEOL] = host->c_cc[VEOL];
4156     target->c_cc[TARGET_VREPRINT] = host->c_cc[VREPRINT];
4157     target->c_cc[TARGET_VDISCARD] = host->c_cc[VDISCARD];
4158     target->c_cc[TARGET_VWERASE] = host->c_cc[VWERASE];
4159     target->c_cc[TARGET_VLNEXT] = host->c_cc[VLNEXT];
4160     target->c_cc[TARGET_VEOL2] = host->c_cc[VEOL2];
4161 }
4162 
4163 static const StructEntry struct_termios_def = {
4164     .convert = { host_to_target_termios, target_to_host_termios },
4165     .size = { sizeof(struct target_termios), sizeof(struct host_termios) },
4166     .align = { __alignof__(struct target_termios), __alignof__(struct host_termios) },
4167 };
4168 
4169 static bitmask_transtbl mmap_flags_tbl[] = {
4170 	{ TARGET_MAP_SHARED, TARGET_MAP_SHARED, MAP_SHARED, MAP_SHARED },
4171 	{ TARGET_MAP_PRIVATE, TARGET_MAP_PRIVATE, MAP_PRIVATE, MAP_PRIVATE },
4172 	{ TARGET_MAP_FIXED, TARGET_MAP_FIXED, MAP_FIXED, MAP_FIXED },
4173 	{ TARGET_MAP_ANONYMOUS, TARGET_MAP_ANONYMOUS, MAP_ANONYMOUS, MAP_ANONYMOUS },
4174 	{ TARGET_MAP_GROWSDOWN, TARGET_MAP_GROWSDOWN, MAP_GROWSDOWN, MAP_GROWSDOWN },
4175 	{ TARGET_MAP_DENYWRITE, TARGET_MAP_DENYWRITE, MAP_DENYWRITE, MAP_DENYWRITE },
4176 	{ TARGET_MAP_EXECUTABLE, TARGET_MAP_EXECUTABLE, MAP_EXECUTABLE, MAP_EXECUTABLE },
4177 	{ TARGET_MAP_LOCKED, TARGET_MAP_LOCKED, MAP_LOCKED, MAP_LOCKED },
4178         { TARGET_MAP_NORESERVE, TARGET_MAP_NORESERVE, MAP_NORESERVE,
4179           MAP_NORESERVE },
4180 	{ 0, 0, 0, 0 }
4181 };
4182 
4183 #if defined(TARGET_I386)
4184 
4185 /* NOTE: there is really one LDT for all the threads */
4186 static uint8_t *ldt_table;
4187 
4188 static abi_long read_ldt(abi_ulong ptr, unsigned long bytecount)
4189 {
4190     int size;
4191     void *p;
4192 
4193     if (!ldt_table)
4194         return 0;
4195     size = TARGET_LDT_ENTRIES * TARGET_LDT_ENTRY_SIZE;
4196     if (size > bytecount)
4197         size = bytecount;
4198     p = lock_user(VERIFY_WRITE, ptr, size, 0);
4199     if (!p)
4200         return -TARGET_EFAULT;
4201     /* ??? Should this by byteswapped?  */
4202     memcpy(p, ldt_table, size);
4203     unlock_user(p, ptr, size);
4204     return size;
4205 }
4206 
4207 /* XXX: add locking support */
4208 static abi_long write_ldt(CPUX86State *env,
4209                           abi_ulong ptr, unsigned long bytecount, int oldmode)
4210 {
4211     struct target_modify_ldt_ldt_s ldt_info;
4212     struct target_modify_ldt_ldt_s *target_ldt_info;
4213     int seg_32bit, contents, read_exec_only, limit_in_pages;
4214     int seg_not_present, useable, lm;
4215     uint32_t *lp, entry_1, entry_2;
4216 
4217     if (bytecount != sizeof(ldt_info))
4218         return -TARGET_EINVAL;
4219     if (!lock_user_struct(VERIFY_READ, target_ldt_info, ptr, 1))
4220         return -TARGET_EFAULT;
4221     ldt_info.entry_number = tswap32(target_ldt_info->entry_number);
4222     ldt_info.base_addr = tswapal(target_ldt_info->base_addr);
4223     ldt_info.limit = tswap32(target_ldt_info->limit);
4224     ldt_info.flags = tswap32(target_ldt_info->flags);
4225     unlock_user_struct(target_ldt_info, ptr, 0);
4226 
4227     if (ldt_info.entry_number >= TARGET_LDT_ENTRIES)
4228         return -TARGET_EINVAL;
4229     seg_32bit = ldt_info.flags & 1;
4230     contents = (ldt_info.flags >> 1) & 3;
4231     read_exec_only = (ldt_info.flags >> 3) & 1;
4232     limit_in_pages = (ldt_info.flags >> 4) & 1;
4233     seg_not_present = (ldt_info.flags >> 5) & 1;
4234     useable = (ldt_info.flags >> 6) & 1;
4235 #ifdef TARGET_ABI32
4236     lm = 0;
4237 #else
4238     lm = (ldt_info.flags >> 7) & 1;
4239 #endif
4240     if (contents == 3) {
4241         if (oldmode)
4242             return -TARGET_EINVAL;
4243         if (seg_not_present == 0)
4244             return -TARGET_EINVAL;
4245     }
4246     /* allocate the LDT */
4247     if (!ldt_table) {
4248         env->ldt.base = target_mmap(0,
4249                                     TARGET_LDT_ENTRIES * TARGET_LDT_ENTRY_SIZE,
4250                                     PROT_READ|PROT_WRITE,
4251                                     MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
4252         if (env->ldt.base == -1)
4253             return -TARGET_ENOMEM;
4254         memset(g2h(env->ldt.base), 0,
4255                TARGET_LDT_ENTRIES * TARGET_LDT_ENTRY_SIZE);
4256         env->ldt.limit = 0xffff;
4257         ldt_table = g2h(env->ldt.base);
4258     }
4259 
4260     /* NOTE: same code as Linux kernel */
4261     /* Allow LDTs to be cleared by the user. */
4262     if (ldt_info.base_addr == 0 && ldt_info.limit == 0) {
4263         if (oldmode ||
4264             (contents == 0		&&
4265              read_exec_only == 1	&&
4266              seg_32bit == 0		&&
4267              limit_in_pages == 0	&&
4268              seg_not_present == 1	&&
4269              useable == 0 )) {
4270             entry_1 = 0;
4271             entry_2 = 0;
4272             goto install;
4273         }
4274     }
4275 
4276     entry_1 = ((ldt_info.base_addr & 0x0000ffff) << 16) |
4277         (ldt_info.limit & 0x0ffff);
4278     entry_2 = (ldt_info.base_addr & 0xff000000) |
4279         ((ldt_info.base_addr & 0x00ff0000) >> 16) |
4280         (ldt_info.limit & 0xf0000) |
4281         ((read_exec_only ^ 1) << 9) |
4282         (contents << 10) |
4283         ((seg_not_present ^ 1) << 15) |
4284         (seg_32bit << 22) |
4285         (limit_in_pages << 23) |
4286         (lm << 21) |
4287         0x7000;
4288     if (!oldmode)
4289         entry_2 |= (useable << 20);
4290 
4291     /* Install the new entry ...  */
4292 install:
4293     lp = (uint32_t *)(ldt_table + (ldt_info.entry_number << 3));
4294     lp[0] = tswap32(entry_1);
4295     lp[1] = tswap32(entry_2);
4296     return 0;
4297 }
4298 
4299 /* specific and weird i386 syscalls */
4300 static abi_long do_modify_ldt(CPUX86State *env, int func, abi_ulong ptr,
4301                               unsigned long bytecount)
4302 {
4303     abi_long ret;
4304 
4305     switch (func) {
4306     case 0:
4307         ret = read_ldt(ptr, bytecount);
4308         break;
4309     case 1:
4310         ret = write_ldt(env, ptr, bytecount, 1);
4311         break;
4312     case 0x11:
4313         ret = write_ldt(env, ptr, bytecount, 0);
4314         break;
4315     default:
4316         ret = -TARGET_ENOSYS;
4317         break;
4318     }
4319     return ret;
4320 }
4321 
4322 #if defined(TARGET_I386) && defined(TARGET_ABI32)
4323 abi_long do_set_thread_area(CPUX86State *env, abi_ulong ptr)
4324 {
4325     uint64_t *gdt_table = g2h(env->gdt.base);
4326     struct target_modify_ldt_ldt_s ldt_info;
4327     struct target_modify_ldt_ldt_s *target_ldt_info;
4328     int seg_32bit, contents, read_exec_only, limit_in_pages;
4329     int seg_not_present, useable, lm;
4330     uint32_t *lp, entry_1, entry_2;
4331     int i;
4332 
4333     lock_user_struct(VERIFY_WRITE, target_ldt_info, ptr, 1);
4334     if (!target_ldt_info)
4335         return -TARGET_EFAULT;
4336     ldt_info.entry_number = tswap32(target_ldt_info->entry_number);
4337     ldt_info.base_addr = tswapal(target_ldt_info->base_addr);
4338     ldt_info.limit = tswap32(target_ldt_info->limit);
4339     ldt_info.flags = tswap32(target_ldt_info->flags);
4340     if (ldt_info.entry_number == -1) {
4341         for (i=TARGET_GDT_ENTRY_TLS_MIN; i<=TARGET_GDT_ENTRY_TLS_MAX; i++) {
4342             if (gdt_table[i] == 0) {
4343                 ldt_info.entry_number = i;
4344                 target_ldt_info->entry_number = tswap32(i);
4345                 break;
4346             }
4347         }
4348     }
4349     unlock_user_struct(target_ldt_info, ptr, 1);
4350 
4351     if (ldt_info.entry_number < TARGET_GDT_ENTRY_TLS_MIN ||
4352         ldt_info.entry_number > TARGET_GDT_ENTRY_TLS_MAX)
4353            return -TARGET_EINVAL;
4354     seg_32bit = ldt_info.flags & 1;
4355     contents = (ldt_info.flags >> 1) & 3;
4356     read_exec_only = (ldt_info.flags >> 3) & 1;
4357     limit_in_pages = (ldt_info.flags >> 4) & 1;
4358     seg_not_present = (ldt_info.flags >> 5) & 1;
4359     useable = (ldt_info.flags >> 6) & 1;
4360 #ifdef TARGET_ABI32
4361     lm = 0;
4362 #else
4363     lm = (ldt_info.flags >> 7) & 1;
4364 #endif
4365 
4366     if (contents == 3) {
4367         if (seg_not_present == 0)
4368             return -TARGET_EINVAL;
4369     }
4370 
4371     /* NOTE: same code as Linux kernel */
4372     /* Allow LDTs to be cleared by the user. */
4373     if (ldt_info.base_addr == 0 && ldt_info.limit == 0) {
4374         if ((contents == 0             &&
4375              read_exec_only == 1       &&
4376              seg_32bit == 0            &&
4377              limit_in_pages == 0       &&
4378              seg_not_present == 1      &&
4379              useable == 0 )) {
4380             entry_1 = 0;
4381             entry_2 = 0;
4382             goto install;
4383         }
4384     }
4385 
4386     entry_1 = ((ldt_info.base_addr & 0x0000ffff) << 16) |
4387         (ldt_info.limit & 0x0ffff);
4388     entry_2 = (ldt_info.base_addr & 0xff000000) |
4389         ((ldt_info.base_addr & 0x00ff0000) >> 16) |
4390         (ldt_info.limit & 0xf0000) |
4391         ((read_exec_only ^ 1) << 9) |
4392         (contents << 10) |
4393         ((seg_not_present ^ 1) << 15) |
4394         (seg_32bit << 22) |
4395         (limit_in_pages << 23) |
4396         (useable << 20) |
4397         (lm << 21) |
4398         0x7000;
4399 
4400     /* Install the new entry ...  */
4401 install:
4402     lp = (uint32_t *)(gdt_table + ldt_info.entry_number);
4403     lp[0] = tswap32(entry_1);
4404     lp[1] = tswap32(entry_2);
4405     return 0;
4406 }
4407 
4408 static abi_long do_get_thread_area(CPUX86State *env, abi_ulong ptr)
4409 {
4410     struct target_modify_ldt_ldt_s *target_ldt_info;
4411     uint64_t *gdt_table = g2h(env->gdt.base);
4412     uint32_t base_addr, limit, flags;
4413     int seg_32bit, contents, read_exec_only, limit_in_pages, idx;
4414     int seg_not_present, useable, lm;
4415     uint32_t *lp, entry_1, entry_2;
4416 
4417     lock_user_struct(VERIFY_WRITE, target_ldt_info, ptr, 1);
4418     if (!target_ldt_info)
4419         return -TARGET_EFAULT;
4420     idx = tswap32(target_ldt_info->entry_number);
4421     if (idx < TARGET_GDT_ENTRY_TLS_MIN ||
4422         idx > TARGET_GDT_ENTRY_TLS_MAX) {
4423         unlock_user_struct(target_ldt_info, ptr, 1);
4424         return -TARGET_EINVAL;
4425     }
4426     lp = (uint32_t *)(gdt_table + idx);
4427     entry_1 = tswap32(lp[0]);
4428     entry_2 = tswap32(lp[1]);
4429 
4430     read_exec_only = ((entry_2 >> 9) & 1) ^ 1;
4431     contents = (entry_2 >> 10) & 3;
4432     seg_not_present = ((entry_2 >> 15) & 1) ^ 1;
4433     seg_32bit = (entry_2 >> 22) & 1;
4434     limit_in_pages = (entry_2 >> 23) & 1;
4435     useable = (entry_2 >> 20) & 1;
4436 #ifdef TARGET_ABI32
4437     lm = 0;
4438 #else
4439     lm = (entry_2 >> 21) & 1;
4440 #endif
4441     flags = (seg_32bit << 0) | (contents << 1) |
4442         (read_exec_only << 3) | (limit_in_pages << 4) |
4443         (seg_not_present << 5) | (useable << 6) | (lm << 7);
4444     limit = (entry_1 & 0xffff) | (entry_2  & 0xf0000);
4445     base_addr = (entry_1 >> 16) |
4446         (entry_2 & 0xff000000) |
4447         ((entry_2 & 0xff) << 16);
4448     target_ldt_info->base_addr = tswapal(base_addr);
4449     target_ldt_info->limit = tswap32(limit);
4450     target_ldt_info->flags = tswap32(flags);
4451     unlock_user_struct(target_ldt_info, ptr, 1);
4452     return 0;
4453 }
4454 #endif /* TARGET_I386 && TARGET_ABI32 */
4455 
4456 #ifndef TARGET_ABI32
4457 abi_long do_arch_prctl(CPUX86State *env, int code, abi_ulong addr)
4458 {
4459     abi_long ret = 0;
4460     abi_ulong val;
4461     int idx;
4462 
4463     switch(code) {
4464     case TARGET_ARCH_SET_GS:
4465     case TARGET_ARCH_SET_FS:
4466         if (code == TARGET_ARCH_SET_GS)
4467             idx = R_GS;
4468         else
4469             idx = R_FS;
4470         cpu_x86_load_seg(env, idx, 0);
4471         env->segs[idx].base = addr;
4472         break;
4473     case TARGET_ARCH_GET_GS:
4474     case TARGET_ARCH_GET_FS:
4475         if (code == TARGET_ARCH_GET_GS)
4476             idx = R_GS;
4477         else
4478             idx = R_FS;
4479         val = env->segs[idx].base;
4480         if (put_user(val, addr, abi_ulong))
4481             ret = -TARGET_EFAULT;
4482         break;
4483     default:
4484         ret = -TARGET_EINVAL;
4485         break;
4486     }
4487     return ret;
4488 }
4489 #endif
4490 
4491 #endif /* defined(TARGET_I386) */
4492 
4493 #define NEW_STACK_SIZE 0x40000
4494 
4495 
4496 static pthread_mutex_t clone_lock = PTHREAD_MUTEX_INITIALIZER;
4497 typedef struct {
4498     CPUArchState *env;
4499     pthread_mutex_t mutex;
4500     pthread_cond_t cond;
4501     pthread_t thread;
4502     uint32_t tid;
4503     abi_ulong child_tidptr;
4504     abi_ulong parent_tidptr;
4505     sigset_t sigmask;
4506 } new_thread_info;
4507 
4508 static void *clone_func(void *arg)
4509 {
4510     new_thread_info *info = arg;
4511     CPUArchState *env;
4512     CPUState *cpu;
4513     TaskState *ts;
4514 
4515     rcu_register_thread();
4516     env = info->env;
4517     cpu = ENV_GET_CPU(env);
4518     thread_cpu = cpu;
4519     ts = (TaskState *)cpu->opaque;
4520     info->tid = gettid();
4521     cpu->host_tid = info->tid;
4522     task_settid(ts);
4523     if (info->child_tidptr)
4524         put_user_u32(info->tid, info->child_tidptr);
4525     if (info->parent_tidptr)
4526         put_user_u32(info->tid, info->parent_tidptr);
4527     /* Enable signals.  */
4528     sigprocmask(SIG_SETMASK, &info->sigmask, NULL);
4529     /* Signal to the parent that we're ready.  */
4530     pthread_mutex_lock(&info->mutex);
4531     pthread_cond_broadcast(&info->cond);
4532     pthread_mutex_unlock(&info->mutex);
4533     /* Wait until the parent has finshed initializing the tls state.  */
4534     pthread_mutex_lock(&clone_lock);
4535     pthread_mutex_unlock(&clone_lock);
4536     cpu_loop(env);
4537     /* never exits */
4538     return NULL;
4539 }
4540 
4541 /* do_fork() Must return host values and target errnos (unlike most
4542    do_*() functions). */
4543 static int do_fork(CPUArchState *env, unsigned int flags, abi_ulong newsp,
4544                    abi_ulong parent_tidptr, target_ulong newtls,
4545                    abi_ulong child_tidptr)
4546 {
4547     CPUState *cpu = ENV_GET_CPU(env);
4548     int ret;
4549     TaskState *ts;
4550     CPUState *new_cpu;
4551     CPUArchState *new_env;
4552     unsigned int nptl_flags;
4553     sigset_t sigmask;
4554 
4555     /* Emulate vfork() with fork() */
4556     if (flags & CLONE_VFORK)
4557         flags &= ~(CLONE_VFORK | CLONE_VM);
4558 
4559     if (flags & CLONE_VM) {
4560         TaskState *parent_ts = (TaskState *)cpu->opaque;
4561         new_thread_info info;
4562         pthread_attr_t attr;
4563 
4564         ts = g_malloc0(sizeof(TaskState));
4565         init_task_state(ts);
4566         /* we create a new CPU instance. */
4567         new_env = cpu_copy(env);
4568         /* Init regs that differ from the parent.  */
4569         cpu_clone_regs(new_env, newsp);
4570         new_cpu = ENV_GET_CPU(new_env);
4571         new_cpu->opaque = ts;
4572         ts->bprm = parent_ts->bprm;
4573         ts->info = parent_ts->info;
4574         nptl_flags = flags;
4575         flags &= ~CLONE_NPTL_FLAGS2;
4576 
4577         if (nptl_flags & CLONE_CHILD_CLEARTID) {
4578             ts->child_tidptr = child_tidptr;
4579         }
4580 
4581         if (nptl_flags & CLONE_SETTLS)
4582             cpu_set_tls (new_env, newtls);
4583 
4584         /* Grab a mutex so that thread setup appears atomic.  */
4585         pthread_mutex_lock(&clone_lock);
4586 
4587         memset(&info, 0, sizeof(info));
4588         pthread_mutex_init(&info.mutex, NULL);
4589         pthread_mutex_lock(&info.mutex);
4590         pthread_cond_init(&info.cond, NULL);
4591         info.env = new_env;
4592         if (nptl_flags & CLONE_CHILD_SETTID)
4593             info.child_tidptr = child_tidptr;
4594         if (nptl_flags & CLONE_PARENT_SETTID)
4595             info.parent_tidptr = parent_tidptr;
4596 
4597         ret = pthread_attr_init(&attr);
4598         ret = pthread_attr_setstacksize(&attr, NEW_STACK_SIZE);
4599         ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
4600         /* It is not safe to deliver signals until the child has finished
4601            initializing, so temporarily block all signals.  */
4602         sigfillset(&sigmask);
4603         sigprocmask(SIG_BLOCK, &sigmask, &info.sigmask);
4604 
4605         ret = pthread_create(&info.thread, &attr, clone_func, &info);
4606         /* TODO: Free new CPU state if thread creation failed.  */
4607 
4608         sigprocmask(SIG_SETMASK, &info.sigmask, NULL);
4609         pthread_attr_destroy(&attr);
4610         if (ret == 0) {
4611             /* Wait for the child to initialize.  */
4612             pthread_cond_wait(&info.cond, &info.mutex);
4613             ret = info.tid;
4614             if (flags & CLONE_PARENT_SETTID)
4615                 put_user_u32(ret, parent_tidptr);
4616         } else {
4617             ret = -1;
4618         }
4619         pthread_mutex_unlock(&info.mutex);
4620         pthread_cond_destroy(&info.cond);
4621         pthread_mutex_destroy(&info.mutex);
4622         pthread_mutex_unlock(&clone_lock);
4623     } else {
4624         /* if no CLONE_VM, we consider it is a fork */
4625         if ((flags & ~(CSIGNAL | CLONE_NPTL_FLAGS2)) != 0)
4626             return -EINVAL;
4627         fork_start();
4628         ret = fork();
4629         if (ret == 0) {
4630             /* Child Process.  */
4631             rcu_after_fork();
4632             cpu_clone_regs(env, newsp);
4633             fork_end(1);
4634             /* There is a race condition here.  The parent process could
4635                theoretically read the TID in the child process before the child
4636                tid is set.  This would require using either ptrace
4637                (not implemented) or having *_tidptr to point at a shared memory
4638                mapping.  We can't repeat the spinlock hack used above because
4639                the child process gets its own copy of the lock.  */
4640             if (flags & CLONE_CHILD_SETTID)
4641                 put_user_u32(gettid(), child_tidptr);
4642             if (flags & CLONE_PARENT_SETTID)
4643                 put_user_u32(gettid(), parent_tidptr);
4644             ts = (TaskState *)cpu->opaque;
4645             if (flags & CLONE_SETTLS)
4646                 cpu_set_tls (env, newtls);
4647             if (flags & CLONE_CHILD_CLEARTID)
4648                 ts->child_tidptr = child_tidptr;
4649         } else {
4650             fork_end(0);
4651         }
4652     }
4653     return ret;
4654 }
4655 
4656 /* warning : doesn't handle linux specific flags... */
4657 static int target_to_host_fcntl_cmd(int cmd)
4658 {
4659     switch(cmd) {
4660 	case TARGET_F_DUPFD:
4661 	case TARGET_F_GETFD:
4662 	case TARGET_F_SETFD:
4663 	case TARGET_F_GETFL:
4664 	case TARGET_F_SETFL:
4665             return cmd;
4666         case TARGET_F_GETLK:
4667 	    return F_GETLK;
4668 	case TARGET_F_SETLK:
4669 	    return F_SETLK;
4670 	case TARGET_F_SETLKW:
4671 	    return F_SETLKW;
4672 	case TARGET_F_GETOWN:
4673 	    return F_GETOWN;
4674 	case TARGET_F_SETOWN:
4675 	    return F_SETOWN;
4676 	case TARGET_F_GETSIG:
4677 	    return F_GETSIG;
4678 	case TARGET_F_SETSIG:
4679 	    return F_SETSIG;
4680 #if TARGET_ABI_BITS == 32
4681         case TARGET_F_GETLK64:
4682 	    return F_GETLK64;
4683 	case TARGET_F_SETLK64:
4684 	    return F_SETLK64;
4685 	case TARGET_F_SETLKW64:
4686 	    return F_SETLKW64;
4687 #endif
4688         case TARGET_F_SETLEASE:
4689             return F_SETLEASE;
4690         case TARGET_F_GETLEASE:
4691             return F_GETLEASE;
4692 #ifdef F_DUPFD_CLOEXEC
4693         case TARGET_F_DUPFD_CLOEXEC:
4694             return F_DUPFD_CLOEXEC;
4695 #endif
4696         case TARGET_F_NOTIFY:
4697             return F_NOTIFY;
4698 #ifdef F_GETOWN_EX
4699 	case TARGET_F_GETOWN_EX:
4700 	    return F_GETOWN_EX;
4701 #endif
4702 #ifdef F_SETOWN_EX
4703 	case TARGET_F_SETOWN_EX:
4704 	    return F_SETOWN_EX;
4705 #endif
4706 	default:
4707             return -TARGET_EINVAL;
4708     }
4709     return -TARGET_EINVAL;
4710 }
4711 
4712 #define TRANSTBL_CONVERT(a) { -1, TARGET_##a, -1, a }
4713 static const bitmask_transtbl flock_tbl[] = {
4714     TRANSTBL_CONVERT(F_RDLCK),
4715     TRANSTBL_CONVERT(F_WRLCK),
4716     TRANSTBL_CONVERT(F_UNLCK),
4717     TRANSTBL_CONVERT(F_EXLCK),
4718     TRANSTBL_CONVERT(F_SHLCK),
4719     { 0, 0, 0, 0 }
4720 };
4721 
4722 static abi_long do_fcntl(int fd, int cmd, abi_ulong arg)
4723 {
4724     struct flock fl;
4725     struct target_flock *target_fl;
4726     struct flock64 fl64;
4727     struct target_flock64 *target_fl64;
4728 #ifdef F_GETOWN_EX
4729     struct f_owner_ex fox;
4730     struct target_f_owner_ex *target_fox;
4731 #endif
4732     abi_long ret;
4733     int host_cmd = target_to_host_fcntl_cmd(cmd);
4734 
4735     if (host_cmd == -TARGET_EINVAL)
4736 	    return host_cmd;
4737 
4738     switch(cmd) {
4739     case TARGET_F_GETLK:
4740         if (!lock_user_struct(VERIFY_READ, target_fl, arg, 1))
4741             return -TARGET_EFAULT;
4742         fl.l_type =
4743                   target_to_host_bitmask(tswap16(target_fl->l_type), flock_tbl);
4744         fl.l_whence = tswap16(target_fl->l_whence);
4745         fl.l_start = tswapal(target_fl->l_start);
4746         fl.l_len = tswapal(target_fl->l_len);
4747         fl.l_pid = tswap32(target_fl->l_pid);
4748         unlock_user_struct(target_fl, arg, 0);
4749         ret = get_errno(fcntl(fd, host_cmd, &fl));
4750         if (ret == 0) {
4751             if (!lock_user_struct(VERIFY_WRITE, target_fl, arg, 0))
4752                 return -TARGET_EFAULT;
4753             target_fl->l_type =
4754                           host_to_target_bitmask(tswap16(fl.l_type), flock_tbl);
4755             target_fl->l_whence = tswap16(fl.l_whence);
4756             target_fl->l_start = tswapal(fl.l_start);
4757             target_fl->l_len = tswapal(fl.l_len);
4758             target_fl->l_pid = tswap32(fl.l_pid);
4759             unlock_user_struct(target_fl, arg, 1);
4760         }
4761         break;
4762 
4763     case TARGET_F_SETLK:
4764     case TARGET_F_SETLKW:
4765         if (!lock_user_struct(VERIFY_READ, target_fl, arg, 1))
4766             return -TARGET_EFAULT;
4767         fl.l_type =
4768                   target_to_host_bitmask(tswap16(target_fl->l_type), flock_tbl);
4769         fl.l_whence = tswap16(target_fl->l_whence);
4770         fl.l_start = tswapal(target_fl->l_start);
4771         fl.l_len = tswapal(target_fl->l_len);
4772         fl.l_pid = tswap32(target_fl->l_pid);
4773         unlock_user_struct(target_fl, arg, 0);
4774         ret = get_errno(fcntl(fd, host_cmd, &fl));
4775         break;
4776 
4777     case TARGET_F_GETLK64:
4778         if (!lock_user_struct(VERIFY_READ, target_fl64, arg, 1))
4779             return -TARGET_EFAULT;
4780         fl64.l_type =
4781            target_to_host_bitmask(tswap16(target_fl64->l_type), flock_tbl) >> 1;
4782         fl64.l_whence = tswap16(target_fl64->l_whence);
4783         fl64.l_start = tswap64(target_fl64->l_start);
4784         fl64.l_len = tswap64(target_fl64->l_len);
4785         fl64.l_pid = tswap32(target_fl64->l_pid);
4786         unlock_user_struct(target_fl64, arg, 0);
4787         ret = get_errno(fcntl(fd, host_cmd, &fl64));
4788         if (ret == 0) {
4789             if (!lock_user_struct(VERIFY_WRITE, target_fl64, arg, 0))
4790                 return -TARGET_EFAULT;
4791             target_fl64->l_type =
4792                    host_to_target_bitmask(tswap16(fl64.l_type), flock_tbl) >> 1;
4793             target_fl64->l_whence = tswap16(fl64.l_whence);
4794             target_fl64->l_start = tswap64(fl64.l_start);
4795             target_fl64->l_len = tswap64(fl64.l_len);
4796             target_fl64->l_pid = tswap32(fl64.l_pid);
4797             unlock_user_struct(target_fl64, arg, 1);
4798         }
4799         break;
4800     case TARGET_F_SETLK64:
4801     case TARGET_F_SETLKW64:
4802         if (!lock_user_struct(VERIFY_READ, target_fl64, arg, 1))
4803             return -TARGET_EFAULT;
4804         fl64.l_type =
4805            target_to_host_bitmask(tswap16(target_fl64->l_type), flock_tbl) >> 1;
4806         fl64.l_whence = tswap16(target_fl64->l_whence);
4807         fl64.l_start = tswap64(target_fl64->l_start);
4808         fl64.l_len = tswap64(target_fl64->l_len);
4809         fl64.l_pid = tswap32(target_fl64->l_pid);
4810         unlock_user_struct(target_fl64, arg, 0);
4811         ret = get_errno(fcntl(fd, host_cmd, &fl64));
4812         break;
4813 
4814     case TARGET_F_GETFL:
4815         ret = get_errno(fcntl(fd, host_cmd, arg));
4816         if (ret >= 0) {
4817             ret = host_to_target_bitmask(ret, fcntl_flags_tbl);
4818         }
4819         break;
4820 
4821     case TARGET_F_SETFL:
4822         ret = get_errno(fcntl(fd, host_cmd, target_to_host_bitmask(arg, fcntl_flags_tbl)));
4823         break;
4824 
4825 #ifdef F_GETOWN_EX
4826     case TARGET_F_GETOWN_EX:
4827         ret = get_errno(fcntl(fd, host_cmd, &fox));
4828         if (ret >= 0) {
4829             if (!lock_user_struct(VERIFY_WRITE, target_fox, arg, 0))
4830                 return -TARGET_EFAULT;
4831             target_fox->type = tswap32(fox.type);
4832             target_fox->pid = tswap32(fox.pid);
4833             unlock_user_struct(target_fox, arg, 1);
4834         }
4835         break;
4836 #endif
4837 
4838 #ifdef F_SETOWN_EX
4839     case TARGET_F_SETOWN_EX:
4840         if (!lock_user_struct(VERIFY_READ, target_fox, arg, 1))
4841             return -TARGET_EFAULT;
4842         fox.type = tswap32(target_fox->type);
4843         fox.pid = tswap32(target_fox->pid);
4844         unlock_user_struct(target_fox, arg, 0);
4845         ret = get_errno(fcntl(fd, host_cmd, &fox));
4846         break;
4847 #endif
4848 
4849     case TARGET_F_SETOWN:
4850     case TARGET_F_GETOWN:
4851     case TARGET_F_SETSIG:
4852     case TARGET_F_GETSIG:
4853     case TARGET_F_SETLEASE:
4854     case TARGET_F_GETLEASE:
4855         ret = get_errno(fcntl(fd, host_cmd, arg));
4856         break;
4857 
4858     default:
4859         ret = get_errno(fcntl(fd, cmd, arg));
4860         break;
4861     }
4862     return ret;
4863 }
4864 
4865 #ifdef USE_UID16
4866 
4867 static inline int high2lowuid(int uid)
4868 {
4869     if (uid > 65535)
4870         return 65534;
4871     else
4872         return uid;
4873 }
4874 
4875 static inline int high2lowgid(int gid)
4876 {
4877     if (gid > 65535)
4878         return 65534;
4879     else
4880         return gid;
4881 }
4882 
4883 static inline int low2highuid(int uid)
4884 {
4885     if ((int16_t)uid == -1)
4886         return -1;
4887     else
4888         return uid;
4889 }
4890 
4891 static inline int low2highgid(int gid)
4892 {
4893     if ((int16_t)gid == -1)
4894         return -1;
4895     else
4896         return gid;
4897 }
4898 static inline int tswapid(int id)
4899 {
4900     return tswap16(id);
4901 }
4902 
4903 #define put_user_id(x, gaddr) put_user_u16(x, gaddr)
4904 
4905 #else /* !USE_UID16 */
4906 static inline int high2lowuid(int uid)
4907 {
4908     return uid;
4909 }
4910 static inline int high2lowgid(int gid)
4911 {
4912     return gid;
4913 }
4914 static inline int low2highuid(int uid)
4915 {
4916     return uid;
4917 }
4918 static inline int low2highgid(int gid)
4919 {
4920     return gid;
4921 }
4922 static inline int tswapid(int id)
4923 {
4924     return tswap32(id);
4925 }
4926 
4927 #define put_user_id(x, gaddr) put_user_u32(x, gaddr)
4928 
4929 #endif /* USE_UID16 */
4930 
4931 void syscall_init(void)
4932 {
4933     IOCTLEntry *ie;
4934     const argtype *arg_type;
4935     int size;
4936     int i;
4937 
4938     thunk_init(STRUCT_MAX);
4939 
4940 #define STRUCT(name, ...) thunk_register_struct(STRUCT_ ## name, #name, struct_ ## name ## _def);
4941 #define STRUCT_SPECIAL(name) thunk_register_struct_direct(STRUCT_ ## name, #name, &struct_ ## name ## _def);
4942 #include "syscall_types.h"
4943 #undef STRUCT
4944 #undef STRUCT_SPECIAL
4945 
4946     /* Build target_to_host_errno_table[] table from
4947      * host_to_target_errno_table[]. */
4948     for (i = 0; i < ERRNO_TABLE_SIZE; i++) {
4949         target_to_host_errno_table[host_to_target_errno_table[i]] = i;
4950     }
4951 
4952     /* we patch the ioctl size if necessary. We rely on the fact that
4953        no ioctl has all the bits at '1' in the size field */
4954     ie = ioctl_entries;
4955     while (ie->target_cmd != 0) {
4956         if (((ie->target_cmd >> TARGET_IOC_SIZESHIFT) & TARGET_IOC_SIZEMASK) ==
4957             TARGET_IOC_SIZEMASK) {
4958             arg_type = ie->arg_type;
4959             if (arg_type[0] != TYPE_PTR) {
4960                 fprintf(stderr, "cannot patch size for ioctl 0x%x\n",
4961                         ie->target_cmd);
4962                 exit(1);
4963             }
4964             arg_type++;
4965             size = thunk_type_size(arg_type, 0);
4966             ie->target_cmd = (ie->target_cmd &
4967                               ~(TARGET_IOC_SIZEMASK << TARGET_IOC_SIZESHIFT)) |
4968                 (size << TARGET_IOC_SIZESHIFT);
4969         }
4970 
4971         /* automatic consistency check if same arch */
4972 #if (defined(__i386__) && defined(TARGET_I386) && defined(TARGET_ABI32)) || \
4973     (defined(__x86_64__) && defined(TARGET_X86_64))
4974         if (unlikely(ie->target_cmd != ie->host_cmd)) {
4975             fprintf(stderr, "ERROR: ioctl(%s): target=0x%x host=0x%x\n",
4976                     ie->name, ie->target_cmd, ie->host_cmd);
4977         }
4978 #endif
4979         ie++;
4980     }
4981 }
4982 
4983 #if TARGET_ABI_BITS == 32
4984 static inline uint64_t target_offset64(uint32_t word0, uint32_t word1)
4985 {
4986 #ifdef TARGET_WORDS_BIGENDIAN
4987     return ((uint64_t)word0 << 32) | word1;
4988 #else
4989     return ((uint64_t)word1 << 32) | word0;
4990 #endif
4991 }
4992 #else /* TARGET_ABI_BITS == 32 */
4993 static inline uint64_t target_offset64(uint64_t word0, uint64_t word1)
4994 {
4995     return word0;
4996 }
4997 #endif /* TARGET_ABI_BITS != 32 */
4998 
4999 #ifdef TARGET_NR_truncate64
5000 static inline abi_long target_truncate64(void *cpu_env, const char *arg1,
5001                                          abi_long arg2,
5002                                          abi_long arg3,
5003                                          abi_long arg4)
5004 {
5005     if (regpairs_aligned(cpu_env)) {
5006         arg2 = arg3;
5007         arg3 = arg4;
5008     }
5009     return get_errno(truncate64(arg1, target_offset64(arg2, arg3)));
5010 }
5011 #endif
5012 
5013 #ifdef TARGET_NR_ftruncate64
5014 static inline abi_long target_ftruncate64(void *cpu_env, abi_long arg1,
5015                                           abi_long arg2,
5016                                           abi_long arg3,
5017                                           abi_long arg4)
5018 {
5019     if (regpairs_aligned(cpu_env)) {
5020         arg2 = arg3;
5021         arg3 = arg4;
5022     }
5023     return get_errno(ftruncate64(arg1, target_offset64(arg2, arg3)));
5024 }
5025 #endif
5026 
5027 static inline abi_long target_to_host_timespec(struct timespec *host_ts,
5028                                                abi_ulong target_addr)
5029 {
5030     struct target_timespec *target_ts;
5031 
5032     if (!lock_user_struct(VERIFY_READ, target_ts, target_addr, 1))
5033         return -TARGET_EFAULT;
5034     host_ts->tv_sec = tswapal(target_ts->tv_sec);
5035     host_ts->tv_nsec = tswapal(target_ts->tv_nsec);
5036     unlock_user_struct(target_ts, target_addr, 0);
5037     return 0;
5038 }
5039 
5040 static inline abi_long host_to_target_timespec(abi_ulong target_addr,
5041                                                struct timespec *host_ts)
5042 {
5043     struct target_timespec *target_ts;
5044 
5045     if (!lock_user_struct(VERIFY_WRITE, target_ts, target_addr, 0))
5046         return -TARGET_EFAULT;
5047     target_ts->tv_sec = tswapal(host_ts->tv_sec);
5048     target_ts->tv_nsec = tswapal(host_ts->tv_nsec);
5049     unlock_user_struct(target_ts, target_addr, 1);
5050     return 0;
5051 }
5052 
5053 static inline abi_long target_to_host_itimerspec(struct itimerspec *host_itspec,
5054                                                  abi_ulong target_addr)
5055 {
5056     struct target_itimerspec *target_itspec;
5057 
5058     if (!lock_user_struct(VERIFY_READ, target_itspec, target_addr, 1)) {
5059         return -TARGET_EFAULT;
5060     }
5061 
5062     host_itspec->it_interval.tv_sec =
5063                             tswapal(target_itspec->it_interval.tv_sec);
5064     host_itspec->it_interval.tv_nsec =
5065                             tswapal(target_itspec->it_interval.tv_nsec);
5066     host_itspec->it_value.tv_sec = tswapal(target_itspec->it_value.tv_sec);
5067     host_itspec->it_value.tv_nsec = tswapal(target_itspec->it_value.tv_nsec);
5068 
5069     unlock_user_struct(target_itspec, target_addr, 1);
5070     return 0;
5071 }
5072 
5073 static inline abi_long host_to_target_itimerspec(abi_ulong target_addr,
5074                                                struct itimerspec *host_its)
5075 {
5076     struct target_itimerspec *target_itspec;
5077 
5078     if (!lock_user_struct(VERIFY_WRITE, target_itspec, target_addr, 0)) {
5079         return -TARGET_EFAULT;
5080     }
5081 
5082     target_itspec->it_interval.tv_sec = tswapal(host_its->it_interval.tv_sec);
5083     target_itspec->it_interval.tv_nsec = tswapal(host_its->it_interval.tv_nsec);
5084 
5085     target_itspec->it_value.tv_sec = tswapal(host_its->it_value.tv_sec);
5086     target_itspec->it_value.tv_nsec = tswapal(host_its->it_value.tv_nsec);
5087 
5088     unlock_user_struct(target_itspec, target_addr, 0);
5089     return 0;
5090 }
5091 
5092 static inline abi_long target_to_host_sigevent(struct sigevent *host_sevp,
5093                                                abi_ulong target_addr)
5094 {
5095     struct target_sigevent *target_sevp;
5096 
5097     if (!lock_user_struct(VERIFY_READ, target_sevp, target_addr, 1)) {
5098         return -TARGET_EFAULT;
5099     }
5100 
5101     /* This union is awkward on 64 bit systems because it has a 32 bit
5102      * integer and a pointer in it; we follow the conversion approach
5103      * used for handling sigval types in signal.c so the guest should get
5104      * the correct value back even if we did a 64 bit byteswap and it's
5105      * using the 32 bit integer.
5106      */
5107     host_sevp->sigev_value.sival_ptr =
5108         (void *)(uintptr_t)tswapal(target_sevp->sigev_value.sival_ptr);
5109     host_sevp->sigev_signo =
5110         target_to_host_signal(tswap32(target_sevp->sigev_signo));
5111     host_sevp->sigev_notify = tswap32(target_sevp->sigev_notify);
5112     host_sevp->_sigev_un._tid = tswap32(target_sevp->_sigev_un._tid);
5113 
5114     unlock_user_struct(target_sevp, target_addr, 1);
5115     return 0;
5116 }
5117 
5118 #if defined(TARGET_NR_mlockall)
5119 static inline int target_to_host_mlockall_arg(int arg)
5120 {
5121     int result = 0;
5122 
5123     if (arg & TARGET_MLOCKALL_MCL_CURRENT) {
5124         result |= MCL_CURRENT;
5125     }
5126     if (arg & TARGET_MLOCKALL_MCL_FUTURE) {
5127         result |= MCL_FUTURE;
5128     }
5129     return result;
5130 }
5131 #endif
5132 
5133 #if defined(TARGET_NR_stat64) || defined(TARGET_NR_newfstatat)
5134 static inline abi_long host_to_target_stat64(void *cpu_env,
5135                                              abi_ulong target_addr,
5136                                              struct stat *host_st)
5137 {
5138 #if defined(TARGET_ARM) && defined(TARGET_ABI32)
5139     if (((CPUARMState *)cpu_env)->eabi) {
5140         struct target_eabi_stat64 *target_st;
5141 
5142         if (!lock_user_struct(VERIFY_WRITE, target_st, target_addr, 0))
5143             return -TARGET_EFAULT;
5144         memset(target_st, 0, sizeof(struct target_eabi_stat64));
5145         __put_user(host_st->st_dev, &target_st->st_dev);
5146         __put_user(host_st->st_ino, &target_st->st_ino);
5147 #ifdef TARGET_STAT64_HAS_BROKEN_ST_INO
5148         __put_user(host_st->st_ino, &target_st->__st_ino);
5149 #endif
5150         __put_user(host_st->st_mode, &target_st->st_mode);
5151         __put_user(host_st->st_nlink, &target_st->st_nlink);
5152         __put_user(host_st->st_uid, &target_st->st_uid);
5153         __put_user(host_st->st_gid, &target_st->st_gid);
5154         __put_user(host_st->st_rdev, &target_st->st_rdev);
5155         __put_user(host_st->st_size, &target_st->st_size);
5156         __put_user(host_st->st_blksize, &target_st->st_blksize);
5157         __put_user(host_st->st_blocks, &target_st->st_blocks);
5158         __put_user(host_st->st_atime, &target_st->target_st_atime);
5159         __put_user(host_st->st_mtime, &target_st->target_st_mtime);
5160         __put_user(host_st->st_ctime, &target_st->target_st_ctime);
5161         unlock_user_struct(target_st, target_addr, 1);
5162     } else
5163 #endif
5164     {
5165 #if defined(TARGET_HAS_STRUCT_STAT64)
5166         struct target_stat64 *target_st;
5167 #else
5168         struct target_stat *target_st;
5169 #endif
5170 
5171         if (!lock_user_struct(VERIFY_WRITE, target_st, target_addr, 0))
5172             return -TARGET_EFAULT;
5173         memset(target_st, 0, sizeof(*target_st));
5174         __put_user(host_st->st_dev, &target_st->st_dev);
5175         __put_user(host_st->st_ino, &target_st->st_ino);
5176 #ifdef TARGET_STAT64_HAS_BROKEN_ST_INO
5177         __put_user(host_st->st_ino, &target_st->__st_ino);
5178 #endif
5179         __put_user(host_st->st_mode, &target_st->st_mode);
5180         __put_user(host_st->st_nlink, &target_st->st_nlink);
5181         __put_user(host_st->st_uid, &target_st->st_uid);
5182         __put_user(host_st->st_gid, &target_st->st_gid);
5183         __put_user(host_st->st_rdev, &target_st->st_rdev);
5184         /* XXX: better use of kernel struct */
5185         __put_user(host_st->st_size, &target_st->st_size);
5186         __put_user(host_st->st_blksize, &target_st->st_blksize);
5187         __put_user(host_st->st_blocks, &target_st->st_blocks);
5188         __put_user(host_st->st_atime, &target_st->target_st_atime);
5189         __put_user(host_st->st_mtime, &target_st->target_st_mtime);
5190         __put_user(host_st->st_ctime, &target_st->target_st_ctime);
5191         unlock_user_struct(target_st, target_addr, 1);
5192     }
5193 
5194     return 0;
5195 }
5196 #endif
5197 
5198 /* ??? Using host futex calls even when target atomic operations
5199    are not really atomic probably breaks things.  However implementing
5200    futexes locally would make futexes shared between multiple processes
5201    tricky.  However they're probably useless because guest atomic
5202    operations won't work either.  */
5203 static int do_futex(target_ulong uaddr, int op, int val, target_ulong timeout,
5204                     target_ulong uaddr2, int val3)
5205 {
5206     struct timespec ts, *pts;
5207     int base_op;
5208 
5209     /* ??? We assume FUTEX_* constants are the same on both host
5210        and target.  */
5211 #ifdef FUTEX_CMD_MASK
5212     base_op = op & FUTEX_CMD_MASK;
5213 #else
5214     base_op = op;
5215 #endif
5216     switch (base_op) {
5217     case FUTEX_WAIT:
5218     case FUTEX_WAIT_BITSET:
5219         if (timeout) {
5220             pts = &ts;
5221             target_to_host_timespec(pts, timeout);
5222         } else {
5223             pts = NULL;
5224         }
5225         return get_errno(sys_futex(g2h(uaddr), op, tswap32(val),
5226                          pts, NULL, val3));
5227     case FUTEX_WAKE:
5228         return get_errno(sys_futex(g2h(uaddr), op, val, NULL, NULL, 0));
5229     case FUTEX_FD:
5230         return get_errno(sys_futex(g2h(uaddr), op, val, NULL, NULL, 0));
5231     case FUTEX_REQUEUE:
5232     case FUTEX_CMP_REQUEUE:
5233     case FUTEX_WAKE_OP:
5234         /* For FUTEX_REQUEUE, FUTEX_CMP_REQUEUE, and FUTEX_WAKE_OP, the
5235            TIMEOUT parameter is interpreted as a uint32_t by the kernel.
5236            But the prototype takes a `struct timespec *'; insert casts
5237            to satisfy the compiler.  We do not need to tswap TIMEOUT
5238            since it's not compared to guest memory.  */
5239         pts = (struct timespec *)(uintptr_t) timeout;
5240         return get_errno(sys_futex(g2h(uaddr), op, val, pts,
5241                                    g2h(uaddr2),
5242                                    (base_op == FUTEX_CMP_REQUEUE
5243                                     ? tswap32(val3)
5244                                     : val3)));
5245     default:
5246         return -TARGET_ENOSYS;
5247     }
5248 }
5249 
5250 /* Map host to target signal numbers for the wait family of syscalls.
5251    Assume all other status bits are the same.  */
5252 int host_to_target_waitstatus(int status)
5253 {
5254     if (WIFSIGNALED(status)) {
5255         return host_to_target_signal(WTERMSIG(status)) | (status & ~0x7f);
5256     }
5257     if (WIFSTOPPED(status)) {
5258         return (host_to_target_signal(WSTOPSIG(status)) << 8)
5259                | (status & 0xff);
5260     }
5261     return status;
5262 }
5263 
5264 static int open_self_cmdline(void *cpu_env, int fd)
5265 {
5266     int fd_orig = -1;
5267     bool word_skipped = false;
5268 
5269     fd_orig = open("/proc/self/cmdline", O_RDONLY);
5270     if (fd_orig < 0) {
5271         return fd_orig;
5272     }
5273 
5274     while (true) {
5275         ssize_t nb_read;
5276         char buf[128];
5277         char *cp_buf = buf;
5278 
5279         nb_read = read(fd_orig, buf, sizeof(buf));
5280         if (nb_read < 0) {
5281             fd_orig = close(fd_orig);
5282             return -1;
5283         } else if (nb_read == 0) {
5284             break;
5285         }
5286 
5287         if (!word_skipped) {
5288             /* Skip the first string, which is the path to qemu-*-static
5289                instead of the actual command. */
5290             cp_buf = memchr(buf, 0, sizeof(buf));
5291             if (cp_buf) {
5292                 /* Null byte found, skip one string */
5293                 cp_buf++;
5294                 nb_read -= cp_buf - buf;
5295                 word_skipped = true;
5296             }
5297         }
5298 
5299         if (word_skipped) {
5300             if (write(fd, cp_buf, nb_read) != nb_read) {
5301                 close(fd_orig);
5302                 return -1;
5303             }
5304         }
5305     }
5306 
5307     return close(fd_orig);
5308 }
5309 
5310 static int open_self_maps(void *cpu_env, int fd)
5311 {
5312     CPUState *cpu = ENV_GET_CPU((CPUArchState *)cpu_env);
5313     TaskState *ts = cpu->opaque;
5314     FILE *fp;
5315     char *line = NULL;
5316     size_t len = 0;
5317     ssize_t read;
5318 
5319     fp = fopen("/proc/self/maps", "r");
5320     if (fp == NULL) {
5321         return -EACCES;
5322     }
5323 
5324     while ((read = getline(&line, &len, fp)) != -1) {
5325         int fields, dev_maj, dev_min, inode;
5326         uint64_t min, max, offset;
5327         char flag_r, flag_w, flag_x, flag_p;
5328         char path[512] = "";
5329         fields = sscanf(line, "%"PRIx64"-%"PRIx64" %c%c%c%c %"PRIx64" %x:%x %d"
5330                         " %512s", &min, &max, &flag_r, &flag_w, &flag_x,
5331                         &flag_p, &offset, &dev_maj, &dev_min, &inode, path);
5332 
5333         if ((fields < 10) || (fields > 11)) {
5334             continue;
5335         }
5336         if (h2g_valid(min)) {
5337             int flags = page_get_flags(h2g(min));
5338             max = h2g_valid(max - 1) ? max : (uintptr_t)g2h(GUEST_ADDR_MAX);
5339             if (page_check_range(h2g(min), max - min, flags) == -1) {
5340                 continue;
5341             }
5342             if (h2g(min) == ts->info->stack_limit) {
5343                 pstrcpy(path, sizeof(path), "      [stack]");
5344             }
5345             dprintf(fd, TARGET_ABI_FMT_lx "-" TARGET_ABI_FMT_lx
5346                     " %c%c%c%c %08" PRIx64 " %02x:%02x %d %s%s\n",
5347                     h2g(min), h2g(max - 1) + 1, flag_r, flag_w,
5348                     flag_x, flag_p, offset, dev_maj, dev_min, inode,
5349                     path[0] ? "         " : "", path);
5350         }
5351     }
5352 
5353     free(line);
5354     fclose(fp);
5355 
5356     return 0;
5357 }
5358 
5359 static int open_self_stat(void *cpu_env, int fd)
5360 {
5361     CPUState *cpu = ENV_GET_CPU((CPUArchState *)cpu_env);
5362     TaskState *ts = cpu->opaque;
5363     abi_ulong start_stack = ts->info->start_stack;
5364     int i;
5365 
5366     for (i = 0; i < 44; i++) {
5367       char buf[128];
5368       int len;
5369       uint64_t val = 0;
5370 
5371       if (i == 0) {
5372         /* pid */
5373         val = getpid();
5374         snprintf(buf, sizeof(buf), "%"PRId64 " ", val);
5375       } else if (i == 1) {
5376         /* app name */
5377         snprintf(buf, sizeof(buf), "(%s) ", ts->bprm->argv[0]);
5378       } else if (i == 27) {
5379         /* stack bottom */
5380         val = start_stack;
5381         snprintf(buf, sizeof(buf), "%"PRId64 " ", val);
5382       } else {
5383         /* for the rest, there is MasterCard */
5384         snprintf(buf, sizeof(buf), "0%c", i == 43 ? '\n' : ' ');
5385       }
5386 
5387       len = strlen(buf);
5388       if (write(fd, buf, len) != len) {
5389           return -1;
5390       }
5391     }
5392 
5393     return 0;
5394 }
5395 
5396 static int open_self_auxv(void *cpu_env, int fd)
5397 {
5398     CPUState *cpu = ENV_GET_CPU((CPUArchState *)cpu_env);
5399     TaskState *ts = cpu->opaque;
5400     abi_ulong auxv = ts->info->saved_auxv;
5401     abi_ulong len = ts->info->auxv_len;
5402     char *ptr;
5403 
5404     /*
5405      * Auxiliary vector is stored in target process stack.
5406      * read in whole auxv vector and copy it to file
5407      */
5408     ptr = lock_user(VERIFY_READ, auxv, len, 0);
5409     if (ptr != NULL) {
5410         while (len > 0) {
5411             ssize_t r;
5412             r = write(fd, ptr, len);
5413             if (r <= 0) {
5414                 break;
5415             }
5416             len -= r;
5417             ptr += r;
5418         }
5419         lseek(fd, 0, SEEK_SET);
5420         unlock_user(ptr, auxv, len);
5421     }
5422 
5423     return 0;
5424 }
5425 
5426 static int is_proc_myself(const char *filename, const char *entry)
5427 {
5428     if (!strncmp(filename, "/proc/", strlen("/proc/"))) {
5429         filename += strlen("/proc/");
5430         if (!strncmp(filename, "self/", strlen("self/"))) {
5431             filename += strlen("self/");
5432         } else if (*filename >= '1' && *filename <= '9') {
5433             char myself[80];
5434             snprintf(myself, sizeof(myself), "%d/", getpid());
5435             if (!strncmp(filename, myself, strlen(myself))) {
5436                 filename += strlen(myself);
5437             } else {
5438                 return 0;
5439             }
5440         } else {
5441             return 0;
5442         }
5443         if (!strcmp(filename, entry)) {
5444             return 1;
5445         }
5446     }
5447     return 0;
5448 }
5449 
5450 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
5451 static int is_proc(const char *filename, const char *entry)
5452 {
5453     return strcmp(filename, entry) == 0;
5454 }
5455 
5456 static int open_net_route(void *cpu_env, int fd)
5457 {
5458     FILE *fp;
5459     char *line = NULL;
5460     size_t len = 0;
5461     ssize_t read;
5462 
5463     fp = fopen("/proc/net/route", "r");
5464     if (fp == NULL) {
5465         return -EACCES;
5466     }
5467 
5468     /* read header */
5469 
5470     read = getline(&line, &len, fp);
5471     dprintf(fd, "%s", line);
5472 
5473     /* read routes */
5474 
5475     while ((read = getline(&line, &len, fp)) != -1) {
5476         char iface[16];
5477         uint32_t dest, gw, mask;
5478         unsigned int flags, refcnt, use, metric, mtu, window, irtt;
5479         sscanf(line, "%s\t%08x\t%08x\t%04x\t%d\t%d\t%d\t%08x\t%d\t%u\t%u\n",
5480                      iface, &dest, &gw, &flags, &refcnt, &use, &metric,
5481                      &mask, &mtu, &window, &irtt);
5482         dprintf(fd, "%s\t%08x\t%08x\t%04x\t%d\t%d\t%d\t%08x\t%d\t%u\t%u\n",
5483                 iface, tswap32(dest), tswap32(gw), flags, refcnt, use,
5484                 metric, tswap32(mask), mtu, window, irtt);
5485     }
5486 
5487     free(line);
5488     fclose(fp);
5489 
5490     return 0;
5491 }
5492 #endif
5493 
5494 static int do_openat(void *cpu_env, int dirfd, const char *pathname, int flags, mode_t mode)
5495 {
5496     struct fake_open {
5497         const char *filename;
5498         int (*fill)(void *cpu_env, int fd);
5499         int (*cmp)(const char *s1, const char *s2);
5500     };
5501     const struct fake_open *fake_open;
5502     static const struct fake_open fakes[] = {
5503         { "maps", open_self_maps, is_proc_myself },
5504         { "stat", open_self_stat, is_proc_myself },
5505         { "auxv", open_self_auxv, is_proc_myself },
5506         { "cmdline", open_self_cmdline, is_proc_myself },
5507 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
5508         { "/proc/net/route", open_net_route, is_proc },
5509 #endif
5510         { NULL, NULL, NULL }
5511     };
5512 
5513     if (is_proc_myself(pathname, "exe")) {
5514         int execfd = qemu_getauxval(AT_EXECFD);
5515         return execfd ? execfd : get_errno(sys_openat(dirfd, exec_path, flags, mode));
5516     }
5517 
5518     for (fake_open = fakes; fake_open->filename; fake_open++) {
5519         if (fake_open->cmp(pathname, fake_open->filename)) {
5520             break;
5521         }
5522     }
5523 
5524     if (fake_open->filename) {
5525         const char *tmpdir;
5526         char filename[PATH_MAX];
5527         int fd, r;
5528 
5529         /* create temporary file to map stat to */
5530         tmpdir = getenv("TMPDIR");
5531         if (!tmpdir)
5532             tmpdir = "/tmp";
5533         snprintf(filename, sizeof(filename), "%s/qemu-open.XXXXXX", tmpdir);
5534         fd = mkstemp(filename);
5535         if (fd < 0) {
5536             return fd;
5537         }
5538         unlink(filename);
5539 
5540         if ((r = fake_open->fill(cpu_env, fd))) {
5541             close(fd);
5542             return r;
5543         }
5544         lseek(fd, 0, SEEK_SET);
5545 
5546         return fd;
5547     }
5548 
5549     return get_errno(sys_openat(dirfd, path(pathname), flags, mode));
5550 }
5551 
5552 #define TIMER_MAGIC 0x0caf0000
5553 #define TIMER_MAGIC_MASK 0xffff0000
5554 
5555 /* Convert QEMU provided timer ID back to internal 16bit index format */
5556 static target_timer_t get_timer_id(abi_long arg)
5557 {
5558     target_timer_t timerid = arg;
5559 
5560     if ((timerid & TIMER_MAGIC_MASK) != TIMER_MAGIC) {
5561         return -TARGET_EINVAL;
5562     }
5563 
5564     timerid &= 0xffff;
5565 
5566     if (timerid >= ARRAY_SIZE(g_posix_timers)) {
5567         return -TARGET_EINVAL;
5568     }
5569 
5570     return timerid;
5571 }
5572 
5573 /* do_syscall() should always have a single exit point at the end so
5574    that actions, such as logging of syscall results, can be performed.
5575    All errnos that do_syscall() returns must be -TARGET_<errcode>. */
5576 abi_long do_syscall(void *cpu_env, int num, abi_long arg1,
5577                     abi_long arg2, abi_long arg3, abi_long arg4,
5578                     abi_long arg5, abi_long arg6, abi_long arg7,
5579                     abi_long arg8)
5580 {
5581     CPUState *cpu = ENV_GET_CPU(cpu_env);
5582     abi_long ret;
5583     struct stat st;
5584     struct statfs stfs;
5585     void *p;
5586 
5587 #ifdef DEBUG
5588     gemu_log("syscall %d", num);
5589 #endif
5590     if(do_strace)
5591         print_syscall(num, arg1, arg2, arg3, arg4, arg5, arg6);
5592 
5593     switch(num) {
5594     case TARGET_NR_exit:
5595         /* In old applications this may be used to implement _exit(2).
5596            However in threaded applictions it is used for thread termination,
5597            and _exit_group is used for application termination.
5598            Do thread termination if we have more then one thread.  */
5599         /* FIXME: This probably breaks if a signal arrives.  We should probably
5600            be disabling signals.  */
5601         if (CPU_NEXT(first_cpu)) {
5602             TaskState *ts;
5603 
5604             cpu_list_lock();
5605             /* Remove the CPU from the list.  */
5606             QTAILQ_REMOVE(&cpus, cpu, node);
5607             cpu_list_unlock();
5608             ts = cpu->opaque;
5609             if (ts->child_tidptr) {
5610                 put_user_u32(0, ts->child_tidptr);
5611                 sys_futex(g2h(ts->child_tidptr), FUTEX_WAKE, INT_MAX,
5612                           NULL, NULL, 0);
5613             }
5614             thread_cpu = NULL;
5615             object_unref(OBJECT(cpu));
5616             g_free(ts);
5617             rcu_unregister_thread();
5618             pthread_exit(NULL);
5619         }
5620 #ifdef TARGET_GPROF
5621         _mcleanup();
5622 #endif
5623         gdb_exit(cpu_env, arg1);
5624         _exit(arg1);
5625         ret = 0; /* avoid warning */
5626         break;
5627     case TARGET_NR_read:
5628         if (arg3 == 0)
5629             ret = 0;
5630         else {
5631             if (!(p = lock_user(VERIFY_WRITE, arg2, arg3, 0)))
5632                 goto efault;
5633             ret = get_errno(read(arg1, p, arg3));
5634             unlock_user(p, arg2, ret);
5635         }
5636         break;
5637     case TARGET_NR_write:
5638         if (!(p = lock_user(VERIFY_READ, arg2, arg3, 1)))
5639             goto efault;
5640         ret = get_errno(write(arg1, p, arg3));
5641         unlock_user(p, arg2, 0);
5642         break;
5643 #ifdef TARGET_NR_open
5644     case TARGET_NR_open:
5645         if (!(p = lock_user_string(arg1)))
5646             goto efault;
5647         ret = get_errno(do_openat(cpu_env, AT_FDCWD, p,
5648                                   target_to_host_bitmask(arg2, fcntl_flags_tbl),
5649                                   arg3));
5650         unlock_user(p, arg1, 0);
5651         break;
5652 #endif
5653     case TARGET_NR_openat:
5654         if (!(p = lock_user_string(arg2)))
5655             goto efault;
5656         ret = get_errno(do_openat(cpu_env, arg1, p,
5657                                   target_to_host_bitmask(arg3, fcntl_flags_tbl),
5658                                   arg4));
5659         unlock_user(p, arg2, 0);
5660         break;
5661     case TARGET_NR_close:
5662         ret = get_errno(close(arg1));
5663         break;
5664     case TARGET_NR_brk:
5665         ret = do_brk(arg1);
5666         break;
5667 #ifdef TARGET_NR_fork
5668     case TARGET_NR_fork:
5669         ret = get_errno(do_fork(cpu_env, SIGCHLD, 0, 0, 0, 0));
5670         break;
5671 #endif
5672 #ifdef TARGET_NR_waitpid
5673     case TARGET_NR_waitpid:
5674         {
5675             int status;
5676             ret = get_errno(waitpid(arg1, &status, arg3));
5677             if (!is_error(ret) && arg2 && ret
5678                 && put_user_s32(host_to_target_waitstatus(status), arg2))
5679                 goto efault;
5680         }
5681         break;
5682 #endif
5683 #ifdef TARGET_NR_waitid
5684     case TARGET_NR_waitid:
5685         {
5686             siginfo_t info;
5687             info.si_pid = 0;
5688             ret = get_errno(waitid(arg1, arg2, &info, arg4));
5689             if (!is_error(ret) && arg3 && info.si_pid != 0) {
5690                 if (!(p = lock_user(VERIFY_WRITE, arg3, sizeof(target_siginfo_t), 0)))
5691                     goto efault;
5692                 host_to_target_siginfo(p, &info);
5693                 unlock_user(p, arg3, sizeof(target_siginfo_t));
5694             }
5695         }
5696         break;
5697 #endif
5698 #ifdef TARGET_NR_creat /* not on alpha */
5699     case TARGET_NR_creat:
5700         if (!(p = lock_user_string(arg1)))
5701             goto efault;
5702         ret = get_errno(creat(p, arg2));
5703         unlock_user(p, arg1, 0);
5704         break;
5705 #endif
5706 #ifdef TARGET_NR_link
5707     case TARGET_NR_link:
5708         {
5709             void * p2;
5710             p = lock_user_string(arg1);
5711             p2 = lock_user_string(arg2);
5712             if (!p || !p2)
5713                 ret = -TARGET_EFAULT;
5714             else
5715                 ret = get_errno(link(p, p2));
5716             unlock_user(p2, arg2, 0);
5717             unlock_user(p, arg1, 0);
5718         }
5719         break;
5720 #endif
5721 #if defined(TARGET_NR_linkat)
5722     case TARGET_NR_linkat:
5723         {
5724             void * p2 = NULL;
5725             if (!arg2 || !arg4)
5726                 goto efault;
5727             p  = lock_user_string(arg2);
5728             p2 = lock_user_string(arg4);
5729             if (!p || !p2)
5730                 ret = -TARGET_EFAULT;
5731             else
5732                 ret = get_errno(linkat(arg1, p, arg3, p2, arg5));
5733             unlock_user(p, arg2, 0);
5734             unlock_user(p2, arg4, 0);
5735         }
5736         break;
5737 #endif
5738 #ifdef TARGET_NR_unlink
5739     case TARGET_NR_unlink:
5740         if (!(p = lock_user_string(arg1)))
5741             goto efault;
5742         ret = get_errno(unlink(p));
5743         unlock_user(p, arg1, 0);
5744         break;
5745 #endif
5746 #if defined(TARGET_NR_unlinkat)
5747     case TARGET_NR_unlinkat:
5748         if (!(p = lock_user_string(arg2)))
5749             goto efault;
5750         ret = get_errno(unlinkat(arg1, p, arg3));
5751         unlock_user(p, arg2, 0);
5752         break;
5753 #endif
5754     case TARGET_NR_execve:
5755         {
5756             char **argp, **envp;
5757             int argc, envc;
5758             abi_ulong gp;
5759             abi_ulong guest_argp;
5760             abi_ulong guest_envp;
5761             abi_ulong addr;
5762             char **q;
5763             int total_size = 0;
5764 
5765             argc = 0;
5766             guest_argp = arg2;
5767             for (gp = guest_argp; gp; gp += sizeof(abi_ulong)) {
5768                 if (get_user_ual(addr, gp))
5769                     goto efault;
5770                 if (!addr)
5771                     break;
5772                 argc++;
5773             }
5774             envc = 0;
5775             guest_envp = arg3;
5776             for (gp = guest_envp; gp; gp += sizeof(abi_ulong)) {
5777                 if (get_user_ual(addr, gp))
5778                     goto efault;
5779                 if (!addr)
5780                     break;
5781                 envc++;
5782             }
5783 
5784             argp = alloca((argc + 1) * sizeof(void *));
5785             envp = alloca((envc + 1) * sizeof(void *));
5786 
5787             for (gp = guest_argp, q = argp; gp;
5788                   gp += sizeof(abi_ulong), q++) {
5789                 if (get_user_ual(addr, gp))
5790                     goto execve_efault;
5791                 if (!addr)
5792                     break;
5793                 if (!(*q = lock_user_string(addr)))
5794                     goto execve_efault;
5795                 total_size += strlen(*q) + 1;
5796             }
5797             *q = NULL;
5798 
5799             for (gp = guest_envp, q = envp; gp;
5800                   gp += sizeof(abi_ulong), q++) {
5801                 if (get_user_ual(addr, gp))
5802                     goto execve_efault;
5803                 if (!addr)
5804                     break;
5805                 if (!(*q = lock_user_string(addr)))
5806                     goto execve_efault;
5807                 total_size += strlen(*q) + 1;
5808             }
5809             *q = NULL;
5810 
5811             /* This case will not be caught by the host's execve() if its
5812                page size is bigger than the target's. */
5813             if (total_size > MAX_ARG_PAGES * TARGET_PAGE_SIZE) {
5814                 ret = -TARGET_E2BIG;
5815                 goto execve_end;
5816             }
5817             if (!(p = lock_user_string(arg1)))
5818                 goto execve_efault;
5819             ret = get_errno(execve(p, argp, envp));
5820             unlock_user(p, arg1, 0);
5821 
5822             goto execve_end;
5823 
5824         execve_efault:
5825             ret = -TARGET_EFAULT;
5826 
5827         execve_end:
5828             for (gp = guest_argp, q = argp; *q;
5829                   gp += sizeof(abi_ulong), q++) {
5830                 if (get_user_ual(addr, gp)
5831                     || !addr)
5832                     break;
5833                 unlock_user(*q, addr, 0);
5834             }
5835             for (gp = guest_envp, q = envp; *q;
5836                   gp += sizeof(abi_ulong), q++) {
5837                 if (get_user_ual(addr, gp)
5838                     || !addr)
5839                     break;
5840                 unlock_user(*q, addr, 0);
5841             }
5842         }
5843         break;
5844     case TARGET_NR_chdir:
5845         if (!(p = lock_user_string(arg1)))
5846             goto efault;
5847         ret = get_errno(chdir(p));
5848         unlock_user(p, arg1, 0);
5849         break;
5850 #ifdef TARGET_NR_time
5851     case TARGET_NR_time:
5852         {
5853             time_t host_time;
5854             ret = get_errno(time(&host_time));
5855             if (!is_error(ret)
5856                 && arg1
5857                 && put_user_sal(host_time, arg1))
5858                 goto efault;
5859         }
5860         break;
5861 #endif
5862 #ifdef TARGET_NR_mknod
5863     case TARGET_NR_mknod:
5864         if (!(p = lock_user_string(arg1)))
5865             goto efault;
5866         ret = get_errno(mknod(p, arg2, arg3));
5867         unlock_user(p, arg1, 0);
5868         break;
5869 #endif
5870 #if defined(TARGET_NR_mknodat)
5871     case TARGET_NR_mknodat:
5872         if (!(p = lock_user_string(arg2)))
5873             goto efault;
5874         ret = get_errno(mknodat(arg1, p, arg3, arg4));
5875         unlock_user(p, arg2, 0);
5876         break;
5877 #endif
5878 #ifdef TARGET_NR_chmod
5879     case TARGET_NR_chmod:
5880         if (!(p = lock_user_string(arg1)))
5881             goto efault;
5882         ret = get_errno(chmod(p, arg2));
5883         unlock_user(p, arg1, 0);
5884         break;
5885 #endif
5886 #ifdef TARGET_NR_break
5887     case TARGET_NR_break:
5888         goto unimplemented;
5889 #endif
5890 #ifdef TARGET_NR_oldstat
5891     case TARGET_NR_oldstat:
5892         goto unimplemented;
5893 #endif
5894     case TARGET_NR_lseek:
5895         ret = get_errno(lseek(arg1, arg2, arg3));
5896         break;
5897 #if defined(TARGET_NR_getxpid) && defined(TARGET_ALPHA)
5898     /* Alpha specific */
5899     case TARGET_NR_getxpid:
5900         ((CPUAlphaState *)cpu_env)->ir[IR_A4] = getppid();
5901         ret = get_errno(getpid());
5902         break;
5903 #endif
5904 #ifdef TARGET_NR_getpid
5905     case TARGET_NR_getpid:
5906         ret = get_errno(getpid());
5907         break;
5908 #endif
5909     case TARGET_NR_mount:
5910         {
5911             /* need to look at the data field */
5912             void *p2, *p3;
5913 
5914             if (arg1) {
5915                 p = lock_user_string(arg1);
5916                 if (!p) {
5917                     goto efault;
5918                 }
5919             } else {
5920                 p = NULL;
5921             }
5922 
5923             p2 = lock_user_string(arg2);
5924             if (!p2) {
5925                 if (arg1) {
5926                     unlock_user(p, arg1, 0);
5927                 }
5928                 goto efault;
5929             }
5930 
5931             if (arg3) {
5932                 p3 = lock_user_string(arg3);
5933                 if (!p3) {
5934                     if (arg1) {
5935                         unlock_user(p, arg1, 0);
5936                     }
5937                     unlock_user(p2, arg2, 0);
5938                     goto efault;
5939                 }
5940             } else {
5941                 p3 = NULL;
5942             }
5943 
5944             /* FIXME - arg5 should be locked, but it isn't clear how to
5945              * do that since it's not guaranteed to be a NULL-terminated
5946              * string.
5947              */
5948             if (!arg5) {
5949                 ret = mount(p, p2, p3, (unsigned long)arg4, NULL);
5950             } else {
5951                 ret = mount(p, p2, p3, (unsigned long)arg4, g2h(arg5));
5952             }
5953             ret = get_errno(ret);
5954 
5955             if (arg1) {
5956                 unlock_user(p, arg1, 0);
5957             }
5958             unlock_user(p2, arg2, 0);
5959             if (arg3) {
5960                 unlock_user(p3, arg3, 0);
5961             }
5962         }
5963         break;
5964 #ifdef TARGET_NR_umount
5965     case TARGET_NR_umount:
5966         if (!(p = lock_user_string(arg1)))
5967             goto efault;
5968         ret = get_errno(umount(p));
5969         unlock_user(p, arg1, 0);
5970         break;
5971 #endif
5972 #ifdef TARGET_NR_stime /* not on alpha */
5973     case TARGET_NR_stime:
5974         {
5975             time_t host_time;
5976             if (get_user_sal(host_time, arg1))
5977                 goto efault;
5978             ret = get_errno(stime(&host_time));
5979         }
5980         break;
5981 #endif
5982     case TARGET_NR_ptrace:
5983         goto unimplemented;
5984 #ifdef TARGET_NR_alarm /* not on alpha */
5985     case TARGET_NR_alarm:
5986         ret = alarm(arg1);
5987         break;
5988 #endif
5989 #ifdef TARGET_NR_oldfstat
5990     case TARGET_NR_oldfstat:
5991         goto unimplemented;
5992 #endif
5993 #ifdef TARGET_NR_pause /* not on alpha */
5994     case TARGET_NR_pause:
5995         ret = get_errno(pause());
5996         break;
5997 #endif
5998 #ifdef TARGET_NR_utime
5999     case TARGET_NR_utime:
6000         {
6001             struct utimbuf tbuf, *host_tbuf;
6002             struct target_utimbuf *target_tbuf;
6003             if (arg2) {
6004                 if (!lock_user_struct(VERIFY_READ, target_tbuf, arg2, 1))
6005                     goto efault;
6006                 tbuf.actime = tswapal(target_tbuf->actime);
6007                 tbuf.modtime = tswapal(target_tbuf->modtime);
6008                 unlock_user_struct(target_tbuf, arg2, 0);
6009                 host_tbuf = &tbuf;
6010             } else {
6011                 host_tbuf = NULL;
6012             }
6013             if (!(p = lock_user_string(arg1)))
6014                 goto efault;
6015             ret = get_errno(utime(p, host_tbuf));
6016             unlock_user(p, arg1, 0);
6017         }
6018         break;
6019 #endif
6020 #ifdef TARGET_NR_utimes
6021     case TARGET_NR_utimes:
6022         {
6023             struct timeval *tvp, tv[2];
6024             if (arg2) {
6025                 if (copy_from_user_timeval(&tv[0], arg2)
6026                     || copy_from_user_timeval(&tv[1],
6027                                               arg2 + sizeof(struct target_timeval)))
6028                     goto efault;
6029                 tvp = tv;
6030             } else {
6031                 tvp = NULL;
6032             }
6033             if (!(p = lock_user_string(arg1)))
6034                 goto efault;
6035             ret = get_errno(utimes(p, tvp));
6036             unlock_user(p, arg1, 0);
6037         }
6038         break;
6039 #endif
6040 #if defined(TARGET_NR_futimesat)
6041     case TARGET_NR_futimesat:
6042         {
6043             struct timeval *tvp, tv[2];
6044             if (arg3) {
6045                 if (copy_from_user_timeval(&tv[0], arg3)
6046                     || copy_from_user_timeval(&tv[1],
6047                                               arg3 + sizeof(struct target_timeval)))
6048                     goto efault;
6049                 tvp = tv;
6050             } else {
6051                 tvp = NULL;
6052             }
6053             if (!(p = lock_user_string(arg2)))
6054                 goto efault;
6055             ret = get_errno(futimesat(arg1, path(p), tvp));
6056             unlock_user(p, arg2, 0);
6057         }
6058         break;
6059 #endif
6060 #ifdef TARGET_NR_stty
6061     case TARGET_NR_stty:
6062         goto unimplemented;
6063 #endif
6064 #ifdef TARGET_NR_gtty
6065     case TARGET_NR_gtty:
6066         goto unimplemented;
6067 #endif
6068 #ifdef TARGET_NR_access
6069     case TARGET_NR_access:
6070         if (!(p = lock_user_string(arg1)))
6071             goto efault;
6072         ret = get_errno(access(path(p), arg2));
6073         unlock_user(p, arg1, 0);
6074         break;
6075 #endif
6076 #if defined(TARGET_NR_faccessat) && defined(__NR_faccessat)
6077     case TARGET_NR_faccessat:
6078         if (!(p = lock_user_string(arg2)))
6079             goto efault;
6080         ret = get_errno(faccessat(arg1, p, arg3, 0));
6081         unlock_user(p, arg2, 0);
6082         break;
6083 #endif
6084 #ifdef TARGET_NR_nice /* not on alpha */
6085     case TARGET_NR_nice:
6086         ret = get_errno(nice(arg1));
6087         break;
6088 #endif
6089 #ifdef TARGET_NR_ftime
6090     case TARGET_NR_ftime:
6091         goto unimplemented;
6092 #endif
6093     case TARGET_NR_sync:
6094         sync();
6095         ret = 0;
6096         break;
6097     case TARGET_NR_kill:
6098         ret = get_errno(kill(arg1, target_to_host_signal(arg2)));
6099         break;
6100 #ifdef TARGET_NR_rename
6101     case TARGET_NR_rename:
6102         {
6103             void *p2;
6104             p = lock_user_string(arg1);
6105             p2 = lock_user_string(arg2);
6106             if (!p || !p2)
6107                 ret = -TARGET_EFAULT;
6108             else
6109                 ret = get_errno(rename(p, p2));
6110             unlock_user(p2, arg2, 0);
6111             unlock_user(p, arg1, 0);
6112         }
6113         break;
6114 #endif
6115 #if defined(TARGET_NR_renameat)
6116     case TARGET_NR_renameat:
6117         {
6118             void *p2;
6119             p  = lock_user_string(arg2);
6120             p2 = lock_user_string(arg4);
6121             if (!p || !p2)
6122                 ret = -TARGET_EFAULT;
6123             else
6124                 ret = get_errno(renameat(arg1, p, arg3, p2));
6125             unlock_user(p2, arg4, 0);
6126             unlock_user(p, arg2, 0);
6127         }
6128         break;
6129 #endif
6130 #ifdef TARGET_NR_mkdir
6131     case TARGET_NR_mkdir:
6132         if (!(p = lock_user_string(arg1)))
6133             goto efault;
6134         ret = get_errno(mkdir(p, arg2));
6135         unlock_user(p, arg1, 0);
6136         break;
6137 #endif
6138 #if defined(TARGET_NR_mkdirat)
6139     case TARGET_NR_mkdirat:
6140         if (!(p = lock_user_string(arg2)))
6141             goto efault;
6142         ret = get_errno(mkdirat(arg1, p, arg3));
6143         unlock_user(p, arg2, 0);
6144         break;
6145 #endif
6146 #ifdef TARGET_NR_rmdir
6147     case TARGET_NR_rmdir:
6148         if (!(p = lock_user_string(arg1)))
6149             goto efault;
6150         ret = get_errno(rmdir(p));
6151         unlock_user(p, arg1, 0);
6152         break;
6153 #endif
6154     case TARGET_NR_dup:
6155         ret = get_errno(dup(arg1));
6156         break;
6157 #ifdef TARGET_NR_pipe
6158     case TARGET_NR_pipe:
6159         ret = do_pipe(cpu_env, arg1, 0, 0);
6160         break;
6161 #endif
6162 #ifdef TARGET_NR_pipe2
6163     case TARGET_NR_pipe2:
6164         ret = do_pipe(cpu_env, arg1,
6165                       target_to_host_bitmask(arg2, fcntl_flags_tbl), 1);
6166         break;
6167 #endif
6168     case TARGET_NR_times:
6169         {
6170             struct target_tms *tmsp;
6171             struct tms tms;
6172             ret = get_errno(times(&tms));
6173             if (arg1) {
6174                 tmsp = lock_user(VERIFY_WRITE, arg1, sizeof(struct target_tms), 0);
6175                 if (!tmsp)
6176                     goto efault;
6177                 tmsp->tms_utime = tswapal(host_to_target_clock_t(tms.tms_utime));
6178                 tmsp->tms_stime = tswapal(host_to_target_clock_t(tms.tms_stime));
6179                 tmsp->tms_cutime = tswapal(host_to_target_clock_t(tms.tms_cutime));
6180                 tmsp->tms_cstime = tswapal(host_to_target_clock_t(tms.tms_cstime));
6181             }
6182             if (!is_error(ret))
6183                 ret = host_to_target_clock_t(ret);
6184         }
6185         break;
6186 #ifdef TARGET_NR_prof
6187     case TARGET_NR_prof:
6188         goto unimplemented;
6189 #endif
6190 #ifdef TARGET_NR_signal
6191     case TARGET_NR_signal:
6192         goto unimplemented;
6193 #endif
6194     case TARGET_NR_acct:
6195         if (arg1 == 0) {
6196             ret = get_errno(acct(NULL));
6197         } else {
6198             if (!(p = lock_user_string(arg1)))
6199                 goto efault;
6200             ret = get_errno(acct(path(p)));
6201             unlock_user(p, arg1, 0);
6202         }
6203         break;
6204 #ifdef TARGET_NR_umount2
6205     case TARGET_NR_umount2:
6206         if (!(p = lock_user_string(arg1)))
6207             goto efault;
6208         ret = get_errno(umount2(p, arg2));
6209         unlock_user(p, arg1, 0);
6210         break;
6211 #endif
6212 #ifdef TARGET_NR_lock
6213     case TARGET_NR_lock:
6214         goto unimplemented;
6215 #endif
6216     case TARGET_NR_ioctl:
6217         ret = do_ioctl(arg1, arg2, arg3);
6218         break;
6219     case TARGET_NR_fcntl:
6220         ret = do_fcntl(arg1, arg2, arg3);
6221         break;
6222 #ifdef TARGET_NR_mpx
6223     case TARGET_NR_mpx:
6224         goto unimplemented;
6225 #endif
6226     case TARGET_NR_setpgid:
6227         ret = get_errno(setpgid(arg1, arg2));
6228         break;
6229 #ifdef TARGET_NR_ulimit
6230     case TARGET_NR_ulimit:
6231         goto unimplemented;
6232 #endif
6233 #ifdef TARGET_NR_oldolduname
6234     case TARGET_NR_oldolduname:
6235         goto unimplemented;
6236 #endif
6237     case TARGET_NR_umask:
6238         ret = get_errno(umask(arg1));
6239         break;
6240     case TARGET_NR_chroot:
6241         if (!(p = lock_user_string(arg1)))
6242             goto efault;
6243         ret = get_errno(chroot(p));
6244         unlock_user(p, arg1, 0);
6245         break;
6246 #ifdef TARGET_NR_ustat
6247     case TARGET_NR_ustat:
6248         goto unimplemented;
6249 #endif
6250 #ifdef TARGET_NR_dup2
6251     case TARGET_NR_dup2:
6252         ret = get_errno(dup2(arg1, arg2));
6253         break;
6254 #endif
6255 #if defined(CONFIG_DUP3) && defined(TARGET_NR_dup3)
6256     case TARGET_NR_dup3:
6257         ret = get_errno(dup3(arg1, arg2, arg3));
6258         break;
6259 #endif
6260 #ifdef TARGET_NR_getppid /* not on alpha */
6261     case TARGET_NR_getppid:
6262         ret = get_errno(getppid());
6263         break;
6264 #endif
6265 #ifdef TARGET_NR_getpgrp
6266     case TARGET_NR_getpgrp:
6267         ret = get_errno(getpgrp());
6268         break;
6269 #endif
6270     case TARGET_NR_setsid:
6271         ret = get_errno(setsid());
6272         break;
6273 #ifdef TARGET_NR_sigaction
6274     case TARGET_NR_sigaction:
6275         {
6276 #if defined(TARGET_ALPHA)
6277             struct target_sigaction act, oact, *pact = 0;
6278             struct target_old_sigaction *old_act;
6279             if (arg2) {
6280                 if (!lock_user_struct(VERIFY_READ, old_act, arg2, 1))
6281                     goto efault;
6282                 act._sa_handler = old_act->_sa_handler;
6283                 target_siginitset(&act.sa_mask, old_act->sa_mask);
6284                 act.sa_flags = old_act->sa_flags;
6285                 act.sa_restorer = 0;
6286                 unlock_user_struct(old_act, arg2, 0);
6287                 pact = &act;
6288             }
6289             ret = get_errno(do_sigaction(arg1, pact, &oact));
6290             if (!is_error(ret) && arg3) {
6291                 if (!lock_user_struct(VERIFY_WRITE, old_act, arg3, 0))
6292                     goto efault;
6293                 old_act->_sa_handler = oact._sa_handler;
6294                 old_act->sa_mask = oact.sa_mask.sig[0];
6295                 old_act->sa_flags = oact.sa_flags;
6296                 unlock_user_struct(old_act, arg3, 1);
6297             }
6298 #elif defined(TARGET_MIPS)
6299 	    struct target_sigaction act, oact, *pact, *old_act;
6300 
6301 	    if (arg2) {
6302                 if (!lock_user_struct(VERIFY_READ, old_act, arg2, 1))
6303                     goto efault;
6304 		act._sa_handler = old_act->_sa_handler;
6305 		target_siginitset(&act.sa_mask, old_act->sa_mask.sig[0]);
6306 		act.sa_flags = old_act->sa_flags;
6307 		unlock_user_struct(old_act, arg2, 0);
6308 		pact = &act;
6309 	    } else {
6310 		pact = NULL;
6311 	    }
6312 
6313 	    ret = get_errno(do_sigaction(arg1, pact, &oact));
6314 
6315 	    if (!is_error(ret) && arg3) {
6316                 if (!lock_user_struct(VERIFY_WRITE, old_act, arg3, 0))
6317                     goto efault;
6318 		old_act->_sa_handler = oact._sa_handler;
6319 		old_act->sa_flags = oact.sa_flags;
6320 		old_act->sa_mask.sig[0] = oact.sa_mask.sig[0];
6321 		old_act->sa_mask.sig[1] = 0;
6322 		old_act->sa_mask.sig[2] = 0;
6323 		old_act->sa_mask.sig[3] = 0;
6324 		unlock_user_struct(old_act, arg3, 1);
6325 	    }
6326 #else
6327             struct target_old_sigaction *old_act;
6328             struct target_sigaction act, oact, *pact;
6329             if (arg2) {
6330                 if (!lock_user_struct(VERIFY_READ, old_act, arg2, 1))
6331                     goto efault;
6332                 act._sa_handler = old_act->_sa_handler;
6333                 target_siginitset(&act.sa_mask, old_act->sa_mask);
6334                 act.sa_flags = old_act->sa_flags;
6335                 act.sa_restorer = old_act->sa_restorer;
6336                 unlock_user_struct(old_act, arg2, 0);
6337                 pact = &act;
6338             } else {
6339                 pact = NULL;
6340             }
6341             ret = get_errno(do_sigaction(arg1, pact, &oact));
6342             if (!is_error(ret) && arg3) {
6343                 if (!lock_user_struct(VERIFY_WRITE, old_act, arg3, 0))
6344                     goto efault;
6345                 old_act->_sa_handler = oact._sa_handler;
6346                 old_act->sa_mask = oact.sa_mask.sig[0];
6347                 old_act->sa_flags = oact.sa_flags;
6348                 old_act->sa_restorer = oact.sa_restorer;
6349                 unlock_user_struct(old_act, arg3, 1);
6350             }
6351 #endif
6352         }
6353         break;
6354 #endif
6355     case TARGET_NR_rt_sigaction:
6356         {
6357 #if defined(TARGET_ALPHA)
6358             struct target_sigaction act, oact, *pact = 0;
6359             struct target_rt_sigaction *rt_act;
6360             /* ??? arg4 == sizeof(sigset_t).  */
6361             if (arg2) {
6362                 if (!lock_user_struct(VERIFY_READ, rt_act, arg2, 1))
6363                     goto efault;
6364                 act._sa_handler = rt_act->_sa_handler;
6365                 act.sa_mask = rt_act->sa_mask;
6366                 act.sa_flags = rt_act->sa_flags;
6367                 act.sa_restorer = arg5;
6368                 unlock_user_struct(rt_act, arg2, 0);
6369                 pact = &act;
6370             }
6371             ret = get_errno(do_sigaction(arg1, pact, &oact));
6372             if (!is_error(ret) && arg3) {
6373                 if (!lock_user_struct(VERIFY_WRITE, rt_act, arg3, 0))
6374                     goto efault;
6375                 rt_act->_sa_handler = oact._sa_handler;
6376                 rt_act->sa_mask = oact.sa_mask;
6377                 rt_act->sa_flags = oact.sa_flags;
6378                 unlock_user_struct(rt_act, arg3, 1);
6379             }
6380 #else
6381             struct target_sigaction *act;
6382             struct target_sigaction *oact;
6383 
6384             if (arg2) {
6385                 if (!lock_user_struct(VERIFY_READ, act, arg2, 1))
6386                     goto efault;
6387             } else
6388                 act = NULL;
6389             if (arg3) {
6390                 if (!lock_user_struct(VERIFY_WRITE, oact, arg3, 0)) {
6391                     ret = -TARGET_EFAULT;
6392                     goto rt_sigaction_fail;
6393                 }
6394             } else
6395                 oact = NULL;
6396             ret = get_errno(do_sigaction(arg1, act, oact));
6397 	rt_sigaction_fail:
6398             if (act)
6399                 unlock_user_struct(act, arg2, 0);
6400             if (oact)
6401                 unlock_user_struct(oact, arg3, 1);
6402 #endif
6403         }
6404         break;
6405 #ifdef TARGET_NR_sgetmask /* not on alpha */
6406     case TARGET_NR_sgetmask:
6407         {
6408             sigset_t cur_set;
6409             abi_ulong target_set;
6410             do_sigprocmask(0, NULL, &cur_set);
6411             host_to_target_old_sigset(&target_set, &cur_set);
6412             ret = target_set;
6413         }
6414         break;
6415 #endif
6416 #ifdef TARGET_NR_ssetmask /* not on alpha */
6417     case TARGET_NR_ssetmask:
6418         {
6419             sigset_t set, oset, cur_set;
6420             abi_ulong target_set = arg1;
6421             do_sigprocmask(0, NULL, &cur_set);
6422             target_to_host_old_sigset(&set, &target_set);
6423             sigorset(&set, &set, &cur_set);
6424             do_sigprocmask(SIG_SETMASK, &set, &oset);
6425             host_to_target_old_sigset(&target_set, &oset);
6426             ret = target_set;
6427         }
6428         break;
6429 #endif
6430 #ifdef TARGET_NR_sigprocmask
6431     case TARGET_NR_sigprocmask:
6432         {
6433 #if defined(TARGET_ALPHA)
6434             sigset_t set, oldset;
6435             abi_ulong mask;
6436             int how;
6437 
6438             switch (arg1) {
6439             case TARGET_SIG_BLOCK:
6440                 how = SIG_BLOCK;
6441                 break;
6442             case TARGET_SIG_UNBLOCK:
6443                 how = SIG_UNBLOCK;
6444                 break;
6445             case TARGET_SIG_SETMASK:
6446                 how = SIG_SETMASK;
6447                 break;
6448             default:
6449                 ret = -TARGET_EINVAL;
6450                 goto fail;
6451             }
6452             mask = arg2;
6453             target_to_host_old_sigset(&set, &mask);
6454 
6455             ret = get_errno(do_sigprocmask(how, &set, &oldset));
6456             if (!is_error(ret)) {
6457                 host_to_target_old_sigset(&mask, &oldset);
6458                 ret = mask;
6459                 ((CPUAlphaState *)cpu_env)->ir[IR_V0] = 0; /* force no error */
6460             }
6461 #else
6462             sigset_t set, oldset, *set_ptr;
6463             int how;
6464 
6465             if (arg2) {
6466                 switch (arg1) {
6467                 case TARGET_SIG_BLOCK:
6468                     how = SIG_BLOCK;
6469                     break;
6470                 case TARGET_SIG_UNBLOCK:
6471                     how = SIG_UNBLOCK;
6472                     break;
6473                 case TARGET_SIG_SETMASK:
6474                     how = SIG_SETMASK;
6475                     break;
6476                 default:
6477                     ret = -TARGET_EINVAL;
6478                     goto fail;
6479                 }
6480                 if (!(p = lock_user(VERIFY_READ, arg2, sizeof(target_sigset_t), 1)))
6481                     goto efault;
6482                 target_to_host_old_sigset(&set, p);
6483                 unlock_user(p, arg2, 0);
6484                 set_ptr = &set;
6485             } else {
6486                 how = 0;
6487                 set_ptr = NULL;
6488             }
6489             ret = get_errno(do_sigprocmask(how, set_ptr, &oldset));
6490             if (!is_error(ret) && arg3) {
6491                 if (!(p = lock_user(VERIFY_WRITE, arg3, sizeof(target_sigset_t), 0)))
6492                     goto efault;
6493                 host_to_target_old_sigset(p, &oldset);
6494                 unlock_user(p, arg3, sizeof(target_sigset_t));
6495             }
6496 #endif
6497         }
6498         break;
6499 #endif
6500     case TARGET_NR_rt_sigprocmask:
6501         {
6502             int how = arg1;
6503             sigset_t set, oldset, *set_ptr;
6504 
6505             if (arg2) {
6506                 switch(how) {
6507                 case TARGET_SIG_BLOCK:
6508                     how = SIG_BLOCK;
6509                     break;
6510                 case TARGET_SIG_UNBLOCK:
6511                     how = SIG_UNBLOCK;
6512                     break;
6513                 case TARGET_SIG_SETMASK:
6514                     how = SIG_SETMASK;
6515                     break;
6516                 default:
6517                     ret = -TARGET_EINVAL;
6518                     goto fail;
6519                 }
6520                 if (!(p = lock_user(VERIFY_READ, arg2, sizeof(target_sigset_t), 1)))
6521                     goto efault;
6522                 target_to_host_sigset(&set, p);
6523                 unlock_user(p, arg2, 0);
6524                 set_ptr = &set;
6525             } else {
6526                 how = 0;
6527                 set_ptr = NULL;
6528             }
6529             ret = get_errno(do_sigprocmask(how, set_ptr, &oldset));
6530             if (!is_error(ret) && arg3) {
6531                 if (!(p = lock_user(VERIFY_WRITE, arg3, sizeof(target_sigset_t), 0)))
6532                     goto efault;
6533                 host_to_target_sigset(p, &oldset);
6534                 unlock_user(p, arg3, sizeof(target_sigset_t));
6535             }
6536         }
6537         break;
6538 #ifdef TARGET_NR_sigpending
6539     case TARGET_NR_sigpending:
6540         {
6541             sigset_t set;
6542             ret = get_errno(sigpending(&set));
6543             if (!is_error(ret)) {
6544                 if (!(p = lock_user(VERIFY_WRITE, arg1, sizeof(target_sigset_t), 0)))
6545                     goto efault;
6546                 host_to_target_old_sigset(p, &set);
6547                 unlock_user(p, arg1, sizeof(target_sigset_t));
6548             }
6549         }
6550         break;
6551 #endif
6552     case TARGET_NR_rt_sigpending:
6553         {
6554             sigset_t set;
6555             ret = get_errno(sigpending(&set));
6556             if (!is_error(ret)) {
6557                 if (!(p = lock_user(VERIFY_WRITE, arg1, sizeof(target_sigset_t), 0)))
6558                     goto efault;
6559                 host_to_target_sigset(p, &set);
6560                 unlock_user(p, arg1, sizeof(target_sigset_t));
6561             }
6562         }
6563         break;
6564 #ifdef TARGET_NR_sigsuspend
6565     case TARGET_NR_sigsuspend:
6566         {
6567             sigset_t set;
6568 #if defined(TARGET_ALPHA)
6569             abi_ulong mask = arg1;
6570             target_to_host_old_sigset(&set, &mask);
6571 #else
6572             if (!(p = lock_user(VERIFY_READ, arg1, sizeof(target_sigset_t), 1)))
6573                 goto efault;
6574             target_to_host_old_sigset(&set, p);
6575             unlock_user(p, arg1, 0);
6576 #endif
6577             ret = get_errno(sigsuspend(&set));
6578         }
6579         break;
6580 #endif
6581     case TARGET_NR_rt_sigsuspend:
6582         {
6583             sigset_t set;
6584             if (!(p = lock_user(VERIFY_READ, arg1, sizeof(target_sigset_t), 1)))
6585                 goto efault;
6586             target_to_host_sigset(&set, p);
6587             unlock_user(p, arg1, 0);
6588             ret = get_errno(sigsuspend(&set));
6589         }
6590         break;
6591     case TARGET_NR_rt_sigtimedwait:
6592         {
6593             sigset_t set;
6594             struct timespec uts, *puts;
6595             siginfo_t uinfo;
6596 
6597             if (!(p = lock_user(VERIFY_READ, arg1, sizeof(target_sigset_t), 1)))
6598                 goto efault;
6599             target_to_host_sigset(&set, p);
6600             unlock_user(p, arg1, 0);
6601             if (arg3) {
6602                 puts = &uts;
6603                 target_to_host_timespec(puts, arg3);
6604             } else {
6605                 puts = NULL;
6606             }
6607             ret = get_errno(sigtimedwait(&set, &uinfo, puts));
6608             if (!is_error(ret)) {
6609                 if (arg2) {
6610                     p = lock_user(VERIFY_WRITE, arg2, sizeof(target_siginfo_t),
6611                                   0);
6612                     if (!p) {
6613                         goto efault;
6614                     }
6615                     host_to_target_siginfo(p, &uinfo);
6616                     unlock_user(p, arg2, sizeof(target_siginfo_t));
6617                 }
6618                 ret = host_to_target_signal(ret);
6619             }
6620         }
6621         break;
6622     case TARGET_NR_rt_sigqueueinfo:
6623         {
6624             siginfo_t uinfo;
6625             if (!(p = lock_user(VERIFY_READ, arg3, sizeof(target_sigset_t), 1)))
6626                 goto efault;
6627             target_to_host_siginfo(&uinfo, p);
6628             unlock_user(p, arg1, 0);
6629             ret = get_errno(sys_rt_sigqueueinfo(arg1, arg2, &uinfo));
6630         }
6631         break;
6632 #ifdef TARGET_NR_sigreturn
6633     case TARGET_NR_sigreturn:
6634         /* NOTE: ret is eax, so not transcoding must be done */
6635         ret = do_sigreturn(cpu_env);
6636         break;
6637 #endif
6638     case TARGET_NR_rt_sigreturn:
6639         /* NOTE: ret is eax, so not transcoding must be done */
6640         ret = do_rt_sigreturn(cpu_env);
6641         break;
6642     case TARGET_NR_sethostname:
6643         if (!(p = lock_user_string(arg1)))
6644             goto efault;
6645         ret = get_errno(sethostname(p, arg2));
6646         unlock_user(p, arg1, 0);
6647         break;
6648     case TARGET_NR_setrlimit:
6649         {
6650             int resource = target_to_host_resource(arg1);
6651             struct target_rlimit *target_rlim;
6652             struct rlimit rlim;
6653             if (!lock_user_struct(VERIFY_READ, target_rlim, arg2, 1))
6654                 goto efault;
6655             rlim.rlim_cur = target_to_host_rlim(target_rlim->rlim_cur);
6656             rlim.rlim_max = target_to_host_rlim(target_rlim->rlim_max);
6657             unlock_user_struct(target_rlim, arg2, 0);
6658             ret = get_errno(setrlimit(resource, &rlim));
6659         }
6660         break;
6661     case TARGET_NR_getrlimit:
6662         {
6663             int resource = target_to_host_resource(arg1);
6664             struct target_rlimit *target_rlim;
6665             struct rlimit rlim;
6666 
6667             ret = get_errno(getrlimit(resource, &rlim));
6668             if (!is_error(ret)) {
6669                 if (!lock_user_struct(VERIFY_WRITE, target_rlim, arg2, 0))
6670                     goto efault;
6671                 target_rlim->rlim_cur = host_to_target_rlim(rlim.rlim_cur);
6672                 target_rlim->rlim_max = host_to_target_rlim(rlim.rlim_max);
6673                 unlock_user_struct(target_rlim, arg2, 1);
6674             }
6675         }
6676         break;
6677     case TARGET_NR_getrusage:
6678         {
6679             struct rusage rusage;
6680             ret = get_errno(getrusage(arg1, &rusage));
6681             if (!is_error(ret)) {
6682                 ret = host_to_target_rusage(arg2, &rusage);
6683             }
6684         }
6685         break;
6686     case TARGET_NR_gettimeofday:
6687         {
6688             struct timeval tv;
6689             ret = get_errno(gettimeofday(&tv, NULL));
6690             if (!is_error(ret)) {
6691                 if (copy_to_user_timeval(arg1, &tv))
6692                     goto efault;
6693             }
6694         }
6695         break;
6696     case TARGET_NR_settimeofday:
6697         {
6698             struct timeval tv, *ptv = NULL;
6699             struct timezone tz, *ptz = NULL;
6700 
6701             if (arg1) {
6702                 if (copy_from_user_timeval(&tv, arg1)) {
6703                     goto efault;
6704                 }
6705                 ptv = &tv;
6706             }
6707 
6708             if (arg2) {
6709                 if (copy_from_user_timezone(&tz, arg2)) {
6710                     goto efault;
6711                 }
6712                 ptz = &tz;
6713             }
6714 
6715             ret = get_errno(settimeofday(ptv, ptz));
6716         }
6717         break;
6718 #if defined(TARGET_NR_select)
6719     case TARGET_NR_select:
6720 #if defined(TARGET_S390X) || defined(TARGET_ALPHA)
6721         ret = do_select(arg1, arg2, arg3, arg4, arg5);
6722 #else
6723         {
6724             struct target_sel_arg_struct *sel;
6725             abi_ulong inp, outp, exp, tvp;
6726             long nsel;
6727 
6728             if (!lock_user_struct(VERIFY_READ, sel, arg1, 1))
6729                 goto efault;
6730             nsel = tswapal(sel->n);
6731             inp = tswapal(sel->inp);
6732             outp = tswapal(sel->outp);
6733             exp = tswapal(sel->exp);
6734             tvp = tswapal(sel->tvp);
6735             unlock_user_struct(sel, arg1, 0);
6736             ret = do_select(nsel, inp, outp, exp, tvp);
6737         }
6738 #endif
6739         break;
6740 #endif
6741 #ifdef TARGET_NR_pselect6
6742     case TARGET_NR_pselect6:
6743         {
6744             abi_long rfd_addr, wfd_addr, efd_addr, n, ts_addr;
6745             fd_set rfds, wfds, efds;
6746             fd_set *rfds_ptr, *wfds_ptr, *efds_ptr;
6747             struct timespec ts, *ts_ptr;
6748 
6749             /*
6750              * The 6th arg is actually two args smashed together,
6751              * so we cannot use the C library.
6752              */
6753             sigset_t set;
6754             struct {
6755                 sigset_t *set;
6756                 size_t size;
6757             } sig, *sig_ptr;
6758 
6759             abi_ulong arg_sigset, arg_sigsize, *arg7;
6760             target_sigset_t *target_sigset;
6761 
6762             n = arg1;
6763             rfd_addr = arg2;
6764             wfd_addr = arg3;
6765             efd_addr = arg4;
6766             ts_addr = arg5;
6767 
6768             ret = copy_from_user_fdset_ptr(&rfds, &rfds_ptr, rfd_addr, n);
6769             if (ret) {
6770                 goto fail;
6771             }
6772             ret = copy_from_user_fdset_ptr(&wfds, &wfds_ptr, wfd_addr, n);
6773             if (ret) {
6774                 goto fail;
6775             }
6776             ret = copy_from_user_fdset_ptr(&efds, &efds_ptr, efd_addr, n);
6777             if (ret) {
6778                 goto fail;
6779             }
6780 
6781             /*
6782              * This takes a timespec, and not a timeval, so we cannot
6783              * use the do_select() helper ...
6784              */
6785             if (ts_addr) {
6786                 if (target_to_host_timespec(&ts, ts_addr)) {
6787                     goto efault;
6788                 }
6789                 ts_ptr = &ts;
6790             } else {
6791                 ts_ptr = NULL;
6792             }
6793 
6794             /* Extract the two packed args for the sigset */
6795             if (arg6) {
6796                 sig_ptr = &sig;
6797                 sig.size = _NSIG / 8;
6798 
6799                 arg7 = lock_user(VERIFY_READ, arg6, sizeof(*arg7) * 2, 1);
6800                 if (!arg7) {
6801                     goto efault;
6802                 }
6803                 arg_sigset = tswapal(arg7[0]);
6804                 arg_sigsize = tswapal(arg7[1]);
6805                 unlock_user(arg7, arg6, 0);
6806 
6807                 if (arg_sigset) {
6808                     sig.set = &set;
6809                     if (arg_sigsize != sizeof(*target_sigset)) {
6810                         /* Like the kernel, we enforce correct size sigsets */
6811                         ret = -TARGET_EINVAL;
6812                         goto fail;
6813                     }
6814                     target_sigset = lock_user(VERIFY_READ, arg_sigset,
6815                                               sizeof(*target_sigset), 1);
6816                     if (!target_sigset) {
6817                         goto efault;
6818                     }
6819                     target_to_host_sigset(&set, target_sigset);
6820                     unlock_user(target_sigset, arg_sigset, 0);
6821                 } else {
6822                     sig.set = NULL;
6823                 }
6824             } else {
6825                 sig_ptr = NULL;
6826             }
6827 
6828             ret = get_errno(sys_pselect6(n, rfds_ptr, wfds_ptr, efds_ptr,
6829                                          ts_ptr, sig_ptr));
6830 
6831             if (!is_error(ret)) {
6832                 if (rfd_addr && copy_to_user_fdset(rfd_addr, &rfds, n))
6833                     goto efault;
6834                 if (wfd_addr && copy_to_user_fdset(wfd_addr, &wfds, n))
6835                     goto efault;
6836                 if (efd_addr && copy_to_user_fdset(efd_addr, &efds, n))
6837                     goto efault;
6838 
6839                 if (ts_addr && host_to_target_timespec(ts_addr, &ts))
6840                     goto efault;
6841             }
6842         }
6843         break;
6844 #endif
6845 #ifdef TARGET_NR_symlink
6846     case TARGET_NR_symlink:
6847         {
6848             void *p2;
6849             p = lock_user_string(arg1);
6850             p2 = lock_user_string(arg2);
6851             if (!p || !p2)
6852                 ret = -TARGET_EFAULT;
6853             else
6854                 ret = get_errno(symlink(p, p2));
6855             unlock_user(p2, arg2, 0);
6856             unlock_user(p, arg1, 0);
6857         }
6858         break;
6859 #endif
6860 #if defined(TARGET_NR_symlinkat)
6861     case TARGET_NR_symlinkat:
6862         {
6863             void *p2;
6864             p  = lock_user_string(arg1);
6865             p2 = lock_user_string(arg3);
6866             if (!p || !p2)
6867                 ret = -TARGET_EFAULT;
6868             else
6869                 ret = get_errno(symlinkat(p, arg2, p2));
6870             unlock_user(p2, arg3, 0);
6871             unlock_user(p, arg1, 0);
6872         }
6873         break;
6874 #endif
6875 #ifdef TARGET_NR_oldlstat
6876     case TARGET_NR_oldlstat:
6877         goto unimplemented;
6878 #endif
6879 #ifdef TARGET_NR_readlink
6880     case TARGET_NR_readlink:
6881         {
6882             void *p2;
6883             p = lock_user_string(arg1);
6884             p2 = lock_user(VERIFY_WRITE, arg2, arg3, 0);
6885             if (!p || !p2) {
6886                 ret = -TARGET_EFAULT;
6887             } else if (!arg3) {
6888                 /* Short circuit this for the magic exe check. */
6889                 ret = -TARGET_EINVAL;
6890             } else if (is_proc_myself((const char *)p, "exe")) {
6891                 char real[PATH_MAX], *temp;
6892                 temp = realpath(exec_path, real);
6893                 /* Return value is # of bytes that we wrote to the buffer. */
6894                 if (temp == NULL) {
6895                     ret = get_errno(-1);
6896                 } else {
6897                     /* Don't worry about sign mismatch as earlier mapping
6898                      * logic would have thrown a bad address error. */
6899                     ret = MIN(strlen(real), arg3);
6900                     /* We cannot NUL terminate the string. */
6901                     memcpy(p2, real, ret);
6902                 }
6903             } else {
6904                 ret = get_errno(readlink(path(p), p2, arg3));
6905             }
6906             unlock_user(p2, arg2, ret);
6907             unlock_user(p, arg1, 0);
6908         }
6909         break;
6910 #endif
6911 #if defined(TARGET_NR_readlinkat)
6912     case TARGET_NR_readlinkat:
6913         {
6914             void *p2;
6915             p  = lock_user_string(arg2);
6916             p2 = lock_user(VERIFY_WRITE, arg3, arg4, 0);
6917             if (!p || !p2) {
6918                 ret = -TARGET_EFAULT;
6919             } else if (is_proc_myself((const char *)p, "exe")) {
6920                 char real[PATH_MAX], *temp;
6921                 temp = realpath(exec_path, real);
6922                 ret = temp == NULL ? get_errno(-1) : strlen(real) ;
6923                 snprintf((char *)p2, arg4, "%s", real);
6924             } else {
6925                 ret = get_errno(readlinkat(arg1, path(p), p2, arg4));
6926             }
6927             unlock_user(p2, arg3, ret);
6928             unlock_user(p, arg2, 0);
6929         }
6930         break;
6931 #endif
6932 #ifdef TARGET_NR_uselib
6933     case TARGET_NR_uselib:
6934         goto unimplemented;
6935 #endif
6936 #ifdef TARGET_NR_swapon
6937     case TARGET_NR_swapon:
6938         if (!(p = lock_user_string(arg1)))
6939             goto efault;
6940         ret = get_errno(swapon(p, arg2));
6941         unlock_user(p, arg1, 0);
6942         break;
6943 #endif
6944     case TARGET_NR_reboot:
6945         if (arg3 == LINUX_REBOOT_CMD_RESTART2) {
6946            /* arg4 must be ignored in all other cases */
6947            p = lock_user_string(arg4);
6948            if (!p) {
6949               goto efault;
6950            }
6951            ret = get_errno(reboot(arg1, arg2, arg3, p));
6952            unlock_user(p, arg4, 0);
6953         } else {
6954            ret = get_errno(reboot(arg1, arg2, arg3, NULL));
6955         }
6956         break;
6957 #ifdef TARGET_NR_readdir
6958     case TARGET_NR_readdir:
6959         goto unimplemented;
6960 #endif
6961 #ifdef TARGET_NR_mmap
6962     case TARGET_NR_mmap:
6963 #if (defined(TARGET_I386) && defined(TARGET_ABI32)) || \
6964     (defined(TARGET_ARM) && defined(TARGET_ABI32)) || \
6965     defined(TARGET_M68K) || defined(TARGET_CRIS) || defined(TARGET_MICROBLAZE) \
6966     || defined(TARGET_S390X)
6967         {
6968             abi_ulong *v;
6969             abi_ulong v1, v2, v3, v4, v5, v6;
6970             if (!(v = lock_user(VERIFY_READ, arg1, 6 * sizeof(abi_ulong), 1)))
6971                 goto efault;
6972             v1 = tswapal(v[0]);
6973             v2 = tswapal(v[1]);
6974             v3 = tswapal(v[2]);
6975             v4 = tswapal(v[3]);
6976             v5 = tswapal(v[4]);
6977             v6 = tswapal(v[5]);
6978             unlock_user(v, arg1, 0);
6979             ret = get_errno(target_mmap(v1, v2, v3,
6980                                         target_to_host_bitmask(v4, mmap_flags_tbl),
6981                                         v5, v6));
6982         }
6983 #else
6984         ret = get_errno(target_mmap(arg1, arg2, arg3,
6985                                     target_to_host_bitmask(arg4, mmap_flags_tbl),
6986                                     arg5,
6987                                     arg6));
6988 #endif
6989         break;
6990 #endif
6991 #ifdef TARGET_NR_mmap2
6992     case TARGET_NR_mmap2:
6993 #ifndef MMAP_SHIFT
6994 #define MMAP_SHIFT 12
6995 #endif
6996         ret = get_errno(target_mmap(arg1, arg2, arg3,
6997                                     target_to_host_bitmask(arg4, mmap_flags_tbl),
6998                                     arg5,
6999                                     arg6 << MMAP_SHIFT));
7000         break;
7001 #endif
7002     case TARGET_NR_munmap:
7003         ret = get_errno(target_munmap(arg1, arg2));
7004         break;
7005     case TARGET_NR_mprotect:
7006         {
7007             TaskState *ts = cpu->opaque;
7008             /* Special hack to detect libc making the stack executable.  */
7009             if ((arg3 & PROT_GROWSDOWN)
7010                 && arg1 >= ts->info->stack_limit
7011                 && arg1 <= ts->info->start_stack) {
7012                 arg3 &= ~PROT_GROWSDOWN;
7013                 arg2 = arg2 + arg1 - ts->info->stack_limit;
7014                 arg1 = ts->info->stack_limit;
7015             }
7016         }
7017         ret = get_errno(target_mprotect(arg1, arg2, arg3));
7018         break;
7019 #ifdef TARGET_NR_mremap
7020     case TARGET_NR_mremap:
7021         ret = get_errno(target_mremap(arg1, arg2, arg3, arg4, arg5));
7022         break;
7023 #endif
7024         /* ??? msync/mlock/munlock are broken for softmmu.  */
7025 #ifdef TARGET_NR_msync
7026     case TARGET_NR_msync:
7027         ret = get_errno(msync(g2h(arg1), arg2, arg3));
7028         break;
7029 #endif
7030 #ifdef TARGET_NR_mlock
7031     case TARGET_NR_mlock:
7032         ret = get_errno(mlock(g2h(arg1), arg2));
7033         break;
7034 #endif
7035 #ifdef TARGET_NR_munlock
7036     case TARGET_NR_munlock:
7037         ret = get_errno(munlock(g2h(arg1), arg2));
7038         break;
7039 #endif
7040 #ifdef TARGET_NR_mlockall
7041     case TARGET_NR_mlockall:
7042         ret = get_errno(mlockall(target_to_host_mlockall_arg(arg1)));
7043         break;
7044 #endif
7045 #ifdef TARGET_NR_munlockall
7046     case TARGET_NR_munlockall:
7047         ret = get_errno(munlockall());
7048         break;
7049 #endif
7050     case TARGET_NR_truncate:
7051         if (!(p = lock_user_string(arg1)))
7052             goto efault;
7053         ret = get_errno(truncate(p, arg2));
7054         unlock_user(p, arg1, 0);
7055         break;
7056     case TARGET_NR_ftruncate:
7057         ret = get_errno(ftruncate(arg1, arg2));
7058         break;
7059     case TARGET_NR_fchmod:
7060         ret = get_errno(fchmod(arg1, arg2));
7061         break;
7062 #if defined(TARGET_NR_fchmodat)
7063     case TARGET_NR_fchmodat:
7064         if (!(p = lock_user_string(arg2)))
7065             goto efault;
7066         ret = get_errno(fchmodat(arg1, p, arg3, 0));
7067         unlock_user(p, arg2, 0);
7068         break;
7069 #endif
7070     case TARGET_NR_getpriority:
7071         /* Note that negative values are valid for getpriority, so we must
7072            differentiate based on errno settings.  */
7073         errno = 0;
7074         ret = getpriority(arg1, arg2);
7075         if (ret == -1 && errno != 0) {
7076             ret = -host_to_target_errno(errno);
7077             break;
7078         }
7079 #ifdef TARGET_ALPHA
7080         /* Return value is the unbiased priority.  Signal no error.  */
7081         ((CPUAlphaState *)cpu_env)->ir[IR_V0] = 0;
7082 #else
7083         /* Return value is a biased priority to avoid negative numbers.  */
7084         ret = 20 - ret;
7085 #endif
7086         break;
7087     case TARGET_NR_setpriority:
7088         ret = get_errno(setpriority(arg1, arg2, arg3));
7089         break;
7090 #ifdef TARGET_NR_profil
7091     case TARGET_NR_profil:
7092         goto unimplemented;
7093 #endif
7094     case TARGET_NR_statfs:
7095         if (!(p = lock_user_string(arg1)))
7096             goto efault;
7097         ret = get_errno(statfs(path(p), &stfs));
7098         unlock_user(p, arg1, 0);
7099     convert_statfs:
7100         if (!is_error(ret)) {
7101             struct target_statfs *target_stfs;
7102 
7103             if (!lock_user_struct(VERIFY_WRITE, target_stfs, arg2, 0))
7104                 goto efault;
7105             __put_user(stfs.f_type, &target_stfs->f_type);
7106             __put_user(stfs.f_bsize, &target_stfs->f_bsize);
7107             __put_user(stfs.f_blocks, &target_stfs->f_blocks);
7108             __put_user(stfs.f_bfree, &target_stfs->f_bfree);
7109             __put_user(stfs.f_bavail, &target_stfs->f_bavail);
7110             __put_user(stfs.f_files, &target_stfs->f_files);
7111             __put_user(stfs.f_ffree, &target_stfs->f_ffree);
7112             __put_user(stfs.f_fsid.__val[0], &target_stfs->f_fsid.val[0]);
7113             __put_user(stfs.f_fsid.__val[1], &target_stfs->f_fsid.val[1]);
7114             __put_user(stfs.f_namelen, &target_stfs->f_namelen);
7115             __put_user(stfs.f_frsize, &target_stfs->f_frsize);
7116             memset(target_stfs->f_spare, 0, sizeof(target_stfs->f_spare));
7117             unlock_user_struct(target_stfs, arg2, 1);
7118         }
7119         break;
7120     case TARGET_NR_fstatfs:
7121         ret = get_errno(fstatfs(arg1, &stfs));
7122         goto convert_statfs;
7123 #ifdef TARGET_NR_statfs64
7124     case TARGET_NR_statfs64:
7125         if (!(p = lock_user_string(arg1)))
7126             goto efault;
7127         ret = get_errno(statfs(path(p), &stfs));
7128         unlock_user(p, arg1, 0);
7129     convert_statfs64:
7130         if (!is_error(ret)) {
7131             struct target_statfs64 *target_stfs;
7132 
7133             if (!lock_user_struct(VERIFY_WRITE, target_stfs, arg3, 0))
7134                 goto efault;
7135             __put_user(stfs.f_type, &target_stfs->f_type);
7136             __put_user(stfs.f_bsize, &target_stfs->f_bsize);
7137             __put_user(stfs.f_blocks, &target_stfs->f_blocks);
7138             __put_user(stfs.f_bfree, &target_stfs->f_bfree);
7139             __put_user(stfs.f_bavail, &target_stfs->f_bavail);
7140             __put_user(stfs.f_files, &target_stfs->f_files);
7141             __put_user(stfs.f_ffree, &target_stfs->f_ffree);
7142             __put_user(stfs.f_fsid.__val[0], &target_stfs->f_fsid.val[0]);
7143             __put_user(stfs.f_fsid.__val[1], &target_stfs->f_fsid.val[1]);
7144             __put_user(stfs.f_namelen, &target_stfs->f_namelen);
7145             __put_user(stfs.f_frsize, &target_stfs->f_frsize);
7146             memset(target_stfs->f_spare, 0, sizeof(target_stfs->f_spare));
7147             unlock_user_struct(target_stfs, arg3, 1);
7148         }
7149         break;
7150     case TARGET_NR_fstatfs64:
7151         ret = get_errno(fstatfs(arg1, &stfs));
7152         goto convert_statfs64;
7153 #endif
7154 #ifdef TARGET_NR_ioperm
7155     case TARGET_NR_ioperm:
7156         goto unimplemented;
7157 #endif
7158 #ifdef TARGET_NR_socketcall
7159     case TARGET_NR_socketcall:
7160         ret = do_socketcall(arg1, arg2);
7161         break;
7162 #endif
7163 #ifdef TARGET_NR_accept
7164     case TARGET_NR_accept:
7165         ret = do_accept4(arg1, arg2, arg3, 0);
7166         break;
7167 #endif
7168 #ifdef TARGET_NR_accept4
7169     case TARGET_NR_accept4:
7170 #ifdef CONFIG_ACCEPT4
7171         ret = do_accept4(arg1, arg2, arg3, arg4);
7172 #else
7173         goto unimplemented;
7174 #endif
7175         break;
7176 #endif
7177 #ifdef TARGET_NR_bind
7178     case TARGET_NR_bind:
7179         ret = do_bind(arg1, arg2, arg3);
7180         break;
7181 #endif
7182 #ifdef TARGET_NR_connect
7183     case TARGET_NR_connect:
7184         ret = do_connect(arg1, arg2, arg3);
7185         break;
7186 #endif
7187 #ifdef TARGET_NR_getpeername
7188     case TARGET_NR_getpeername:
7189         ret = do_getpeername(arg1, arg2, arg3);
7190         break;
7191 #endif
7192 #ifdef TARGET_NR_getsockname
7193     case TARGET_NR_getsockname:
7194         ret = do_getsockname(arg1, arg2, arg3);
7195         break;
7196 #endif
7197 #ifdef TARGET_NR_getsockopt
7198     case TARGET_NR_getsockopt:
7199         ret = do_getsockopt(arg1, arg2, arg3, arg4, arg5);
7200         break;
7201 #endif
7202 #ifdef TARGET_NR_listen
7203     case TARGET_NR_listen:
7204         ret = get_errno(listen(arg1, arg2));
7205         break;
7206 #endif
7207 #ifdef TARGET_NR_recv
7208     case TARGET_NR_recv:
7209         ret = do_recvfrom(arg1, arg2, arg3, arg4, 0, 0);
7210         break;
7211 #endif
7212 #ifdef TARGET_NR_recvfrom
7213     case TARGET_NR_recvfrom:
7214         ret = do_recvfrom(arg1, arg2, arg3, arg4, arg5, arg6);
7215         break;
7216 #endif
7217 #ifdef TARGET_NR_recvmsg
7218     case TARGET_NR_recvmsg:
7219         ret = do_sendrecvmsg(arg1, arg2, arg3, 0);
7220         break;
7221 #endif
7222 #ifdef TARGET_NR_send
7223     case TARGET_NR_send:
7224         ret = do_sendto(arg1, arg2, arg3, arg4, 0, 0);
7225         break;
7226 #endif
7227 #ifdef TARGET_NR_sendmsg
7228     case TARGET_NR_sendmsg:
7229         ret = do_sendrecvmsg(arg1, arg2, arg3, 1);
7230         break;
7231 #endif
7232 #ifdef TARGET_NR_sendmmsg
7233     case TARGET_NR_sendmmsg:
7234         ret = do_sendrecvmmsg(arg1, arg2, arg3, arg4, 1);
7235         break;
7236     case TARGET_NR_recvmmsg:
7237         ret = do_sendrecvmmsg(arg1, arg2, arg3, arg4, 0);
7238         break;
7239 #endif
7240 #ifdef TARGET_NR_sendto
7241     case TARGET_NR_sendto:
7242         ret = do_sendto(arg1, arg2, arg3, arg4, arg5, arg6);
7243         break;
7244 #endif
7245 #ifdef TARGET_NR_shutdown
7246     case TARGET_NR_shutdown:
7247         ret = get_errno(shutdown(arg1, arg2));
7248         break;
7249 #endif
7250 #ifdef TARGET_NR_socket
7251     case TARGET_NR_socket:
7252         ret = do_socket(arg1, arg2, arg3);
7253         break;
7254 #endif
7255 #ifdef TARGET_NR_socketpair
7256     case TARGET_NR_socketpair:
7257         ret = do_socketpair(arg1, arg2, arg3, arg4);
7258         break;
7259 #endif
7260 #ifdef TARGET_NR_setsockopt
7261     case TARGET_NR_setsockopt:
7262         ret = do_setsockopt(arg1, arg2, arg3, arg4, (socklen_t) arg5);
7263         break;
7264 #endif
7265 
7266     case TARGET_NR_syslog:
7267         if (!(p = lock_user_string(arg2)))
7268             goto efault;
7269         ret = get_errno(sys_syslog((int)arg1, p, (int)arg3));
7270         unlock_user(p, arg2, 0);
7271         break;
7272 
7273     case TARGET_NR_setitimer:
7274         {
7275             struct itimerval value, ovalue, *pvalue;
7276 
7277             if (arg2) {
7278                 pvalue = &value;
7279                 if (copy_from_user_timeval(&pvalue->it_interval, arg2)
7280                     || copy_from_user_timeval(&pvalue->it_value,
7281                                               arg2 + sizeof(struct target_timeval)))
7282                     goto efault;
7283             } else {
7284                 pvalue = NULL;
7285             }
7286             ret = get_errno(setitimer(arg1, pvalue, &ovalue));
7287             if (!is_error(ret) && arg3) {
7288                 if (copy_to_user_timeval(arg3,
7289                                          &ovalue.it_interval)
7290                     || copy_to_user_timeval(arg3 + sizeof(struct target_timeval),
7291                                             &ovalue.it_value))
7292                     goto efault;
7293             }
7294         }
7295         break;
7296     case TARGET_NR_getitimer:
7297         {
7298             struct itimerval value;
7299 
7300             ret = get_errno(getitimer(arg1, &value));
7301             if (!is_error(ret) && arg2) {
7302                 if (copy_to_user_timeval(arg2,
7303                                          &value.it_interval)
7304                     || copy_to_user_timeval(arg2 + sizeof(struct target_timeval),
7305                                             &value.it_value))
7306                     goto efault;
7307             }
7308         }
7309         break;
7310 #ifdef TARGET_NR_stat
7311     case TARGET_NR_stat:
7312         if (!(p = lock_user_string(arg1)))
7313             goto efault;
7314         ret = get_errno(stat(path(p), &st));
7315         unlock_user(p, arg1, 0);
7316         goto do_stat;
7317 #endif
7318 #ifdef TARGET_NR_lstat
7319     case TARGET_NR_lstat:
7320         if (!(p = lock_user_string(arg1)))
7321             goto efault;
7322         ret = get_errno(lstat(path(p), &st));
7323         unlock_user(p, arg1, 0);
7324         goto do_stat;
7325 #endif
7326     case TARGET_NR_fstat:
7327         {
7328             ret = get_errno(fstat(arg1, &st));
7329 #if defined(TARGET_NR_stat) || defined(TARGET_NR_lstat)
7330         do_stat:
7331 #endif
7332             if (!is_error(ret)) {
7333                 struct target_stat *target_st;
7334 
7335                 if (!lock_user_struct(VERIFY_WRITE, target_st, arg2, 0))
7336                     goto efault;
7337                 memset(target_st, 0, sizeof(*target_st));
7338                 __put_user(st.st_dev, &target_st->st_dev);
7339                 __put_user(st.st_ino, &target_st->st_ino);
7340                 __put_user(st.st_mode, &target_st->st_mode);
7341                 __put_user(st.st_uid, &target_st->st_uid);
7342                 __put_user(st.st_gid, &target_st->st_gid);
7343                 __put_user(st.st_nlink, &target_st->st_nlink);
7344                 __put_user(st.st_rdev, &target_st->st_rdev);
7345                 __put_user(st.st_size, &target_st->st_size);
7346                 __put_user(st.st_blksize, &target_st->st_blksize);
7347                 __put_user(st.st_blocks, &target_st->st_blocks);
7348                 __put_user(st.st_atime, &target_st->target_st_atime);
7349                 __put_user(st.st_mtime, &target_st->target_st_mtime);
7350                 __put_user(st.st_ctime, &target_st->target_st_ctime);
7351                 unlock_user_struct(target_st, arg2, 1);
7352             }
7353         }
7354         break;
7355 #ifdef TARGET_NR_olduname
7356     case TARGET_NR_olduname:
7357         goto unimplemented;
7358 #endif
7359 #ifdef TARGET_NR_iopl
7360     case TARGET_NR_iopl:
7361         goto unimplemented;
7362 #endif
7363     case TARGET_NR_vhangup:
7364         ret = get_errno(vhangup());
7365         break;
7366 #ifdef TARGET_NR_idle
7367     case TARGET_NR_idle:
7368         goto unimplemented;
7369 #endif
7370 #ifdef TARGET_NR_syscall
7371     case TARGET_NR_syscall:
7372         ret = do_syscall(cpu_env, arg1 & 0xffff, arg2, arg3, arg4, arg5,
7373                          arg6, arg7, arg8, 0);
7374         break;
7375 #endif
7376     case TARGET_NR_wait4:
7377         {
7378             int status;
7379             abi_long status_ptr = arg2;
7380             struct rusage rusage, *rusage_ptr;
7381             abi_ulong target_rusage = arg4;
7382             abi_long rusage_err;
7383             if (target_rusage)
7384                 rusage_ptr = &rusage;
7385             else
7386                 rusage_ptr = NULL;
7387             ret = get_errno(wait4(arg1, &status, arg3, rusage_ptr));
7388             if (!is_error(ret)) {
7389                 if (status_ptr && ret) {
7390                     status = host_to_target_waitstatus(status);
7391                     if (put_user_s32(status, status_ptr))
7392                         goto efault;
7393                 }
7394                 if (target_rusage) {
7395                     rusage_err = host_to_target_rusage(target_rusage, &rusage);
7396                     if (rusage_err) {
7397                         ret = rusage_err;
7398                     }
7399                 }
7400             }
7401         }
7402         break;
7403 #ifdef TARGET_NR_swapoff
7404     case TARGET_NR_swapoff:
7405         if (!(p = lock_user_string(arg1)))
7406             goto efault;
7407         ret = get_errno(swapoff(p));
7408         unlock_user(p, arg1, 0);
7409         break;
7410 #endif
7411     case TARGET_NR_sysinfo:
7412         {
7413             struct target_sysinfo *target_value;
7414             struct sysinfo value;
7415             ret = get_errno(sysinfo(&value));
7416             if (!is_error(ret) && arg1)
7417             {
7418                 if (!lock_user_struct(VERIFY_WRITE, target_value, arg1, 0))
7419                     goto efault;
7420                 __put_user(value.uptime, &target_value->uptime);
7421                 __put_user(value.loads[0], &target_value->loads[0]);
7422                 __put_user(value.loads[1], &target_value->loads[1]);
7423                 __put_user(value.loads[2], &target_value->loads[2]);
7424                 __put_user(value.totalram, &target_value->totalram);
7425                 __put_user(value.freeram, &target_value->freeram);
7426                 __put_user(value.sharedram, &target_value->sharedram);
7427                 __put_user(value.bufferram, &target_value->bufferram);
7428                 __put_user(value.totalswap, &target_value->totalswap);
7429                 __put_user(value.freeswap, &target_value->freeswap);
7430                 __put_user(value.procs, &target_value->procs);
7431                 __put_user(value.totalhigh, &target_value->totalhigh);
7432                 __put_user(value.freehigh, &target_value->freehigh);
7433                 __put_user(value.mem_unit, &target_value->mem_unit);
7434                 unlock_user_struct(target_value, arg1, 1);
7435             }
7436         }
7437         break;
7438 #ifdef TARGET_NR_ipc
7439     case TARGET_NR_ipc:
7440 	ret = do_ipc(arg1, arg2, arg3, arg4, arg5, arg6);
7441 	break;
7442 #endif
7443 #ifdef TARGET_NR_semget
7444     case TARGET_NR_semget:
7445         ret = get_errno(semget(arg1, arg2, arg3));
7446         break;
7447 #endif
7448 #ifdef TARGET_NR_semop
7449     case TARGET_NR_semop:
7450         ret = do_semop(arg1, arg2, arg3);
7451         break;
7452 #endif
7453 #ifdef TARGET_NR_semctl
7454     case TARGET_NR_semctl:
7455         ret = do_semctl(arg1, arg2, arg3, (union target_semun)(abi_ulong)arg4);
7456         break;
7457 #endif
7458 #ifdef TARGET_NR_msgctl
7459     case TARGET_NR_msgctl:
7460         ret = do_msgctl(arg1, arg2, arg3);
7461         break;
7462 #endif
7463 #ifdef TARGET_NR_msgget
7464     case TARGET_NR_msgget:
7465         ret = get_errno(msgget(arg1, arg2));
7466         break;
7467 #endif
7468 #ifdef TARGET_NR_msgrcv
7469     case TARGET_NR_msgrcv:
7470         ret = do_msgrcv(arg1, arg2, arg3, arg4, arg5);
7471         break;
7472 #endif
7473 #ifdef TARGET_NR_msgsnd
7474     case TARGET_NR_msgsnd:
7475         ret = do_msgsnd(arg1, arg2, arg3, arg4);
7476         break;
7477 #endif
7478 #ifdef TARGET_NR_shmget
7479     case TARGET_NR_shmget:
7480         ret = get_errno(shmget(arg1, arg2, arg3));
7481         break;
7482 #endif
7483 #ifdef TARGET_NR_shmctl
7484     case TARGET_NR_shmctl:
7485         ret = do_shmctl(arg1, arg2, arg3);
7486         break;
7487 #endif
7488 #ifdef TARGET_NR_shmat
7489     case TARGET_NR_shmat:
7490         ret = do_shmat(arg1, arg2, arg3);
7491         break;
7492 #endif
7493 #ifdef TARGET_NR_shmdt
7494     case TARGET_NR_shmdt:
7495         ret = do_shmdt(arg1);
7496         break;
7497 #endif
7498     case TARGET_NR_fsync:
7499         ret = get_errno(fsync(arg1));
7500         break;
7501     case TARGET_NR_clone:
7502         /* Linux manages to have three different orderings for its
7503          * arguments to clone(); the BACKWARDS and BACKWARDS2 defines
7504          * match the kernel's CONFIG_CLONE_* settings.
7505          * Microblaze is further special in that it uses a sixth
7506          * implicit argument to clone for the TLS pointer.
7507          */
7508 #if defined(TARGET_MICROBLAZE)
7509         ret = get_errno(do_fork(cpu_env, arg1, arg2, arg4, arg6, arg5));
7510 #elif defined(TARGET_CLONE_BACKWARDS)
7511         ret = get_errno(do_fork(cpu_env, arg1, arg2, arg3, arg4, arg5));
7512 #elif defined(TARGET_CLONE_BACKWARDS2)
7513         ret = get_errno(do_fork(cpu_env, arg2, arg1, arg3, arg5, arg4));
7514 #else
7515         ret = get_errno(do_fork(cpu_env, arg1, arg2, arg3, arg5, arg4));
7516 #endif
7517         break;
7518 #ifdef __NR_exit_group
7519         /* new thread calls */
7520     case TARGET_NR_exit_group:
7521 #ifdef TARGET_GPROF
7522         _mcleanup();
7523 #endif
7524         gdb_exit(cpu_env, arg1);
7525         ret = get_errno(exit_group(arg1));
7526         break;
7527 #endif
7528     case TARGET_NR_setdomainname:
7529         if (!(p = lock_user_string(arg1)))
7530             goto efault;
7531         ret = get_errno(setdomainname(p, arg2));
7532         unlock_user(p, arg1, 0);
7533         break;
7534     case TARGET_NR_uname:
7535         /* no need to transcode because we use the linux syscall */
7536         {
7537             struct new_utsname * buf;
7538 
7539             if (!lock_user_struct(VERIFY_WRITE, buf, arg1, 0))
7540                 goto efault;
7541             ret = get_errno(sys_uname(buf));
7542             if (!is_error(ret)) {
7543                 /* Overrite the native machine name with whatever is being
7544                    emulated. */
7545                 strcpy (buf->machine, cpu_to_uname_machine(cpu_env));
7546                 /* Allow the user to override the reported release.  */
7547                 if (qemu_uname_release && *qemu_uname_release)
7548                   strcpy (buf->release, qemu_uname_release);
7549             }
7550             unlock_user_struct(buf, arg1, 1);
7551         }
7552         break;
7553 #ifdef TARGET_I386
7554     case TARGET_NR_modify_ldt:
7555         ret = do_modify_ldt(cpu_env, arg1, arg2, arg3);
7556         break;
7557 #if !defined(TARGET_X86_64)
7558     case TARGET_NR_vm86old:
7559         goto unimplemented;
7560     case TARGET_NR_vm86:
7561         ret = do_vm86(cpu_env, arg1, arg2);
7562         break;
7563 #endif
7564 #endif
7565     case TARGET_NR_adjtimex:
7566         goto unimplemented;
7567 #ifdef TARGET_NR_create_module
7568     case TARGET_NR_create_module:
7569 #endif
7570     case TARGET_NR_init_module:
7571     case TARGET_NR_delete_module:
7572 #ifdef TARGET_NR_get_kernel_syms
7573     case TARGET_NR_get_kernel_syms:
7574 #endif
7575         goto unimplemented;
7576     case TARGET_NR_quotactl:
7577         goto unimplemented;
7578     case TARGET_NR_getpgid:
7579         ret = get_errno(getpgid(arg1));
7580         break;
7581     case TARGET_NR_fchdir:
7582         ret = get_errno(fchdir(arg1));
7583         break;
7584 #ifdef TARGET_NR_bdflush /* not on x86_64 */
7585     case TARGET_NR_bdflush:
7586         goto unimplemented;
7587 #endif
7588 #ifdef TARGET_NR_sysfs
7589     case TARGET_NR_sysfs:
7590         goto unimplemented;
7591 #endif
7592     case TARGET_NR_personality:
7593         ret = get_errno(personality(arg1));
7594         break;
7595 #ifdef TARGET_NR_afs_syscall
7596     case TARGET_NR_afs_syscall:
7597         goto unimplemented;
7598 #endif
7599 #ifdef TARGET_NR__llseek /* Not on alpha */
7600     case TARGET_NR__llseek:
7601         {
7602             int64_t res;
7603 #if !defined(__NR_llseek)
7604             res = lseek(arg1, ((uint64_t)arg2 << 32) | arg3, arg5);
7605             if (res == -1) {
7606                 ret = get_errno(res);
7607             } else {
7608                 ret = 0;
7609             }
7610 #else
7611             ret = get_errno(_llseek(arg1, arg2, arg3, &res, arg5));
7612 #endif
7613             if ((ret == 0) && put_user_s64(res, arg4)) {
7614                 goto efault;
7615             }
7616         }
7617         break;
7618 #endif
7619 #ifdef TARGET_NR_getdents
7620     case TARGET_NR_getdents:
7621 #ifdef __NR_getdents
7622 #if TARGET_ABI_BITS == 32 && HOST_LONG_BITS == 64
7623         {
7624             struct target_dirent *target_dirp;
7625             struct linux_dirent *dirp;
7626             abi_long count = arg3;
7627 
7628 	    dirp = malloc(count);
7629 	    if (!dirp) {
7630                 ret = -TARGET_ENOMEM;
7631                 goto fail;
7632             }
7633 
7634             ret = get_errno(sys_getdents(arg1, dirp, count));
7635             if (!is_error(ret)) {
7636                 struct linux_dirent *de;
7637 		struct target_dirent *tde;
7638                 int len = ret;
7639                 int reclen, treclen;
7640 		int count1, tnamelen;
7641 
7642 		count1 = 0;
7643                 de = dirp;
7644                 if (!(target_dirp = lock_user(VERIFY_WRITE, arg2, count, 0)))
7645                     goto efault;
7646 		tde = target_dirp;
7647                 while (len > 0) {
7648                     reclen = de->d_reclen;
7649                     tnamelen = reclen - offsetof(struct linux_dirent, d_name);
7650                     assert(tnamelen >= 0);
7651                     treclen = tnamelen + offsetof(struct target_dirent, d_name);
7652                     assert(count1 + treclen <= count);
7653                     tde->d_reclen = tswap16(treclen);
7654                     tde->d_ino = tswapal(de->d_ino);
7655                     tde->d_off = tswapal(de->d_off);
7656                     memcpy(tde->d_name, de->d_name, tnamelen);
7657                     de = (struct linux_dirent *)((char *)de + reclen);
7658                     len -= reclen;
7659                     tde = (struct target_dirent *)((char *)tde + treclen);
7660 		    count1 += treclen;
7661                 }
7662 		ret = count1;
7663                 unlock_user(target_dirp, arg2, ret);
7664             }
7665 	    free(dirp);
7666         }
7667 #else
7668         {
7669             struct linux_dirent *dirp;
7670             abi_long count = arg3;
7671 
7672             if (!(dirp = lock_user(VERIFY_WRITE, arg2, count, 0)))
7673                 goto efault;
7674             ret = get_errno(sys_getdents(arg1, dirp, count));
7675             if (!is_error(ret)) {
7676                 struct linux_dirent *de;
7677                 int len = ret;
7678                 int reclen;
7679                 de = dirp;
7680                 while (len > 0) {
7681                     reclen = de->d_reclen;
7682                     if (reclen > len)
7683                         break;
7684                     de->d_reclen = tswap16(reclen);
7685                     tswapls(&de->d_ino);
7686                     tswapls(&de->d_off);
7687                     de = (struct linux_dirent *)((char *)de + reclen);
7688                     len -= reclen;
7689                 }
7690             }
7691             unlock_user(dirp, arg2, ret);
7692         }
7693 #endif
7694 #else
7695         /* Implement getdents in terms of getdents64 */
7696         {
7697             struct linux_dirent64 *dirp;
7698             abi_long count = arg3;
7699 
7700             dirp = lock_user(VERIFY_WRITE, arg2, count, 0);
7701             if (!dirp) {
7702                 goto efault;
7703             }
7704             ret = get_errno(sys_getdents64(arg1, dirp, count));
7705             if (!is_error(ret)) {
7706                 /* Convert the dirent64 structs to target dirent.  We do this
7707                  * in-place, since we can guarantee that a target_dirent is no
7708                  * larger than a dirent64; however this means we have to be
7709                  * careful to read everything before writing in the new format.
7710                  */
7711                 struct linux_dirent64 *de;
7712                 struct target_dirent *tde;
7713                 int len = ret;
7714                 int tlen = 0;
7715 
7716                 de = dirp;
7717                 tde = (struct target_dirent *)dirp;
7718                 while (len > 0) {
7719                     int namelen, treclen;
7720                     int reclen = de->d_reclen;
7721                     uint64_t ino = de->d_ino;
7722                     int64_t off = de->d_off;
7723                     uint8_t type = de->d_type;
7724 
7725                     namelen = strlen(de->d_name);
7726                     treclen = offsetof(struct target_dirent, d_name)
7727                         + namelen + 2;
7728                     treclen = QEMU_ALIGN_UP(treclen, sizeof(abi_long));
7729 
7730                     memmove(tde->d_name, de->d_name, namelen + 1);
7731                     tde->d_ino = tswapal(ino);
7732                     tde->d_off = tswapal(off);
7733                     tde->d_reclen = tswap16(treclen);
7734                     /* The target_dirent type is in what was formerly a padding
7735                      * byte at the end of the structure:
7736                      */
7737                     *(((char *)tde) + treclen - 1) = type;
7738 
7739                     de = (struct linux_dirent64 *)((char *)de + reclen);
7740                     tde = (struct target_dirent *)((char *)tde + treclen);
7741                     len -= reclen;
7742                     tlen += treclen;
7743                 }
7744                 ret = tlen;
7745             }
7746             unlock_user(dirp, arg2, ret);
7747         }
7748 #endif
7749         break;
7750 #endif /* TARGET_NR_getdents */
7751 #if defined(TARGET_NR_getdents64) && defined(__NR_getdents64)
7752     case TARGET_NR_getdents64:
7753         {
7754             struct linux_dirent64 *dirp;
7755             abi_long count = arg3;
7756             if (!(dirp = lock_user(VERIFY_WRITE, arg2, count, 0)))
7757                 goto efault;
7758             ret = get_errno(sys_getdents64(arg1, dirp, count));
7759             if (!is_error(ret)) {
7760                 struct linux_dirent64 *de;
7761                 int len = ret;
7762                 int reclen;
7763                 de = dirp;
7764                 while (len > 0) {
7765                     reclen = de->d_reclen;
7766                     if (reclen > len)
7767                         break;
7768                     de->d_reclen = tswap16(reclen);
7769                     tswap64s((uint64_t *)&de->d_ino);
7770                     tswap64s((uint64_t *)&de->d_off);
7771                     de = (struct linux_dirent64 *)((char *)de + reclen);
7772                     len -= reclen;
7773                 }
7774             }
7775             unlock_user(dirp, arg2, ret);
7776         }
7777         break;
7778 #endif /* TARGET_NR_getdents64 */
7779 #if defined(TARGET_NR__newselect)
7780     case TARGET_NR__newselect:
7781         ret = do_select(arg1, arg2, arg3, arg4, arg5);
7782         break;
7783 #endif
7784 #if defined(TARGET_NR_poll) || defined(TARGET_NR_ppoll)
7785 # ifdef TARGET_NR_poll
7786     case TARGET_NR_poll:
7787 # endif
7788 # ifdef TARGET_NR_ppoll
7789     case TARGET_NR_ppoll:
7790 # endif
7791         {
7792             struct target_pollfd *target_pfd;
7793             unsigned int nfds = arg2;
7794             int timeout = arg3;
7795             struct pollfd *pfd;
7796             unsigned int i;
7797 
7798             target_pfd = lock_user(VERIFY_WRITE, arg1, sizeof(struct target_pollfd) * nfds, 1);
7799             if (!target_pfd)
7800                 goto efault;
7801 
7802             pfd = alloca(sizeof(struct pollfd) * nfds);
7803             for(i = 0; i < nfds; i++) {
7804                 pfd[i].fd = tswap32(target_pfd[i].fd);
7805                 pfd[i].events = tswap16(target_pfd[i].events);
7806             }
7807 
7808 # ifdef TARGET_NR_ppoll
7809             if (num == TARGET_NR_ppoll) {
7810                 struct timespec _timeout_ts, *timeout_ts = &_timeout_ts;
7811                 target_sigset_t *target_set;
7812                 sigset_t _set, *set = &_set;
7813 
7814                 if (arg3) {
7815                     if (target_to_host_timespec(timeout_ts, arg3)) {
7816                         unlock_user(target_pfd, arg1, 0);
7817                         goto efault;
7818                     }
7819                 } else {
7820                     timeout_ts = NULL;
7821                 }
7822 
7823                 if (arg4) {
7824                     target_set = lock_user(VERIFY_READ, arg4, sizeof(target_sigset_t), 1);
7825                     if (!target_set) {
7826                         unlock_user(target_pfd, arg1, 0);
7827                         goto efault;
7828                     }
7829                     target_to_host_sigset(set, target_set);
7830                 } else {
7831                     set = NULL;
7832                 }
7833 
7834                 ret = get_errno(sys_ppoll(pfd, nfds, timeout_ts, set, _NSIG/8));
7835 
7836                 if (!is_error(ret) && arg3) {
7837                     host_to_target_timespec(arg3, timeout_ts);
7838                 }
7839                 if (arg4) {
7840                     unlock_user(target_set, arg4, 0);
7841                 }
7842             } else
7843 # endif
7844                 ret = get_errno(poll(pfd, nfds, timeout));
7845 
7846             if (!is_error(ret)) {
7847                 for(i = 0; i < nfds; i++) {
7848                     target_pfd[i].revents = tswap16(pfd[i].revents);
7849                 }
7850             }
7851             unlock_user(target_pfd, arg1, sizeof(struct target_pollfd) * nfds);
7852         }
7853         break;
7854 #endif
7855     case TARGET_NR_flock:
7856         /* NOTE: the flock constant seems to be the same for every
7857            Linux platform */
7858         ret = get_errno(flock(arg1, arg2));
7859         break;
7860     case TARGET_NR_readv:
7861         {
7862             struct iovec *vec = lock_iovec(VERIFY_WRITE, arg2, arg3, 0);
7863             if (vec != NULL) {
7864                 ret = get_errno(readv(arg1, vec, arg3));
7865                 unlock_iovec(vec, arg2, arg3, 1);
7866             } else {
7867                 ret = -host_to_target_errno(errno);
7868             }
7869         }
7870         break;
7871     case TARGET_NR_writev:
7872         {
7873             struct iovec *vec = lock_iovec(VERIFY_READ, arg2, arg3, 1);
7874             if (vec != NULL) {
7875                 ret = get_errno(writev(arg1, vec, arg3));
7876                 unlock_iovec(vec, arg2, arg3, 0);
7877             } else {
7878                 ret = -host_to_target_errno(errno);
7879             }
7880         }
7881         break;
7882     case TARGET_NR_getsid:
7883         ret = get_errno(getsid(arg1));
7884         break;
7885 #if defined(TARGET_NR_fdatasync) /* Not on alpha (osf_datasync ?) */
7886     case TARGET_NR_fdatasync:
7887         ret = get_errno(fdatasync(arg1));
7888         break;
7889 #endif
7890 #ifdef TARGET_NR__sysctl
7891     case TARGET_NR__sysctl:
7892         /* We don't implement this, but ENOTDIR is always a safe
7893            return value. */
7894         ret = -TARGET_ENOTDIR;
7895         break;
7896 #endif
7897     case TARGET_NR_sched_getaffinity:
7898         {
7899             unsigned int mask_size;
7900             unsigned long *mask;
7901 
7902             /*
7903              * sched_getaffinity needs multiples of ulong, so need to take
7904              * care of mismatches between target ulong and host ulong sizes.
7905              */
7906             if (arg2 & (sizeof(abi_ulong) - 1)) {
7907                 ret = -TARGET_EINVAL;
7908                 break;
7909             }
7910             mask_size = (arg2 + (sizeof(*mask) - 1)) & ~(sizeof(*mask) - 1);
7911 
7912             mask = alloca(mask_size);
7913             ret = get_errno(sys_sched_getaffinity(arg1, mask_size, mask));
7914 
7915             if (!is_error(ret)) {
7916                 if (ret > arg2) {
7917                     /* More data returned than the caller's buffer will fit.
7918                      * This only happens if sizeof(abi_long) < sizeof(long)
7919                      * and the caller passed us a buffer holding an odd number
7920                      * of abi_longs. If the host kernel is actually using the
7921                      * extra 4 bytes then fail EINVAL; otherwise we can just
7922                      * ignore them and only copy the interesting part.
7923                      */
7924                     int numcpus = sysconf(_SC_NPROCESSORS_CONF);
7925                     if (numcpus > arg2 * 8) {
7926                         ret = -TARGET_EINVAL;
7927                         break;
7928                     }
7929                     ret = arg2;
7930                 }
7931 
7932                 if (copy_to_user(arg3, mask, ret)) {
7933                     goto efault;
7934                 }
7935             }
7936         }
7937         break;
7938     case TARGET_NR_sched_setaffinity:
7939         {
7940             unsigned int mask_size;
7941             unsigned long *mask;
7942 
7943             /*
7944              * sched_setaffinity needs multiples of ulong, so need to take
7945              * care of mismatches between target ulong and host ulong sizes.
7946              */
7947             if (arg2 & (sizeof(abi_ulong) - 1)) {
7948                 ret = -TARGET_EINVAL;
7949                 break;
7950             }
7951             mask_size = (arg2 + (sizeof(*mask) - 1)) & ~(sizeof(*mask) - 1);
7952 
7953             mask = alloca(mask_size);
7954             if (!lock_user_struct(VERIFY_READ, p, arg3, 1)) {
7955                 goto efault;
7956             }
7957             memcpy(mask, p, arg2);
7958             unlock_user_struct(p, arg2, 0);
7959 
7960             ret = get_errno(sys_sched_setaffinity(arg1, mask_size, mask));
7961         }
7962         break;
7963     case TARGET_NR_sched_setparam:
7964         {
7965             struct sched_param *target_schp;
7966             struct sched_param schp;
7967 
7968             if (arg2 == 0) {
7969                 return -TARGET_EINVAL;
7970             }
7971             if (!lock_user_struct(VERIFY_READ, target_schp, arg2, 1))
7972                 goto efault;
7973             schp.sched_priority = tswap32(target_schp->sched_priority);
7974             unlock_user_struct(target_schp, arg2, 0);
7975             ret = get_errno(sched_setparam(arg1, &schp));
7976         }
7977         break;
7978     case TARGET_NR_sched_getparam:
7979         {
7980             struct sched_param *target_schp;
7981             struct sched_param schp;
7982 
7983             if (arg2 == 0) {
7984                 return -TARGET_EINVAL;
7985             }
7986             ret = get_errno(sched_getparam(arg1, &schp));
7987             if (!is_error(ret)) {
7988                 if (!lock_user_struct(VERIFY_WRITE, target_schp, arg2, 0))
7989                     goto efault;
7990                 target_schp->sched_priority = tswap32(schp.sched_priority);
7991                 unlock_user_struct(target_schp, arg2, 1);
7992             }
7993         }
7994         break;
7995     case TARGET_NR_sched_setscheduler:
7996         {
7997             struct sched_param *target_schp;
7998             struct sched_param schp;
7999             if (arg3 == 0) {
8000                 return -TARGET_EINVAL;
8001             }
8002             if (!lock_user_struct(VERIFY_READ, target_schp, arg3, 1))
8003                 goto efault;
8004             schp.sched_priority = tswap32(target_schp->sched_priority);
8005             unlock_user_struct(target_schp, arg3, 0);
8006             ret = get_errno(sched_setscheduler(arg1, arg2, &schp));
8007         }
8008         break;
8009     case TARGET_NR_sched_getscheduler:
8010         ret = get_errno(sched_getscheduler(arg1));
8011         break;
8012     case TARGET_NR_sched_yield:
8013         ret = get_errno(sched_yield());
8014         break;
8015     case TARGET_NR_sched_get_priority_max:
8016         ret = get_errno(sched_get_priority_max(arg1));
8017         break;
8018     case TARGET_NR_sched_get_priority_min:
8019         ret = get_errno(sched_get_priority_min(arg1));
8020         break;
8021     case TARGET_NR_sched_rr_get_interval:
8022         {
8023             struct timespec ts;
8024             ret = get_errno(sched_rr_get_interval(arg1, &ts));
8025             if (!is_error(ret)) {
8026                 ret = host_to_target_timespec(arg2, &ts);
8027             }
8028         }
8029         break;
8030     case TARGET_NR_nanosleep:
8031         {
8032             struct timespec req, rem;
8033             target_to_host_timespec(&req, arg1);
8034             ret = get_errno(nanosleep(&req, &rem));
8035             if (is_error(ret) && arg2) {
8036                 host_to_target_timespec(arg2, &rem);
8037             }
8038         }
8039         break;
8040 #ifdef TARGET_NR_query_module
8041     case TARGET_NR_query_module:
8042         goto unimplemented;
8043 #endif
8044 #ifdef TARGET_NR_nfsservctl
8045     case TARGET_NR_nfsservctl:
8046         goto unimplemented;
8047 #endif
8048     case TARGET_NR_prctl:
8049         switch (arg1) {
8050         case PR_GET_PDEATHSIG:
8051         {
8052             int deathsig;
8053             ret = get_errno(prctl(arg1, &deathsig, arg3, arg4, arg5));
8054             if (!is_error(ret) && arg2
8055                 && put_user_ual(deathsig, arg2)) {
8056                 goto efault;
8057             }
8058             break;
8059         }
8060 #ifdef PR_GET_NAME
8061         case PR_GET_NAME:
8062         {
8063             void *name = lock_user(VERIFY_WRITE, arg2, 16, 1);
8064             if (!name) {
8065                 goto efault;
8066             }
8067             ret = get_errno(prctl(arg1, (unsigned long)name,
8068                                   arg3, arg4, arg5));
8069             unlock_user(name, arg2, 16);
8070             break;
8071         }
8072         case PR_SET_NAME:
8073         {
8074             void *name = lock_user(VERIFY_READ, arg2, 16, 1);
8075             if (!name) {
8076                 goto efault;
8077             }
8078             ret = get_errno(prctl(arg1, (unsigned long)name,
8079                                   arg3, arg4, arg5));
8080             unlock_user(name, arg2, 0);
8081             break;
8082         }
8083 #endif
8084         default:
8085             /* Most prctl options have no pointer arguments */
8086             ret = get_errno(prctl(arg1, arg2, arg3, arg4, arg5));
8087             break;
8088         }
8089         break;
8090 #ifdef TARGET_NR_arch_prctl
8091     case TARGET_NR_arch_prctl:
8092 #if defined(TARGET_I386) && !defined(TARGET_ABI32)
8093         ret = do_arch_prctl(cpu_env, arg1, arg2);
8094         break;
8095 #else
8096         goto unimplemented;
8097 #endif
8098 #endif
8099 #ifdef TARGET_NR_pread64
8100     case TARGET_NR_pread64:
8101         if (regpairs_aligned(cpu_env)) {
8102             arg4 = arg5;
8103             arg5 = arg6;
8104         }
8105         if (!(p = lock_user(VERIFY_WRITE, arg2, arg3, 0)))
8106             goto efault;
8107         ret = get_errno(pread64(arg1, p, arg3, target_offset64(arg4, arg5)));
8108         unlock_user(p, arg2, ret);
8109         break;
8110     case TARGET_NR_pwrite64:
8111         if (regpairs_aligned(cpu_env)) {
8112             arg4 = arg5;
8113             arg5 = arg6;
8114         }
8115         if (!(p = lock_user(VERIFY_READ, arg2, arg3, 1)))
8116             goto efault;
8117         ret = get_errno(pwrite64(arg1, p, arg3, target_offset64(arg4, arg5)));
8118         unlock_user(p, arg2, 0);
8119         break;
8120 #endif
8121     case TARGET_NR_getcwd:
8122         if (!(p = lock_user(VERIFY_WRITE, arg1, arg2, 0)))
8123             goto efault;
8124         ret = get_errno(sys_getcwd1(p, arg2));
8125         unlock_user(p, arg1, ret);
8126         break;
8127     case TARGET_NR_capget:
8128     case TARGET_NR_capset:
8129     {
8130         struct target_user_cap_header *target_header;
8131         struct target_user_cap_data *target_data = NULL;
8132         struct __user_cap_header_struct header;
8133         struct __user_cap_data_struct data[2];
8134         struct __user_cap_data_struct *dataptr = NULL;
8135         int i, target_datalen;
8136         int data_items = 1;
8137 
8138         if (!lock_user_struct(VERIFY_WRITE, target_header, arg1, 1)) {
8139             goto efault;
8140         }
8141         header.version = tswap32(target_header->version);
8142         header.pid = tswap32(target_header->pid);
8143 
8144         if (header.version != _LINUX_CAPABILITY_VERSION) {
8145             /* Version 2 and up takes pointer to two user_data structs */
8146             data_items = 2;
8147         }
8148 
8149         target_datalen = sizeof(*target_data) * data_items;
8150 
8151         if (arg2) {
8152             if (num == TARGET_NR_capget) {
8153                 target_data = lock_user(VERIFY_WRITE, arg2, target_datalen, 0);
8154             } else {
8155                 target_data = lock_user(VERIFY_READ, arg2, target_datalen, 1);
8156             }
8157             if (!target_data) {
8158                 unlock_user_struct(target_header, arg1, 0);
8159                 goto efault;
8160             }
8161 
8162             if (num == TARGET_NR_capset) {
8163                 for (i = 0; i < data_items; i++) {
8164                     data[i].effective = tswap32(target_data[i].effective);
8165                     data[i].permitted = tswap32(target_data[i].permitted);
8166                     data[i].inheritable = tswap32(target_data[i].inheritable);
8167                 }
8168             }
8169 
8170             dataptr = data;
8171         }
8172 
8173         if (num == TARGET_NR_capget) {
8174             ret = get_errno(capget(&header, dataptr));
8175         } else {
8176             ret = get_errno(capset(&header, dataptr));
8177         }
8178 
8179         /* The kernel always updates version for both capget and capset */
8180         target_header->version = tswap32(header.version);
8181         unlock_user_struct(target_header, arg1, 1);
8182 
8183         if (arg2) {
8184             if (num == TARGET_NR_capget) {
8185                 for (i = 0; i < data_items; i++) {
8186                     target_data[i].effective = tswap32(data[i].effective);
8187                     target_data[i].permitted = tswap32(data[i].permitted);
8188                     target_data[i].inheritable = tswap32(data[i].inheritable);
8189                 }
8190                 unlock_user(target_data, arg2, target_datalen);
8191             } else {
8192                 unlock_user(target_data, arg2, 0);
8193             }
8194         }
8195         break;
8196     }
8197     case TARGET_NR_sigaltstack:
8198 #if defined(TARGET_I386) || defined(TARGET_ARM) || defined(TARGET_MIPS) || \
8199     defined(TARGET_SPARC) || defined(TARGET_PPC) || defined(TARGET_ALPHA) || \
8200     defined(TARGET_M68K) || defined(TARGET_S390X) || defined(TARGET_OPENRISC)
8201         ret = do_sigaltstack(arg1, arg2, get_sp_from_cpustate((CPUArchState *)cpu_env));
8202         break;
8203 #else
8204         goto unimplemented;
8205 #endif
8206 
8207 #ifdef CONFIG_SENDFILE
8208     case TARGET_NR_sendfile:
8209     {
8210         off_t *offp = NULL;
8211         off_t off;
8212         if (arg3) {
8213             ret = get_user_sal(off, arg3);
8214             if (is_error(ret)) {
8215                 break;
8216             }
8217             offp = &off;
8218         }
8219         ret = get_errno(sendfile(arg1, arg2, offp, arg4));
8220         if (!is_error(ret) && arg3) {
8221             abi_long ret2 = put_user_sal(off, arg3);
8222             if (is_error(ret2)) {
8223                 ret = ret2;
8224             }
8225         }
8226         break;
8227     }
8228 #ifdef TARGET_NR_sendfile64
8229     case TARGET_NR_sendfile64:
8230     {
8231         off_t *offp = NULL;
8232         off_t off;
8233         if (arg3) {
8234             ret = get_user_s64(off, arg3);
8235             if (is_error(ret)) {
8236                 break;
8237             }
8238             offp = &off;
8239         }
8240         ret = get_errno(sendfile(arg1, arg2, offp, arg4));
8241         if (!is_error(ret) && arg3) {
8242             abi_long ret2 = put_user_s64(off, arg3);
8243             if (is_error(ret2)) {
8244                 ret = ret2;
8245             }
8246         }
8247         break;
8248     }
8249 #endif
8250 #else
8251     case TARGET_NR_sendfile:
8252 #ifdef TARGET_NR_sendfile64
8253     case TARGET_NR_sendfile64:
8254 #endif
8255         goto unimplemented;
8256 #endif
8257 
8258 #ifdef TARGET_NR_getpmsg
8259     case TARGET_NR_getpmsg:
8260         goto unimplemented;
8261 #endif
8262 #ifdef TARGET_NR_putpmsg
8263     case TARGET_NR_putpmsg:
8264         goto unimplemented;
8265 #endif
8266 #ifdef TARGET_NR_vfork
8267     case TARGET_NR_vfork:
8268         ret = get_errno(do_fork(cpu_env, CLONE_VFORK | CLONE_VM | SIGCHLD,
8269                         0, 0, 0, 0));
8270         break;
8271 #endif
8272 #ifdef TARGET_NR_ugetrlimit
8273     case TARGET_NR_ugetrlimit:
8274     {
8275 	struct rlimit rlim;
8276 	int resource = target_to_host_resource(arg1);
8277 	ret = get_errno(getrlimit(resource, &rlim));
8278 	if (!is_error(ret)) {
8279 	    struct target_rlimit *target_rlim;
8280             if (!lock_user_struct(VERIFY_WRITE, target_rlim, arg2, 0))
8281                 goto efault;
8282 	    target_rlim->rlim_cur = host_to_target_rlim(rlim.rlim_cur);
8283 	    target_rlim->rlim_max = host_to_target_rlim(rlim.rlim_max);
8284             unlock_user_struct(target_rlim, arg2, 1);
8285 	}
8286 	break;
8287     }
8288 #endif
8289 #ifdef TARGET_NR_truncate64
8290     case TARGET_NR_truncate64:
8291         if (!(p = lock_user_string(arg1)))
8292             goto efault;
8293 	ret = target_truncate64(cpu_env, p, arg2, arg3, arg4);
8294         unlock_user(p, arg1, 0);
8295 	break;
8296 #endif
8297 #ifdef TARGET_NR_ftruncate64
8298     case TARGET_NR_ftruncate64:
8299 	ret = target_ftruncate64(cpu_env, arg1, arg2, arg3, arg4);
8300 	break;
8301 #endif
8302 #ifdef TARGET_NR_stat64
8303     case TARGET_NR_stat64:
8304         if (!(p = lock_user_string(arg1)))
8305             goto efault;
8306         ret = get_errno(stat(path(p), &st));
8307         unlock_user(p, arg1, 0);
8308         if (!is_error(ret))
8309             ret = host_to_target_stat64(cpu_env, arg2, &st);
8310         break;
8311 #endif
8312 #ifdef TARGET_NR_lstat64
8313     case TARGET_NR_lstat64:
8314         if (!(p = lock_user_string(arg1)))
8315             goto efault;
8316         ret = get_errno(lstat(path(p), &st));
8317         unlock_user(p, arg1, 0);
8318         if (!is_error(ret))
8319             ret = host_to_target_stat64(cpu_env, arg2, &st);
8320         break;
8321 #endif
8322 #ifdef TARGET_NR_fstat64
8323     case TARGET_NR_fstat64:
8324         ret = get_errno(fstat(arg1, &st));
8325         if (!is_error(ret))
8326             ret = host_to_target_stat64(cpu_env, arg2, &st);
8327         break;
8328 #endif
8329 #if (defined(TARGET_NR_fstatat64) || defined(TARGET_NR_newfstatat))
8330 #ifdef TARGET_NR_fstatat64
8331     case TARGET_NR_fstatat64:
8332 #endif
8333 #ifdef TARGET_NR_newfstatat
8334     case TARGET_NR_newfstatat:
8335 #endif
8336         if (!(p = lock_user_string(arg2)))
8337             goto efault;
8338         ret = get_errno(fstatat(arg1, path(p), &st, arg4));
8339         if (!is_error(ret))
8340             ret = host_to_target_stat64(cpu_env, arg3, &st);
8341         break;
8342 #endif
8343 #ifdef TARGET_NR_lchown
8344     case TARGET_NR_lchown:
8345         if (!(p = lock_user_string(arg1)))
8346             goto efault;
8347         ret = get_errno(lchown(p, low2highuid(arg2), low2highgid(arg3)));
8348         unlock_user(p, arg1, 0);
8349         break;
8350 #endif
8351 #ifdef TARGET_NR_getuid
8352     case TARGET_NR_getuid:
8353         ret = get_errno(high2lowuid(getuid()));
8354         break;
8355 #endif
8356 #ifdef TARGET_NR_getgid
8357     case TARGET_NR_getgid:
8358         ret = get_errno(high2lowgid(getgid()));
8359         break;
8360 #endif
8361 #ifdef TARGET_NR_geteuid
8362     case TARGET_NR_geteuid:
8363         ret = get_errno(high2lowuid(geteuid()));
8364         break;
8365 #endif
8366 #ifdef TARGET_NR_getegid
8367     case TARGET_NR_getegid:
8368         ret = get_errno(high2lowgid(getegid()));
8369         break;
8370 #endif
8371     case TARGET_NR_setreuid:
8372         ret = get_errno(setreuid(low2highuid(arg1), low2highuid(arg2)));
8373         break;
8374     case TARGET_NR_setregid:
8375         ret = get_errno(setregid(low2highgid(arg1), low2highgid(arg2)));
8376         break;
8377     case TARGET_NR_getgroups:
8378         {
8379             int gidsetsize = arg1;
8380             target_id *target_grouplist;
8381             gid_t *grouplist;
8382             int i;
8383 
8384             grouplist = alloca(gidsetsize * sizeof(gid_t));
8385             ret = get_errno(getgroups(gidsetsize, grouplist));
8386             if (gidsetsize == 0)
8387                 break;
8388             if (!is_error(ret)) {
8389                 target_grouplist = lock_user(VERIFY_WRITE, arg2, gidsetsize * sizeof(target_id), 0);
8390                 if (!target_grouplist)
8391                     goto efault;
8392                 for(i = 0;i < ret; i++)
8393                     target_grouplist[i] = tswapid(high2lowgid(grouplist[i]));
8394                 unlock_user(target_grouplist, arg2, gidsetsize * sizeof(target_id));
8395             }
8396         }
8397         break;
8398     case TARGET_NR_setgroups:
8399         {
8400             int gidsetsize = arg1;
8401             target_id *target_grouplist;
8402             gid_t *grouplist = NULL;
8403             int i;
8404             if (gidsetsize) {
8405                 grouplist = alloca(gidsetsize * sizeof(gid_t));
8406                 target_grouplist = lock_user(VERIFY_READ, arg2, gidsetsize * sizeof(target_id), 1);
8407                 if (!target_grouplist) {
8408                     ret = -TARGET_EFAULT;
8409                     goto fail;
8410                 }
8411                 for (i = 0; i < gidsetsize; i++) {
8412                     grouplist[i] = low2highgid(tswapid(target_grouplist[i]));
8413                 }
8414                 unlock_user(target_grouplist, arg2, 0);
8415             }
8416             ret = get_errno(setgroups(gidsetsize, grouplist));
8417         }
8418         break;
8419     case TARGET_NR_fchown:
8420         ret = get_errno(fchown(arg1, low2highuid(arg2), low2highgid(arg3)));
8421         break;
8422 #if defined(TARGET_NR_fchownat)
8423     case TARGET_NR_fchownat:
8424         if (!(p = lock_user_string(arg2)))
8425             goto efault;
8426         ret = get_errno(fchownat(arg1, p, low2highuid(arg3),
8427                                  low2highgid(arg4), arg5));
8428         unlock_user(p, arg2, 0);
8429         break;
8430 #endif
8431 #ifdef TARGET_NR_setresuid
8432     case TARGET_NR_setresuid:
8433         ret = get_errno(setresuid(low2highuid(arg1),
8434                                   low2highuid(arg2),
8435                                   low2highuid(arg3)));
8436         break;
8437 #endif
8438 #ifdef TARGET_NR_getresuid
8439     case TARGET_NR_getresuid:
8440         {
8441             uid_t ruid, euid, suid;
8442             ret = get_errno(getresuid(&ruid, &euid, &suid));
8443             if (!is_error(ret)) {
8444                 if (put_user_id(high2lowuid(ruid), arg1)
8445                     || put_user_id(high2lowuid(euid), arg2)
8446                     || put_user_id(high2lowuid(suid), arg3))
8447                     goto efault;
8448             }
8449         }
8450         break;
8451 #endif
8452 #ifdef TARGET_NR_getresgid
8453     case TARGET_NR_setresgid:
8454         ret = get_errno(setresgid(low2highgid(arg1),
8455                                   low2highgid(arg2),
8456                                   low2highgid(arg3)));
8457         break;
8458 #endif
8459 #ifdef TARGET_NR_getresgid
8460     case TARGET_NR_getresgid:
8461         {
8462             gid_t rgid, egid, sgid;
8463             ret = get_errno(getresgid(&rgid, &egid, &sgid));
8464             if (!is_error(ret)) {
8465                 if (put_user_id(high2lowgid(rgid), arg1)
8466                     || put_user_id(high2lowgid(egid), arg2)
8467                     || put_user_id(high2lowgid(sgid), arg3))
8468                     goto efault;
8469             }
8470         }
8471         break;
8472 #endif
8473 #ifdef TARGET_NR_chown
8474     case TARGET_NR_chown:
8475         if (!(p = lock_user_string(arg1)))
8476             goto efault;
8477         ret = get_errno(chown(p, low2highuid(arg2), low2highgid(arg3)));
8478         unlock_user(p, arg1, 0);
8479         break;
8480 #endif
8481     case TARGET_NR_setuid:
8482         ret = get_errno(setuid(low2highuid(arg1)));
8483         break;
8484     case TARGET_NR_setgid:
8485         ret = get_errno(setgid(low2highgid(arg1)));
8486         break;
8487     case TARGET_NR_setfsuid:
8488         ret = get_errno(setfsuid(arg1));
8489         break;
8490     case TARGET_NR_setfsgid:
8491         ret = get_errno(setfsgid(arg1));
8492         break;
8493 
8494 #ifdef TARGET_NR_lchown32
8495     case TARGET_NR_lchown32:
8496         if (!(p = lock_user_string(arg1)))
8497             goto efault;
8498         ret = get_errno(lchown(p, arg2, arg3));
8499         unlock_user(p, arg1, 0);
8500         break;
8501 #endif
8502 #ifdef TARGET_NR_getuid32
8503     case TARGET_NR_getuid32:
8504         ret = get_errno(getuid());
8505         break;
8506 #endif
8507 
8508 #if defined(TARGET_NR_getxuid) && defined(TARGET_ALPHA)
8509    /* Alpha specific */
8510     case TARGET_NR_getxuid:
8511          {
8512             uid_t euid;
8513             euid=geteuid();
8514             ((CPUAlphaState *)cpu_env)->ir[IR_A4]=euid;
8515          }
8516         ret = get_errno(getuid());
8517         break;
8518 #endif
8519 #if defined(TARGET_NR_getxgid) && defined(TARGET_ALPHA)
8520    /* Alpha specific */
8521     case TARGET_NR_getxgid:
8522          {
8523             uid_t egid;
8524             egid=getegid();
8525             ((CPUAlphaState *)cpu_env)->ir[IR_A4]=egid;
8526          }
8527         ret = get_errno(getgid());
8528         break;
8529 #endif
8530 #if defined(TARGET_NR_osf_getsysinfo) && defined(TARGET_ALPHA)
8531     /* Alpha specific */
8532     case TARGET_NR_osf_getsysinfo:
8533         ret = -TARGET_EOPNOTSUPP;
8534         switch (arg1) {
8535           case TARGET_GSI_IEEE_FP_CONTROL:
8536             {
8537                 uint64_t swcr, fpcr = cpu_alpha_load_fpcr (cpu_env);
8538 
8539                 /* Copied from linux ieee_fpcr_to_swcr.  */
8540                 swcr = (fpcr >> 35) & SWCR_STATUS_MASK;
8541                 swcr |= (fpcr >> 36) & SWCR_MAP_DMZ;
8542                 swcr |= (~fpcr >> 48) & (SWCR_TRAP_ENABLE_INV
8543                                         | SWCR_TRAP_ENABLE_DZE
8544                                         | SWCR_TRAP_ENABLE_OVF);
8545                 swcr |= (~fpcr >> 57) & (SWCR_TRAP_ENABLE_UNF
8546                                         | SWCR_TRAP_ENABLE_INE);
8547                 swcr |= (fpcr >> 47) & SWCR_MAP_UMZ;
8548                 swcr |= (~fpcr >> 41) & SWCR_TRAP_ENABLE_DNO;
8549 
8550                 if (put_user_u64 (swcr, arg2))
8551                         goto efault;
8552                 ret = 0;
8553             }
8554             break;
8555 
8556           /* case GSI_IEEE_STATE_AT_SIGNAL:
8557              -- Not implemented in linux kernel.
8558              case GSI_UACPROC:
8559              -- Retrieves current unaligned access state; not much used.
8560              case GSI_PROC_TYPE:
8561              -- Retrieves implver information; surely not used.
8562              case GSI_GET_HWRPB:
8563              -- Grabs a copy of the HWRPB; surely not used.
8564           */
8565         }
8566         break;
8567 #endif
8568 #if defined(TARGET_NR_osf_setsysinfo) && defined(TARGET_ALPHA)
8569     /* Alpha specific */
8570     case TARGET_NR_osf_setsysinfo:
8571         ret = -TARGET_EOPNOTSUPP;
8572         switch (arg1) {
8573           case TARGET_SSI_IEEE_FP_CONTROL:
8574             {
8575                 uint64_t swcr, fpcr, orig_fpcr;
8576 
8577                 if (get_user_u64 (swcr, arg2)) {
8578                     goto efault;
8579                 }
8580                 orig_fpcr = cpu_alpha_load_fpcr(cpu_env);
8581                 fpcr = orig_fpcr & FPCR_DYN_MASK;
8582 
8583                 /* Copied from linux ieee_swcr_to_fpcr.  */
8584                 fpcr |= (swcr & SWCR_STATUS_MASK) << 35;
8585                 fpcr |= (swcr & SWCR_MAP_DMZ) << 36;
8586                 fpcr |= (~swcr & (SWCR_TRAP_ENABLE_INV
8587                                   | SWCR_TRAP_ENABLE_DZE
8588                                   | SWCR_TRAP_ENABLE_OVF)) << 48;
8589                 fpcr |= (~swcr & (SWCR_TRAP_ENABLE_UNF
8590                                   | SWCR_TRAP_ENABLE_INE)) << 57;
8591                 fpcr |= (swcr & SWCR_MAP_UMZ ? FPCR_UNDZ | FPCR_UNFD : 0);
8592                 fpcr |= (~swcr & SWCR_TRAP_ENABLE_DNO) << 41;
8593 
8594                 cpu_alpha_store_fpcr(cpu_env, fpcr);
8595                 ret = 0;
8596             }
8597             break;
8598 
8599           case TARGET_SSI_IEEE_RAISE_EXCEPTION:
8600             {
8601                 uint64_t exc, fpcr, orig_fpcr;
8602                 int si_code;
8603 
8604                 if (get_user_u64(exc, arg2)) {
8605                     goto efault;
8606                 }
8607 
8608                 orig_fpcr = cpu_alpha_load_fpcr(cpu_env);
8609 
8610                 /* We only add to the exception status here.  */
8611                 fpcr = orig_fpcr | ((exc & SWCR_STATUS_MASK) << 35);
8612 
8613                 cpu_alpha_store_fpcr(cpu_env, fpcr);
8614                 ret = 0;
8615 
8616                 /* Old exceptions are not signaled.  */
8617                 fpcr &= ~(orig_fpcr & FPCR_STATUS_MASK);
8618 
8619                 /* If any exceptions set by this call,
8620                    and are unmasked, send a signal.  */
8621                 si_code = 0;
8622                 if ((fpcr & (FPCR_INE | FPCR_INED)) == FPCR_INE) {
8623                     si_code = TARGET_FPE_FLTRES;
8624                 }
8625                 if ((fpcr & (FPCR_UNF | FPCR_UNFD)) == FPCR_UNF) {
8626                     si_code = TARGET_FPE_FLTUND;
8627                 }
8628                 if ((fpcr & (FPCR_OVF | FPCR_OVFD)) == FPCR_OVF) {
8629                     si_code = TARGET_FPE_FLTOVF;
8630                 }
8631                 if ((fpcr & (FPCR_DZE | FPCR_DZED)) == FPCR_DZE) {
8632                     si_code = TARGET_FPE_FLTDIV;
8633                 }
8634                 if ((fpcr & (FPCR_INV | FPCR_INVD)) == FPCR_INV) {
8635                     si_code = TARGET_FPE_FLTINV;
8636                 }
8637                 if (si_code != 0) {
8638                     target_siginfo_t info;
8639                     info.si_signo = SIGFPE;
8640                     info.si_errno = 0;
8641                     info.si_code = si_code;
8642                     info._sifields._sigfault._addr
8643                         = ((CPUArchState *)cpu_env)->pc;
8644                     queue_signal((CPUArchState *)cpu_env, info.si_signo, &info);
8645                 }
8646             }
8647             break;
8648 
8649           /* case SSI_NVPAIRS:
8650              -- Used with SSIN_UACPROC to enable unaligned accesses.
8651              case SSI_IEEE_STATE_AT_SIGNAL:
8652              case SSI_IEEE_IGNORE_STATE_AT_SIGNAL:
8653              -- Not implemented in linux kernel
8654           */
8655         }
8656         break;
8657 #endif
8658 #ifdef TARGET_NR_osf_sigprocmask
8659     /* Alpha specific.  */
8660     case TARGET_NR_osf_sigprocmask:
8661         {
8662             abi_ulong mask;
8663             int how;
8664             sigset_t set, oldset;
8665 
8666             switch(arg1) {
8667             case TARGET_SIG_BLOCK:
8668                 how = SIG_BLOCK;
8669                 break;
8670             case TARGET_SIG_UNBLOCK:
8671                 how = SIG_UNBLOCK;
8672                 break;
8673             case TARGET_SIG_SETMASK:
8674                 how = SIG_SETMASK;
8675                 break;
8676             default:
8677                 ret = -TARGET_EINVAL;
8678                 goto fail;
8679             }
8680             mask = arg2;
8681             target_to_host_old_sigset(&set, &mask);
8682             do_sigprocmask(how, &set, &oldset);
8683             host_to_target_old_sigset(&mask, &oldset);
8684             ret = mask;
8685         }
8686         break;
8687 #endif
8688 
8689 #ifdef TARGET_NR_getgid32
8690     case TARGET_NR_getgid32:
8691         ret = get_errno(getgid());
8692         break;
8693 #endif
8694 #ifdef TARGET_NR_geteuid32
8695     case TARGET_NR_geteuid32:
8696         ret = get_errno(geteuid());
8697         break;
8698 #endif
8699 #ifdef TARGET_NR_getegid32
8700     case TARGET_NR_getegid32:
8701         ret = get_errno(getegid());
8702         break;
8703 #endif
8704 #ifdef TARGET_NR_setreuid32
8705     case TARGET_NR_setreuid32:
8706         ret = get_errno(setreuid(arg1, arg2));
8707         break;
8708 #endif
8709 #ifdef TARGET_NR_setregid32
8710     case TARGET_NR_setregid32:
8711         ret = get_errno(setregid(arg1, arg2));
8712         break;
8713 #endif
8714 #ifdef TARGET_NR_getgroups32
8715     case TARGET_NR_getgroups32:
8716         {
8717             int gidsetsize = arg1;
8718             uint32_t *target_grouplist;
8719             gid_t *grouplist;
8720             int i;
8721 
8722             grouplist = alloca(gidsetsize * sizeof(gid_t));
8723             ret = get_errno(getgroups(gidsetsize, grouplist));
8724             if (gidsetsize == 0)
8725                 break;
8726             if (!is_error(ret)) {
8727                 target_grouplist = lock_user(VERIFY_WRITE, arg2, gidsetsize * 4, 0);
8728                 if (!target_grouplist) {
8729                     ret = -TARGET_EFAULT;
8730                     goto fail;
8731                 }
8732                 for(i = 0;i < ret; i++)
8733                     target_grouplist[i] = tswap32(grouplist[i]);
8734                 unlock_user(target_grouplist, arg2, gidsetsize * 4);
8735             }
8736         }
8737         break;
8738 #endif
8739 #ifdef TARGET_NR_setgroups32
8740     case TARGET_NR_setgroups32:
8741         {
8742             int gidsetsize = arg1;
8743             uint32_t *target_grouplist;
8744             gid_t *grouplist;
8745             int i;
8746 
8747             grouplist = alloca(gidsetsize * sizeof(gid_t));
8748             target_grouplist = lock_user(VERIFY_READ, arg2, gidsetsize * 4, 1);
8749             if (!target_grouplist) {
8750                 ret = -TARGET_EFAULT;
8751                 goto fail;
8752             }
8753             for(i = 0;i < gidsetsize; i++)
8754                 grouplist[i] = tswap32(target_grouplist[i]);
8755             unlock_user(target_grouplist, arg2, 0);
8756             ret = get_errno(setgroups(gidsetsize, grouplist));
8757         }
8758         break;
8759 #endif
8760 #ifdef TARGET_NR_fchown32
8761     case TARGET_NR_fchown32:
8762         ret = get_errno(fchown(arg1, arg2, arg3));
8763         break;
8764 #endif
8765 #ifdef TARGET_NR_setresuid32
8766     case TARGET_NR_setresuid32:
8767         ret = get_errno(setresuid(arg1, arg2, arg3));
8768         break;
8769 #endif
8770 #ifdef TARGET_NR_getresuid32
8771     case TARGET_NR_getresuid32:
8772         {
8773             uid_t ruid, euid, suid;
8774             ret = get_errno(getresuid(&ruid, &euid, &suid));
8775             if (!is_error(ret)) {
8776                 if (put_user_u32(ruid, arg1)
8777                     || put_user_u32(euid, arg2)
8778                     || put_user_u32(suid, arg3))
8779                     goto efault;
8780             }
8781         }
8782         break;
8783 #endif
8784 #ifdef TARGET_NR_setresgid32
8785     case TARGET_NR_setresgid32:
8786         ret = get_errno(setresgid(arg1, arg2, arg3));
8787         break;
8788 #endif
8789 #ifdef TARGET_NR_getresgid32
8790     case TARGET_NR_getresgid32:
8791         {
8792             gid_t rgid, egid, sgid;
8793             ret = get_errno(getresgid(&rgid, &egid, &sgid));
8794             if (!is_error(ret)) {
8795                 if (put_user_u32(rgid, arg1)
8796                     || put_user_u32(egid, arg2)
8797                     || put_user_u32(sgid, arg3))
8798                     goto efault;
8799             }
8800         }
8801         break;
8802 #endif
8803 #ifdef TARGET_NR_chown32
8804     case TARGET_NR_chown32:
8805         if (!(p = lock_user_string(arg1)))
8806             goto efault;
8807         ret = get_errno(chown(p, arg2, arg3));
8808         unlock_user(p, arg1, 0);
8809         break;
8810 #endif
8811 #ifdef TARGET_NR_setuid32
8812     case TARGET_NR_setuid32:
8813         ret = get_errno(setuid(arg1));
8814         break;
8815 #endif
8816 #ifdef TARGET_NR_setgid32
8817     case TARGET_NR_setgid32:
8818         ret = get_errno(setgid(arg1));
8819         break;
8820 #endif
8821 #ifdef TARGET_NR_setfsuid32
8822     case TARGET_NR_setfsuid32:
8823         ret = get_errno(setfsuid(arg1));
8824         break;
8825 #endif
8826 #ifdef TARGET_NR_setfsgid32
8827     case TARGET_NR_setfsgid32:
8828         ret = get_errno(setfsgid(arg1));
8829         break;
8830 #endif
8831 
8832     case TARGET_NR_pivot_root:
8833         goto unimplemented;
8834 #ifdef TARGET_NR_mincore
8835     case TARGET_NR_mincore:
8836         {
8837             void *a;
8838             ret = -TARGET_EFAULT;
8839             if (!(a = lock_user(VERIFY_READ, arg1,arg2, 0)))
8840                 goto efault;
8841             if (!(p = lock_user_string(arg3)))
8842                 goto mincore_fail;
8843             ret = get_errno(mincore(a, arg2, p));
8844             unlock_user(p, arg3, ret);
8845             mincore_fail:
8846             unlock_user(a, arg1, 0);
8847         }
8848         break;
8849 #endif
8850 #ifdef TARGET_NR_arm_fadvise64_64
8851     case TARGET_NR_arm_fadvise64_64:
8852 	{
8853 		/*
8854 		 * arm_fadvise64_64 looks like fadvise64_64 but
8855 		 * with different argument order
8856 		 */
8857 		abi_long temp;
8858 		temp = arg3;
8859 		arg3 = arg4;
8860 		arg4 = temp;
8861 	}
8862 #endif
8863 #if defined(TARGET_NR_fadvise64_64) || defined(TARGET_NR_arm_fadvise64_64) || defined(TARGET_NR_fadvise64)
8864 #ifdef TARGET_NR_fadvise64_64
8865     case TARGET_NR_fadvise64_64:
8866 #endif
8867 #ifdef TARGET_NR_fadvise64
8868     case TARGET_NR_fadvise64:
8869 #endif
8870 #ifdef TARGET_S390X
8871         switch (arg4) {
8872         case 4: arg4 = POSIX_FADV_NOREUSE + 1; break; /* make sure it's an invalid value */
8873         case 5: arg4 = POSIX_FADV_NOREUSE + 2; break; /* ditto */
8874         case 6: arg4 = POSIX_FADV_DONTNEED; break;
8875         case 7: arg4 = POSIX_FADV_NOREUSE; break;
8876         default: break;
8877         }
8878 #endif
8879         ret = -posix_fadvise(arg1, arg2, arg3, arg4);
8880 	break;
8881 #endif
8882 #ifdef TARGET_NR_madvise
8883     case TARGET_NR_madvise:
8884         /* A straight passthrough may not be safe because qemu sometimes
8885            turns private file-backed mappings into anonymous mappings.
8886            This will break MADV_DONTNEED.
8887            This is a hint, so ignoring and returning success is ok.  */
8888         ret = get_errno(0);
8889         break;
8890 #endif
8891 #if TARGET_ABI_BITS == 32
8892     case TARGET_NR_fcntl64:
8893     {
8894 	int cmd;
8895 	struct flock64 fl;
8896 	struct target_flock64 *target_fl;
8897 #ifdef TARGET_ARM
8898 	struct target_eabi_flock64 *target_efl;
8899 #endif
8900 
8901 	cmd = target_to_host_fcntl_cmd(arg2);
8902         if (cmd == -TARGET_EINVAL) {
8903             ret = cmd;
8904             break;
8905         }
8906 
8907         switch(arg2) {
8908         case TARGET_F_GETLK64:
8909 #ifdef TARGET_ARM
8910             if (((CPUARMState *)cpu_env)->eabi) {
8911                 if (!lock_user_struct(VERIFY_READ, target_efl, arg3, 1))
8912                     goto efault;
8913                 fl.l_type = tswap16(target_efl->l_type);
8914                 fl.l_whence = tswap16(target_efl->l_whence);
8915                 fl.l_start = tswap64(target_efl->l_start);
8916                 fl.l_len = tswap64(target_efl->l_len);
8917                 fl.l_pid = tswap32(target_efl->l_pid);
8918                 unlock_user_struct(target_efl, arg3, 0);
8919             } else
8920 #endif
8921             {
8922                 if (!lock_user_struct(VERIFY_READ, target_fl, arg3, 1))
8923                     goto efault;
8924                 fl.l_type = tswap16(target_fl->l_type);
8925                 fl.l_whence = tswap16(target_fl->l_whence);
8926                 fl.l_start = tswap64(target_fl->l_start);
8927                 fl.l_len = tswap64(target_fl->l_len);
8928                 fl.l_pid = tswap32(target_fl->l_pid);
8929                 unlock_user_struct(target_fl, arg3, 0);
8930             }
8931             ret = get_errno(fcntl(arg1, cmd, &fl));
8932 	    if (ret == 0) {
8933 #ifdef TARGET_ARM
8934                 if (((CPUARMState *)cpu_env)->eabi) {
8935                     if (!lock_user_struct(VERIFY_WRITE, target_efl, arg3, 0))
8936                         goto efault;
8937                     target_efl->l_type = tswap16(fl.l_type);
8938                     target_efl->l_whence = tswap16(fl.l_whence);
8939                     target_efl->l_start = tswap64(fl.l_start);
8940                     target_efl->l_len = tswap64(fl.l_len);
8941                     target_efl->l_pid = tswap32(fl.l_pid);
8942                     unlock_user_struct(target_efl, arg3, 1);
8943                 } else
8944 #endif
8945                 {
8946                     if (!lock_user_struct(VERIFY_WRITE, target_fl, arg3, 0))
8947                         goto efault;
8948                     target_fl->l_type = tswap16(fl.l_type);
8949                     target_fl->l_whence = tswap16(fl.l_whence);
8950                     target_fl->l_start = tswap64(fl.l_start);
8951                     target_fl->l_len = tswap64(fl.l_len);
8952                     target_fl->l_pid = tswap32(fl.l_pid);
8953                     unlock_user_struct(target_fl, arg3, 1);
8954                 }
8955 	    }
8956 	    break;
8957 
8958         case TARGET_F_SETLK64:
8959         case TARGET_F_SETLKW64:
8960 #ifdef TARGET_ARM
8961             if (((CPUARMState *)cpu_env)->eabi) {
8962                 if (!lock_user_struct(VERIFY_READ, target_efl, arg3, 1))
8963                     goto efault;
8964                 fl.l_type = tswap16(target_efl->l_type);
8965                 fl.l_whence = tswap16(target_efl->l_whence);
8966                 fl.l_start = tswap64(target_efl->l_start);
8967                 fl.l_len = tswap64(target_efl->l_len);
8968                 fl.l_pid = tswap32(target_efl->l_pid);
8969                 unlock_user_struct(target_efl, arg3, 0);
8970             } else
8971 #endif
8972             {
8973                 if (!lock_user_struct(VERIFY_READ, target_fl, arg3, 1))
8974                     goto efault;
8975                 fl.l_type = tswap16(target_fl->l_type);
8976                 fl.l_whence = tswap16(target_fl->l_whence);
8977                 fl.l_start = tswap64(target_fl->l_start);
8978                 fl.l_len = tswap64(target_fl->l_len);
8979                 fl.l_pid = tswap32(target_fl->l_pid);
8980                 unlock_user_struct(target_fl, arg3, 0);
8981             }
8982             ret = get_errno(fcntl(arg1, cmd, &fl));
8983 	    break;
8984         default:
8985             ret = do_fcntl(arg1, arg2, arg3);
8986             break;
8987         }
8988 	break;
8989     }
8990 #endif
8991 #ifdef TARGET_NR_cacheflush
8992     case TARGET_NR_cacheflush:
8993         /* self-modifying code is handled automatically, so nothing needed */
8994         ret = 0;
8995         break;
8996 #endif
8997 #ifdef TARGET_NR_security
8998     case TARGET_NR_security:
8999         goto unimplemented;
9000 #endif
9001 #ifdef TARGET_NR_getpagesize
9002     case TARGET_NR_getpagesize:
9003         ret = TARGET_PAGE_SIZE;
9004         break;
9005 #endif
9006     case TARGET_NR_gettid:
9007         ret = get_errno(gettid());
9008         break;
9009 #ifdef TARGET_NR_readahead
9010     case TARGET_NR_readahead:
9011 #if TARGET_ABI_BITS == 32
9012         if (regpairs_aligned(cpu_env)) {
9013             arg2 = arg3;
9014             arg3 = arg4;
9015             arg4 = arg5;
9016         }
9017         ret = get_errno(readahead(arg1, ((off64_t)arg3 << 32) | arg2, arg4));
9018 #else
9019         ret = get_errno(readahead(arg1, arg2, arg3));
9020 #endif
9021         break;
9022 #endif
9023 #ifdef CONFIG_ATTR
9024 #ifdef TARGET_NR_setxattr
9025     case TARGET_NR_listxattr:
9026     case TARGET_NR_llistxattr:
9027     {
9028         void *p, *b = 0;
9029         if (arg2) {
9030             b = lock_user(VERIFY_WRITE, arg2, arg3, 0);
9031             if (!b) {
9032                 ret = -TARGET_EFAULT;
9033                 break;
9034             }
9035         }
9036         p = lock_user_string(arg1);
9037         if (p) {
9038             if (num == TARGET_NR_listxattr) {
9039                 ret = get_errno(listxattr(p, b, arg3));
9040             } else {
9041                 ret = get_errno(llistxattr(p, b, arg3));
9042             }
9043         } else {
9044             ret = -TARGET_EFAULT;
9045         }
9046         unlock_user(p, arg1, 0);
9047         unlock_user(b, arg2, arg3);
9048         break;
9049     }
9050     case TARGET_NR_flistxattr:
9051     {
9052         void *b = 0;
9053         if (arg2) {
9054             b = lock_user(VERIFY_WRITE, arg2, arg3, 0);
9055             if (!b) {
9056                 ret = -TARGET_EFAULT;
9057                 break;
9058             }
9059         }
9060         ret = get_errno(flistxattr(arg1, b, arg3));
9061         unlock_user(b, arg2, arg3);
9062         break;
9063     }
9064     case TARGET_NR_setxattr:
9065     case TARGET_NR_lsetxattr:
9066         {
9067             void *p, *n, *v = 0;
9068             if (arg3) {
9069                 v = lock_user(VERIFY_READ, arg3, arg4, 1);
9070                 if (!v) {
9071                     ret = -TARGET_EFAULT;
9072                     break;
9073                 }
9074             }
9075             p = lock_user_string(arg1);
9076             n = lock_user_string(arg2);
9077             if (p && n) {
9078                 if (num == TARGET_NR_setxattr) {
9079                     ret = get_errno(setxattr(p, n, v, arg4, arg5));
9080                 } else {
9081                     ret = get_errno(lsetxattr(p, n, v, arg4, arg5));
9082                 }
9083             } else {
9084                 ret = -TARGET_EFAULT;
9085             }
9086             unlock_user(p, arg1, 0);
9087             unlock_user(n, arg2, 0);
9088             unlock_user(v, arg3, 0);
9089         }
9090         break;
9091     case TARGET_NR_fsetxattr:
9092         {
9093             void *n, *v = 0;
9094             if (arg3) {
9095                 v = lock_user(VERIFY_READ, arg3, arg4, 1);
9096                 if (!v) {
9097                     ret = -TARGET_EFAULT;
9098                     break;
9099                 }
9100             }
9101             n = lock_user_string(arg2);
9102             if (n) {
9103                 ret = get_errno(fsetxattr(arg1, n, v, arg4, arg5));
9104             } else {
9105                 ret = -TARGET_EFAULT;
9106             }
9107             unlock_user(n, arg2, 0);
9108             unlock_user(v, arg3, 0);
9109         }
9110         break;
9111     case TARGET_NR_getxattr:
9112     case TARGET_NR_lgetxattr:
9113         {
9114             void *p, *n, *v = 0;
9115             if (arg3) {
9116                 v = lock_user(VERIFY_WRITE, arg3, arg4, 0);
9117                 if (!v) {
9118                     ret = -TARGET_EFAULT;
9119                     break;
9120                 }
9121             }
9122             p = lock_user_string(arg1);
9123             n = lock_user_string(arg2);
9124             if (p && n) {
9125                 if (num == TARGET_NR_getxattr) {
9126                     ret = get_errno(getxattr(p, n, v, arg4));
9127                 } else {
9128                     ret = get_errno(lgetxattr(p, n, v, arg4));
9129                 }
9130             } else {
9131                 ret = -TARGET_EFAULT;
9132             }
9133             unlock_user(p, arg1, 0);
9134             unlock_user(n, arg2, 0);
9135             unlock_user(v, arg3, arg4);
9136         }
9137         break;
9138     case TARGET_NR_fgetxattr:
9139         {
9140             void *n, *v = 0;
9141             if (arg3) {
9142                 v = lock_user(VERIFY_WRITE, arg3, arg4, 0);
9143                 if (!v) {
9144                     ret = -TARGET_EFAULT;
9145                     break;
9146                 }
9147             }
9148             n = lock_user_string(arg2);
9149             if (n) {
9150                 ret = get_errno(fgetxattr(arg1, n, v, arg4));
9151             } else {
9152                 ret = -TARGET_EFAULT;
9153             }
9154             unlock_user(n, arg2, 0);
9155             unlock_user(v, arg3, arg4);
9156         }
9157         break;
9158     case TARGET_NR_removexattr:
9159     case TARGET_NR_lremovexattr:
9160         {
9161             void *p, *n;
9162             p = lock_user_string(arg1);
9163             n = lock_user_string(arg2);
9164             if (p && n) {
9165                 if (num == TARGET_NR_removexattr) {
9166                     ret = get_errno(removexattr(p, n));
9167                 } else {
9168                     ret = get_errno(lremovexattr(p, n));
9169                 }
9170             } else {
9171                 ret = -TARGET_EFAULT;
9172             }
9173             unlock_user(p, arg1, 0);
9174             unlock_user(n, arg2, 0);
9175         }
9176         break;
9177     case TARGET_NR_fremovexattr:
9178         {
9179             void *n;
9180             n = lock_user_string(arg2);
9181             if (n) {
9182                 ret = get_errno(fremovexattr(arg1, n));
9183             } else {
9184                 ret = -TARGET_EFAULT;
9185             }
9186             unlock_user(n, arg2, 0);
9187         }
9188         break;
9189 #endif
9190 #endif /* CONFIG_ATTR */
9191 #ifdef TARGET_NR_set_thread_area
9192     case TARGET_NR_set_thread_area:
9193 #if defined(TARGET_MIPS)
9194       ((CPUMIPSState *) cpu_env)->active_tc.CP0_UserLocal = arg1;
9195       ret = 0;
9196       break;
9197 #elif defined(TARGET_CRIS)
9198       if (arg1 & 0xff)
9199           ret = -TARGET_EINVAL;
9200       else {
9201           ((CPUCRISState *) cpu_env)->pregs[PR_PID] = arg1;
9202           ret = 0;
9203       }
9204       break;
9205 #elif defined(TARGET_I386) && defined(TARGET_ABI32)
9206       ret = do_set_thread_area(cpu_env, arg1);
9207       break;
9208 #elif defined(TARGET_M68K)
9209       {
9210           TaskState *ts = cpu->opaque;
9211           ts->tp_value = arg1;
9212           ret = 0;
9213           break;
9214       }
9215 #else
9216       goto unimplemented_nowarn;
9217 #endif
9218 #endif
9219 #ifdef TARGET_NR_get_thread_area
9220     case TARGET_NR_get_thread_area:
9221 #if defined(TARGET_I386) && defined(TARGET_ABI32)
9222         ret = do_get_thread_area(cpu_env, arg1);
9223         break;
9224 #elif defined(TARGET_M68K)
9225         {
9226             TaskState *ts = cpu->opaque;
9227             ret = ts->tp_value;
9228             break;
9229         }
9230 #else
9231         goto unimplemented_nowarn;
9232 #endif
9233 #endif
9234 #ifdef TARGET_NR_getdomainname
9235     case TARGET_NR_getdomainname:
9236         goto unimplemented_nowarn;
9237 #endif
9238 
9239 #ifdef TARGET_NR_clock_gettime
9240     case TARGET_NR_clock_gettime:
9241     {
9242         struct timespec ts;
9243         ret = get_errno(clock_gettime(arg1, &ts));
9244         if (!is_error(ret)) {
9245             host_to_target_timespec(arg2, &ts);
9246         }
9247         break;
9248     }
9249 #endif
9250 #ifdef TARGET_NR_clock_getres
9251     case TARGET_NR_clock_getres:
9252     {
9253         struct timespec ts;
9254         ret = get_errno(clock_getres(arg1, &ts));
9255         if (!is_error(ret)) {
9256             host_to_target_timespec(arg2, &ts);
9257         }
9258         break;
9259     }
9260 #endif
9261 #ifdef TARGET_NR_clock_nanosleep
9262     case TARGET_NR_clock_nanosleep:
9263     {
9264         struct timespec ts;
9265         target_to_host_timespec(&ts, arg3);
9266         ret = get_errno(clock_nanosleep(arg1, arg2, &ts, arg4 ? &ts : NULL));
9267         if (arg4)
9268             host_to_target_timespec(arg4, &ts);
9269 
9270 #if defined(TARGET_PPC)
9271         /* clock_nanosleep is odd in that it returns positive errno values.
9272          * On PPC, CR0 bit 3 should be set in such a situation. */
9273         if (ret) {
9274             ((CPUPPCState *)cpu_env)->crf[0] |= 1;
9275         }
9276 #endif
9277         break;
9278     }
9279 #endif
9280 
9281 #if defined(TARGET_NR_set_tid_address) && defined(__NR_set_tid_address)
9282     case TARGET_NR_set_tid_address:
9283         ret = get_errno(set_tid_address((int *)g2h(arg1)));
9284         break;
9285 #endif
9286 
9287 #if defined(TARGET_NR_tkill) && defined(__NR_tkill)
9288     case TARGET_NR_tkill:
9289         ret = get_errno(sys_tkill((int)arg1, target_to_host_signal(arg2)));
9290         break;
9291 #endif
9292 
9293 #if defined(TARGET_NR_tgkill) && defined(__NR_tgkill)
9294     case TARGET_NR_tgkill:
9295 	ret = get_errno(sys_tgkill((int)arg1, (int)arg2,
9296                         target_to_host_signal(arg3)));
9297 	break;
9298 #endif
9299 
9300 #ifdef TARGET_NR_set_robust_list
9301     case TARGET_NR_set_robust_list:
9302     case TARGET_NR_get_robust_list:
9303         /* The ABI for supporting robust futexes has userspace pass
9304          * the kernel a pointer to a linked list which is updated by
9305          * userspace after the syscall; the list is walked by the kernel
9306          * when the thread exits. Since the linked list in QEMU guest
9307          * memory isn't a valid linked list for the host and we have
9308          * no way to reliably intercept the thread-death event, we can't
9309          * support these. Silently return ENOSYS so that guest userspace
9310          * falls back to a non-robust futex implementation (which should
9311          * be OK except in the corner case of the guest crashing while
9312          * holding a mutex that is shared with another process via
9313          * shared memory).
9314          */
9315         goto unimplemented_nowarn;
9316 #endif
9317 
9318 #if defined(TARGET_NR_utimensat)
9319     case TARGET_NR_utimensat:
9320         {
9321             struct timespec *tsp, ts[2];
9322             if (!arg3) {
9323                 tsp = NULL;
9324             } else {
9325                 target_to_host_timespec(ts, arg3);
9326                 target_to_host_timespec(ts+1, arg3+sizeof(struct target_timespec));
9327                 tsp = ts;
9328             }
9329             if (!arg2)
9330                 ret = get_errno(sys_utimensat(arg1, NULL, tsp, arg4));
9331             else {
9332                 if (!(p = lock_user_string(arg2))) {
9333                     ret = -TARGET_EFAULT;
9334                     goto fail;
9335                 }
9336                 ret = get_errno(sys_utimensat(arg1, path(p), tsp, arg4));
9337                 unlock_user(p, arg2, 0);
9338             }
9339         }
9340 	break;
9341 #endif
9342     case TARGET_NR_futex:
9343         ret = do_futex(arg1, arg2, arg3, arg4, arg5, arg6);
9344         break;
9345 #if defined(TARGET_NR_inotify_init) && defined(__NR_inotify_init)
9346     case TARGET_NR_inotify_init:
9347         ret = get_errno(sys_inotify_init());
9348         break;
9349 #endif
9350 #ifdef CONFIG_INOTIFY1
9351 #if defined(TARGET_NR_inotify_init1) && defined(__NR_inotify_init1)
9352     case TARGET_NR_inotify_init1:
9353         ret = get_errno(sys_inotify_init1(arg1));
9354         break;
9355 #endif
9356 #endif
9357 #if defined(TARGET_NR_inotify_add_watch) && defined(__NR_inotify_add_watch)
9358     case TARGET_NR_inotify_add_watch:
9359         p = lock_user_string(arg2);
9360         ret = get_errno(sys_inotify_add_watch(arg1, path(p), arg3));
9361         unlock_user(p, arg2, 0);
9362         break;
9363 #endif
9364 #if defined(TARGET_NR_inotify_rm_watch) && defined(__NR_inotify_rm_watch)
9365     case TARGET_NR_inotify_rm_watch:
9366         ret = get_errno(sys_inotify_rm_watch(arg1, arg2));
9367         break;
9368 #endif
9369 
9370 #if defined(TARGET_NR_mq_open) && defined(__NR_mq_open)
9371     case TARGET_NR_mq_open:
9372         {
9373             struct mq_attr posix_mq_attr, *attrp;
9374 
9375             p = lock_user_string(arg1 - 1);
9376             if (arg4 != 0) {
9377                 copy_from_user_mq_attr (&posix_mq_attr, arg4);
9378                 attrp = &posix_mq_attr;
9379             } else {
9380                 attrp = 0;
9381             }
9382             ret = get_errno(mq_open(p, arg2, arg3, attrp));
9383             unlock_user (p, arg1, 0);
9384         }
9385         break;
9386 
9387     case TARGET_NR_mq_unlink:
9388         p = lock_user_string(arg1 - 1);
9389         ret = get_errno(mq_unlink(p));
9390         unlock_user (p, arg1, 0);
9391         break;
9392 
9393     case TARGET_NR_mq_timedsend:
9394         {
9395             struct timespec ts;
9396 
9397             p = lock_user (VERIFY_READ, arg2, arg3, 1);
9398             if (arg5 != 0) {
9399                 target_to_host_timespec(&ts, arg5);
9400                 ret = get_errno(mq_timedsend(arg1, p, arg3, arg4, &ts));
9401                 host_to_target_timespec(arg5, &ts);
9402             }
9403             else
9404                 ret = get_errno(mq_send(arg1, p, arg3, arg4));
9405             unlock_user (p, arg2, arg3);
9406         }
9407         break;
9408 
9409     case TARGET_NR_mq_timedreceive:
9410         {
9411             struct timespec ts;
9412             unsigned int prio;
9413 
9414             p = lock_user (VERIFY_READ, arg2, arg3, 1);
9415             if (arg5 != 0) {
9416                 target_to_host_timespec(&ts, arg5);
9417                 ret = get_errno(mq_timedreceive(arg1, p, arg3, &prio, &ts));
9418                 host_to_target_timespec(arg5, &ts);
9419             }
9420             else
9421                 ret = get_errno(mq_receive(arg1, p, arg3, &prio));
9422             unlock_user (p, arg2, arg3);
9423             if (arg4 != 0)
9424                 put_user_u32(prio, arg4);
9425         }
9426         break;
9427 
9428     /* Not implemented for now... */
9429 /*     case TARGET_NR_mq_notify: */
9430 /*         break; */
9431 
9432     case TARGET_NR_mq_getsetattr:
9433         {
9434             struct mq_attr posix_mq_attr_in, posix_mq_attr_out;
9435             ret = 0;
9436             if (arg3 != 0) {
9437                 ret = mq_getattr(arg1, &posix_mq_attr_out);
9438                 copy_to_user_mq_attr(arg3, &posix_mq_attr_out);
9439             }
9440             if (arg2 != 0) {
9441                 copy_from_user_mq_attr(&posix_mq_attr_in, arg2);
9442                 ret |= mq_setattr(arg1, &posix_mq_attr_in, &posix_mq_attr_out);
9443             }
9444 
9445         }
9446         break;
9447 #endif
9448 
9449 #ifdef CONFIG_SPLICE
9450 #ifdef TARGET_NR_tee
9451     case TARGET_NR_tee:
9452         {
9453             ret = get_errno(tee(arg1,arg2,arg3,arg4));
9454         }
9455         break;
9456 #endif
9457 #ifdef TARGET_NR_splice
9458     case TARGET_NR_splice:
9459         {
9460             loff_t loff_in, loff_out;
9461             loff_t *ploff_in = NULL, *ploff_out = NULL;
9462             if (arg2) {
9463                 if (get_user_u64(loff_in, arg2)) {
9464                     goto efault;
9465                 }
9466                 ploff_in = &loff_in;
9467             }
9468             if (arg4) {
9469                 if (get_user_u64(loff_out, arg4)) {
9470                     goto efault;
9471                 }
9472                 ploff_out = &loff_out;
9473             }
9474             ret = get_errno(splice(arg1, ploff_in, arg3, ploff_out, arg5, arg6));
9475             if (arg2) {
9476                 if (put_user_u64(loff_in, arg2)) {
9477                     goto efault;
9478                 }
9479             }
9480             if (arg4) {
9481                 if (put_user_u64(loff_out, arg4)) {
9482                     goto efault;
9483                 }
9484             }
9485         }
9486         break;
9487 #endif
9488 #ifdef TARGET_NR_vmsplice
9489 	case TARGET_NR_vmsplice:
9490         {
9491             struct iovec *vec = lock_iovec(VERIFY_READ, arg2, arg3, 1);
9492             if (vec != NULL) {
9493                 ret = get_errno(vmsplice(arg1, vec, arg3, arg4));
9494                 unlock_iovec(vec, arg2, arg3, 0);
9495             } else {
9496                 ret = -host_to_target_errno(errno);
9497             }
9498         }
9499         break;
9500 #endif
9501 #endif /* CONFIG_SPLICE */
9502 #ifdef CONFIG_EVENTFD
9503 #if defined(TARGET_NR_eventfd)
9504     case TARGET_NR_eventfd:
9505         ret = get_errno(eventfd(arg1, 0));
9506         break;
9507 #endif
9508 #if defined(TARGET_NR_eventfd2)
9509     case TARGET_NR_eventfd2:
9510     {
9511         int host_flags = arg2 & (~(TARGET_O_NONBLOCK | TARGET_O_CLOEXEC));
9512         if (arg2 & TARGET_O_NONBLOCK) {
9513             host_flags |= O_NONBLOCK;
9514         }
9515         if (arg2 & TARGET_O_CLOEXEC) {
9516             host_flags |= O_CLOEXEC;
9517         }
9518         ret = get_errno(eventfd(arg1, host_flags));
9519         break;
9520     }
9521 #endif
9522 #endif /* CONFIG_EVENTFD  */
9523 #if defined(CONFIG_FALLOCATE) && defined(TARGET_NR_fallocate)
9524     case TARGET_NR_fallocate:
9525 #if TARGET_ABI_BITS == 32
9526         ret = get_errno(fallocate(arg1, arg2, target_offset64(arg3, arg4),
9527                                   target_offset64(arg5, arg6)));
9528 #else
9529         ret = get_errno(fallocate(arg1, arg2, arg3, arg4));
9530 #endif
9531         break;
9532 #endif
9533 #if defined(CONFIG_SYNC_FILE_RANGE)
9534 #if defined(TARGET_NR_sync_file_range)
9535     case TARGET_NR_sync_file_range:
9536 #if TARGET_ABI_BITS == 32
9537 #if defined(TARGET_MIPS)
9538         ret = get_errno(sync_file_range(arg1, target_offset64(arg3, arg4),
9539                                         target_offset64(arg5, arg6), arg7));
9540 #else
9541         ret = get_errno(sync_file_range(arg1, target_offset64(arg2, arg3),
9542                                         target_offset64(arg4, arg5), arg6));
9543 #endif /* !TARGET_MIPS */
9544 #else
9545         ret = get_errno(sync_file_range(arg1, arg2, arg3, arg4));
9546 #endif
9547         break;
9548 #endif
9549 #if defined(TARGET_NR_sync_file_range2)
9550     case TARGET_NR_sync_file_range2:
9551         /* This is like sync_file_range but the arguments are reordered */
9552 #if TARGET_ABI_BITS == 32
9553         ret = get_errno(sync_file_range(arg1, target_offset64(arg3, arg4),
9554                                         target_offset64(arg5, arg6), arg2));
9555 #else
9556         ret = get_errno(sync_file_range(arg1, arg3, arg4, arg2));
9557 #endif
9558         break;
9559 #endif
9560 #endif
9561 #if defined(CONFIG_EPOLL)
9562 #if defined(TARGET_NR_epoll_create)
9563     case TARGET_NR_epoll_create:
9564         ret = get_errno(epoll_create(arg1));
9565         break;
9566 #endif
9567 #if defined(TARGET_NR_epoll_create1) && defined(CONFIG_EPOLL_CREATE1)
9568     case TARGET_NR_epoll_create1:
9569         ret = get_errno(epoll_create1(arg1));
9570         break;
9571 #endif
9572 #if defined(TARGET_NR_epoll_ctl)
9573     case TARGET_NR_epoll_ctl:
9574     {
9575         struct epoll_event ep;
9576         struct epoll_event *epp = 0;
9577         if (arg4) {
9578             struct target_epoll_event *target_ep;
9579             if (!lock_user_struct(VERIFY_READ, target_ep, arg4, 1)) {
9580                 goto efault;
9581             }
9582             ep.events = tswap32(target_ep->events);
9583             /* The epoll_data_t union is just opaque data to the kernel,
9584              * so we transfer all 64 bits across and need not worry what
9585              * actual data type it is.
9586              */
9587             ep.data.u64 = tswap64(target_ep->data.u64);
9588             unlock_user_struct(target_ep, arg4, 0);
9589             epp = &ep;
9590         }
9591         ret = get_errno(epoll_ctl(arg1, arg2, arg3, epp));
9592         break;
9593     }
9594 #endif
9595 
9596 #if defined(TARGET_NR_epoll_pwait) && defined(CONFIG_EPOLL_PWAIT)
9597 #define IMPLEMENT_EPOLL_PWAIT
9598 #endif
9599 #if defined(TARGET_NR_epoll_wait) || defined(IMPLEMENT_EPOLL_PWAIT)
9600 #if defined(TARGET_NR_epoll_wait)
9601     case TARGET_NR_epoll_wait:
9602 #endif
9603 #if defined(IMPLEMENT_EPOLL_PWAIT)
9604     case TARGET_NR_epoll_pwait:
9605 #endif
9606     {
9607         struct target_epoll_event *target_ep;
9608         struct epoll_event *ep;
9609         int epfd = arg1;
9610         int maxevents = arg3;
9611         int timeout = arg4;
9612 
9613         target_ep = lock_user(VERIFY_WRITE, arg2,
9614                               maxevents * sizeof(struct target_epoll_event), 1);
9615         if (!target_ep) {
9616             goto efault;
9617         }
9618 
9619         ep = alloca(maxevents * sizeof(struct epoll_event));
9620 
9621         switch (num) {
9622 #if defined(IMPLEMENT_EPOLL_PWAIT)
9623         case TARGET_NR_epoll_pwait:
9624         {
9625             target_sigset_t *target_set;
9626             sigset_t _set, *set = &_set;
9627 
9628             if (arg5) {
9629                 target_set = lock_user(VERIFY_READ, arg5,
9630                                        sizeof(target_sigset_t), 1);
9631                 if (!target_set) {
9632                     unlock_user(target_ep, arg2, 0);
9633                     goto efault;
9634                 }
9635                 target_to_host_sigset(set, target_set);
9636                 unlock_user(target_set, arg5, 0);
9637             } else {
9638                 set = NULL;
9639             }
9640 
9641             ret = get_errno(epoll_pwait(epfd, ep, maxevents, timeout, set));
9642             break;
9643         }
9644 #endif
9645 #if defined(TARGET_NR_epoll_wait)
9646         case TARGET_NR_epoll_wait:
9647             ret = get_errno(epoll_wait(epfd, ep, maxevents, timeout));
9648             break;
9649 #endif
9650         default:
9651             ret = -TARGET_ENOSYS;
9652         }
9653         if (!is_error(ret)) {
9654             int i;
9655             for (i = 0; i < ret; i++) {
9656                 target_ep[i].events = tswap32(ep[i].events);
9657                 target_ep[i].data.u64 = tswap64(ep[i].data.u64);
9658             }
9659         }
9660         unlock_user(target_ep, arg2, ret * sizeof(struct target_epoll_event));
9661         break;
9662     }
9663 #endif
9664 #endif
9665 #ifdef TARGET_NR_prlimit64
9666     case TARGET_NR_prlimit64:
9667     {
9668         /* args: pid, resource number, ptr to new rlimit, ptr to old rlimit */
9669         struct target_rlimit64 *target_rnew, *target_rold;
9670         struct host_rlimit64 rnew, rold, *rnewp = 0;
9671         int resource = target_to_host_resource(arg2);
9672         if (arg3) {
9673             if (!lock_user_struct(VERIFY_READ, target_rnew, arg3, 1)) {
9674                 goto efault;
9675             }
9676             rnew.rlim_cur = tswap64(target_rnew->rlim_cur);
9677             rnew.rlim_max = tswap64(target_rnew->rlim_max);
9678             unlock_user_struct(target_rnew, arg3, 0);
9679             rnewp = &rnew;
9680         }
9681 
9682         ret = get_errno(sys_prlimit64(arg1, resource, rnewp, arg4 ? &rold : 0));
9683         if (!is_error(ret) && arg4) {
9684             if (!lock_user_struct(VERIFY_WRITE, target_rold, arg4, 1)) {
9685                 goto efault;
9686             }
9687             target_rold->rlim_cur = tswap64(rold.rlim_cur);
9688             target_rold->rlim_max = tswap64(rold.rlim_max);
9689             unlock_user_struct(target_rold, arg4, 1);
9690         }
9691         break;
9692     }
9693 #endif
9694 #ifdef TARGET_NR_gethostname
9695     case TARGET_NR_gethostname:
9696     {
9697         char *name = lock_user(VERIFY_WRITE, arg1, arg2, 0);
9698         if (name) {
9699             ret = get_errno(gethostname(name, arg2));
9700             unlock_user(name, arg1, arg2);
9701         } else {
9702             ret = -TARGET_EFAULT;
9703         }
9704         break;
9705     }
9706 #endif
9707 #ifdef TARGET_NR_atomic_cmpxchg_32
9708     case TARGET_NR_atomic_cmpxchg_32:
9709     {
9710         /* should use start_exclusive from main.c */
9711         abi_ulong mem_value;
9712         if (get_user_u32(mem_value, arg6)) {
9713             target_siginfo_t info;
9714             info.si_signo = SIGSEGV;
9715             info.si_errno = 0;
9716             info.si_code = TARGET_SEGV_MAPERR;
9717             info._sifields._sigfault._addr = arg6;
9718             queue_signal((CPUArchState *)cpu_env, info.si_signo, &info);
9719             ret = 0xdeadbeef;
9720 
9721         }
9722         if (mem_value == arg2)
9723             put_user_u32(arg1, arg6);
9724         ret = mem_value;
9725         break;
9726     }
9727 #endif
9728 #ifdef TARGET_NR_atomic_barrier
9729     case TARGET_NR_atomic_barrier:
9730     {
9731         /* Like the kernel implementation and the qemu arm barrier, no-op this? */
9732         ret = 0;
9733         break;
9734     }
9735 #endif
9736 
9737 #ifdef TARGET_NR_timer_create
9738     case TARGET_NR_timer_create:
9739     {
9740         /* args: clockid_t clockid, struct sigevent *sevp, timer_t *timerid */
9741 
9742         struct sigevent host_sevp = { {0}, }, *phost_sevp = NULL;
9743 
9744         int clkid = arg1;
9745         int timer_index = next_free_host_timer();
9746 
9747         if (timer_index < 0) {
9748             ret = -TARGET_EAGAIN;
9749         } else {
9750             timer_t *phtimer = g_posix_timers  + timer_index;
9751 
9752             if (arg2) {
9753                 phost_sevp = &host_sevp;
9754                 ret = target_to_host_sigevent(phost_sevp, arg2);
9755                 if (ret != 0) {
9756                     break;
9757                 }
9758             }
9759 
9760             ret = get_errno(timer_create(clkid, phost_sevp, phtimer));
9761             if (ret) {
9762                 phtimer = NULL;
9763             } else {
9764                 if (put_user(TIMER_MAGIC | timer_index, arg3, target_timer_t)) {
9765                     goto efault;
9766                 }
9767             }
9768         }
9769         break;
9770     }
9771 #endif
9772 
9773 #ifdef TARGET_NR_timer_settime
9774     case TARGET_NR_timer_settime:
9775     {
9776         /* args: timer_t timerid, int flags, const struct itimerspec *new_value,
9777          * struct itimerspec * old_value */
9778         target_timer_t timerid = get_timer_id(arg1);
9779 
9780         if (timerid < 0) {
9781             ret = timerid;
9782         } else if (arg3 == 0) {
9783             ret = -TARGET_EINVAL;
9784         } else {
9785             timer_t htimer = g_posix_timers[timerid];
9786             struct itimerspec hspec_new = {{0},}, hspec_old = {{0},};
9787 
9788             target_to_host_itimerspec(&hspec_new, arg3);
9789             ret = get_errno(
9790                           timer_settime(htimer, arg2, &hspec_new, &hspec_old));
9791             host_to_target_itimerspec(arg2, &hspec_old);
9792         }
9793         break;
9794     }
9795 #endif
9796 
9797 #ifdef TARGET_NR_timer_gettime
9798     case TARGET_NR_timer_gettime:
9799     {
9800         /* args: timer_t timerid, struct itimerspec *curr_value */
9801         target_timer_t timerid = get_timer_id(arg1);
9802 
9803         if (timerid < 0) {
9804             ret = timerid;
9805         } else if (!arg2) {
9806             ret = -TARGET_EFAULT;
9807         } else {
9808             timer_t htimer = g_posix_timers[timerid];
9809             struct itimerspec hspec;
9810             ret = get_errno(timer_gettime(htimer, &hspec));
9811 
9812             if (host_to_target_itimerspec(arg2, &hspec)) {
9813                 ret = -TARGET_EFAULT;
9814             }
9815         }
9816         break;
9817     }
9818 #endif
9819 
9820 #ifdef TARGET_NR_timer_getoverrun
9821     case TARGET_NR_timer_getoverrun:
9822     {
9823         /* args: timer_t timerid */
9824         target_timer_t timerid = get_timer_id(arg1);
9825 
9826         if (timerid < 0) {
9827             ret = timerid;
9828         } else {
9829             timer_t htimer = g_posix_timers[timerid];
9830             ret = get_errno(timer_getoverrun(htimer));
9831         }
9832         break;
9833     }
9834 #endif
9835 
9836 #ifdef TARGET_NR_timer_delete
9837     case TARGET_NR_timer_delete:
9838     {
9839         /* args: timer_t timerid */
9840         target_timer_t timerid = get_timer_id(arg1);
9841 
9842         if (timerid < 0) {
9843             ret = timerid;
9844         } else {
9845             timer_t htimer = g_posix_timers[timerid];
9846             ret = get_errno(timer_delete(htimer));
9847             g_posix_timers[timerid] = 0;
9848         }
9849         break;
9850     }
9851 #endif
9852 
9853 #if defined(TARGET_NR_timerfd_create) && defined(CONFIG_TIMERFD)
9854     case TARGET_NR_timerfd_create:
9855         ret = get_errno(timerfd_create(arg1,
9856                 target_to_host_bitmask(arg2, fcntl_flags_tbl)));
9857         break;
9858 #endif
9859 
9860 #if defined(TARGET_NR_timerfd_gettime) && defined(CONFIG_TIMERFD)
9861     case TARGET_NR_timerfd_gettime:
9862         {
9863             struct itimerspec its_curr;
9864 
9865             ret = get_errno(timerfd_gettime(arg1, &its_curr));
9866 
9867             if (arg2 && host_to_target_itimerspec(arg2, &its_curr)) {
9868                 goto efault;
9869             }
9870         }
9871         break;
9872 #endif
9873 
9874 #if defined(TARGET_NR_timerfd_settime) && defined(CONFIG_TIMERFD)
9875     case TARGET_NR_timerfd_settime:
9876         {
9877             struct itimerspec its_new, its_old, *p_new;
9878 
9879             if (arg3) {
9880                 if (target_to_host_itimerspec(&its_new, arg3)) {
9881                     goto efault;
9882                 }
9883                 p_new = &its_new;
9884             } else {
9885                 p_new = NULL;
9886             }
9887 
9888             ret = get_errno(timerfd_settime(arg1, arg2, p_new, &its_old));
9889 
9890             if (arg4 && host_to_target_itimerspec(arg4, &its_old)) {
9891                 goto efault;
9892             }
9893         }
9894         break;
9895 #endif
9896 
9897 #if defined(TARGET_NR_ioprio_get) && defined(__NR_ioprio_get)
9898     case TARGET_NR_ioprio_get:
9899         ret = get_errno(ioprio_get(arg1, arg2));
9900         break;
9901 #endif
9902 
9903 #if defined(TARGET_NR_ioprio_set) && defined(__NR_ioprio_set)
9904     case TARGET_NR_ioprio_set:
9905         ret = get_errno(ioprio_set(arg1, arg2, arg3));
9906         break;
9907 #endif
9908 
9909 #if defined(TARGET_NR_setns) && defined(CONFIG_SETNS)
9910     case TARGET_NR_setns:
9911         ret = get_errno(setns(arg1, arg2));
9912         break;
9913 #endif
9914 #if defined(TARGET_NR_unshare) && defined(CONFIG_SETNS)
9915     case TARGET_NR_unshare:
9916         ret = get_errno(unshare(arg1));
9917         break;
9918 #endif
9919 
9920     default:
9921     unimplemented:
9922         gemu_log("qemu: Unsupported syscall: %d\n", num);
9923 #if defined(TARGET_NR_setxattr) || defined(TARGET_NR_get_thread_area) || defined(TARGET_NR_getdomainname) || defined(TARGET_NR_set_robust_list)
9924     unimplemented_nowarn:
9925 #endif
9926         ret = -TARGET_ENOSYS;
9927         break;
9928     }
9929 fail:
9930 #ifdef DEBUG
9931     gemu_log(" = " TARGET_ABI_FMT_ld "\n", ret);
9932 #endif
9933     if(do_strace)
9934         print_syscall_ret(num, ret);
9935     return ret;
9936 efault:
9937     ret = -TARGET_EFAULT;
9938     goto fail;
9939 }
9940