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