qemu/linux-user/syscall.c
<<
>>
Prefs
   1/*
   2 *  Linux syscalls
   3 *
   4 *  Copyright (c) 2003 Fabrice Bellard
   5 *
   6 *  This program is free software; you can redistribute it and/or modify
   7 *  it under the terms of the GNU General Public License as published by
   8 *  the Free Software Foundation; either version 2 of the License, or
   9 *  (at your option) any later version.
  10 *
  11 *  This program is distributed in the hope that it will be useful,
  12 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  13 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14 *  GNU General Public License for more details.
  15 *
  16 *  You should have received a copy of the GNU General Public License
  17 *  along with this program; if not, see <http://www.gnu.org/licenses/>.
  18 */
  19#define _ATFILE_SOURCE
  20#include "qemu/osdep.h"
  21#include "qemu/cutils.h"
  22#include "qemu/path.h"
  23#include <elf.h>
  24#include <endian.h>
  25#include <grp.h>
  26#include <sys/ipc.h>
  27#include <sys/msg.h>
  28#include <sys/wait.h>
  29#include <sys/mount.h>
  30#include <sys/file.h>
  31#include <sys/fsuid.h>
  32#include <sys/personality.h>
  33#include <sys/prctl.h>
  34#include <sys/resource.h>
  35#include <sys/swap.h>
  36#include <linux/capability.h>
  37#include <sched.h>
  38#include <sys/timex.h>
  39#include <sys/socket.h>
  40#include <linux/sockios.h>
  41#include <sys/un.h>
  42#include <sys/uio.h>
  43#include <poll.h>
  44#include <sys/times.h>
  45#include <sys/shm.h>
  46#include <sys/sem.h>
  47#include <sys/statfs.h>
  48#include <utime.h>
  49#include <sys/sysinfo.h>
  50#include <sys/signalfd.h>
  51//#include <sys/user.h>
  52#include <netinet/ip.h>
  53#include <netinet/tcp.h>
  54#include <linux/wireless.h>
  55#include <linux/icmp.h>
  56#include <linux/icmpv6.h>
  57#include <linux/errqueue.h>
  58#include <linux/random.h>
  59#ifdef CONFIG_TIMERFD
  60#include <sys/timerfd.h>
  61#endif
  62#ifdef CONFIG_EVENTFD
  63#include <sys/eventfd.h>
  64#endif
  65#ifdef CONFIG_EPOLL
  66#include <sys/epoll.h>
  67#endif
  68#ifdef CONFIG_ATTR
  69#include "qemu/xattr.h"
  70#endif
  71#ifdef CONFIG_SENDFILE
  72#include <sys/sendfile.h>
  73#endif
  74
  75#define termios host_termios
  76#define winsize host_winsize
  77#define termio host_termio
  78#define sgttyb host_sgttyb /* same as target */
  79#define tchars host_tchars /* same as target */
  80#define ltchars host_ltchars /* same as target */
  81
  82#include <linux/termios.h>
  83#include <linux/unistd.h>
  84#include <linux/cdrom.h>
  85#include <linux/hdreg.h>
  86#include <linux/soundcard.h>
  87#include <linux/kd.h>
  88#include <linux/mtio.h>
  89#include <linux/fs.h>
  90#if defined(CONFIG_FIEMAP)
  91#include <linux/fiemap.h>
  92#endif
  93#include <linux/fb.h>
  94#if defined(CONFIG_USBFS)
  95#include <linux/usbdevice_fs.h>
  96#include <linux/usb/ch9.h>
  97#endif
  98#include <linux/vt.h>
  99#include <linux/dm-ioctl.h>
 100#include <linux/reboot.h>
 101#include <linux/route.h>
 102#include <linux/filter.h>
 103#include <linux/blkpg.h>
 104#include <netpacket/packet.h>
 105#include <linux/netlink.h>
 106#include <linux/if_alg.h>
 107#include "linux_loop.h"
 108#include "uname.h"
 109
 110#include "qemu.h"
 111#include "qemu/guest-random.h"
 112#include "qapi/error.h"
 113#include "fd-trans.h"
 114
 115#ifndef CLONE_IO
 116#define CLONE_IO                0x80000000      /* Clone io context */
 117#endif
 118
 119/* We can't directly call the host clone syscall, because this will
 120 * badly confuse libc (breaking mutexes, for example). So we must
 121 * divide clone flags into:
 122 *  * flag combinations that look like pthread_create()
 123 *  * flag combinations that look like fork()
 124 *  * flags we can implement within QEMU itself
 125 *  * flags we can't support and will return an error for
 126 */
 127/* For thread creation, all these flags must be present; for
 128 * fork, none must be present.
 129 */
 130#define CLONE_THREAD_FLAGS                              \
 131    (CLONE_VM | CLONE_FS | CLONE_FILES |                \
 132     CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM)
 133
 134/* These flags are ignored:
 135 * CLONE_DETACHED is now ignored by the kernel;
 136 * CLONE_IO is just an optimisation hint to the I/O scheduler
 137 */
 138#define CLONE_IGNORED_FLAGS                     \
 139    (CLONE_DETACHED | CLONE_IO)
 140
 141/* Flags for fork which we can implement within QEMU itself */
 142#define CLONE_OPTIONAL_FORK_FLAGS               \
 143    (CLONE_SETTLS | CLONE_PARENT_SETTID |       \
 144     CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID)
 145
 146/* Flags for thread creation which we can implement within QEMU itself */
 147#define CLONE_OPTIONAL_THREAD_FLAGS                             \
 148    (CLONE_SETTLS | CLONE_PARENT_SETTID |                       \
 149     CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID | CLONE_PARENT)
 150
 151#define CLONE_INVALID_FORK_FLAGS                                        \
 152    (~(CSIGNAL | CLONE_OPTIONAL_FORK_FLAGS | CLONE_IGNORED_FLAGS))
 153
 154#define CLONE_INVALID_THREAD_FLAGS                                      \
 155    (~(CSIGNAL | CLONE_THREAD_FLAGS | CLONE_OPTIONAL_THREAD_FLAGS |     \
 156       CLONE_IGNORED_FLAGS))
 157
 158/* CLONE_VFORK is special cased early in do_fork(). The other flag bits
 159 * have almost all been allocated. We cannot support any of
 160 * CLONE_NEWNS, CLONE_NEWCGROUP, CLONE_NEWUTS, CLONE_NEWIPC,
 161 * CLONE_NEWUSER, CLONE_NEWPID, CLONE_NEWNET, CLONE_PTRACE, CLONE_UNTRACED.
 162 * The checks against the invalid thread masks above will catch these.
 163 * (The one remaining unallocated bit is 0x1000 which used to be CLONE_PID.)
 164 */
 165
 166/* Define DEBUG_ERESTARTSYS to force every syscall to be restarted
 167 * once. This exercises the codepaths for restart.
 168 */
 169//#define DEBUG_ERESTARTSYS
 170
 171//#include <linux/msdos_fs.h>
 172#define VFAT_IOCTL_READDIR_BOTH         _IOR('r', 1, struct linux_dirent [2])
 173#define VFAT_IOCTL_READDIR_SHORT        _IOR('r', 2, struct linux_dirent [2])
 174
 175#undef _syscall0
 176#undef _syscall1
 177#undef _syscall2
 178#undef _syscall3
 179#undef _syscall4
 180#undef _syscall5
 181#undef _syscall6
 182
 183#define _syscall0(type,name)            \
 184static type name (void)                 \
 185{                                       \
 186        return syscall(__NR_##name);    \
 187}
 188
 189#define _syscall1(type,name,type1,arg1)         \
 190static type name (type1 arg1)                   \
 191{                                               \
 192        return syscall(__NR_##name, arg1);      \
 193}
 194
 195#define _syscall2(type,name,type1,arg1,type2,arg2)      \
 196static type name (type1 arg1,type2 arg2)                \
 197{                                                       \
 198        return syscall(__NR_##name, arg1, arg2);        \
 199}
 200
 201#define _syscall3(type,name,type1,arg1,type2,arg2,type3,arg3)   \
 202static type name (type1 arg1,type2 arg2,type3 arg3)             \
 203{                                                               \
 204        return syscall(__NR_##name, arg1, arg2, arg3);          \
 205}
 206
 207#define _syscall4(type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4)        \
 208static type name (type1 arg1,type2 arg2,type3 arg3,type4 arg4)                  \
 209{                                                                               \
 210        return syscall(__NR_##name, arg1, arg2, arg3, arg4);                    \
 211}
 212
 213#define _syscall5(type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4,        \
 214                  type5,arg5)                                                   \
 215static type name (type1 arg1,type2 arg2,type3 arg3,type4 arg4,type5 arg5)       \
 216{                                                                               \
 217        return syscall(__NR_##name, arg1, arg2, arg3, arg4, arg5);              \
 218}
 219
 220
 221#define _syscall6(type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4,        \
 222                  type5,arg5,type6,arg6)                                        \
 223static type name (type1 arg1,type2 arg2,type3 arg3,type4 arg4,type5 arg5,       \
 224                  type6 arg6)                                                   \
 225{                                                                               \
 226        return syscall(__NR_##name, arg1, arg2, arg3, arg4, arg5, arg6);        \
 227}
 228
 229
 230#define __NR_sys_uname __NR_uname
 231#define __NR_sys_getcwd1 __NR_getcwd
 232#define __NR_sys_getdents __NR_getdents
 233#define __NR_sys_getdents64 __NR_getdents64
 234#define __NR_sys_getpriority __NR_getpriority
 235#define __NR_sys_rt_sigqueueinfo __NR_rt_sigqueueinfo
 236#define __NR_sys_rt_tgsigqueueinfo __NR_rt_tgsigqueueinfo
 237#define __NR_sys_syslog __NR_syslog
 238#define __NR_sys_futex __NR_futex
 239#define __NR_sys_inotify_init __NR_inotify_init
 240#define __NR_sys_inotify_add_watch __NR_inotify_add_watch
 241#define __NR_sys_inotify_rm_watch __NR_inotify_rm_watch
 242#define __NR_sys_statx __NR_statx
 243
 244#if defined(__alpha__) || defined(__x86_64__) || defined(__s390x__)
 245#define __NR__llseek __NR_lseek
 246#endif
 247
 248/* Newer kernel ports have llseek() instead of _llseek() */
 249#if defined(TARGET_NR_llseek) && !defined(TARGET_NR__llseek)
 250#define TARGET_NR__llseek TARGET_NR_llseek
 251#endif
 252
 253#define __NR_sys_gettid __NR_gettid
 254_syscall0(int, sys_gettid)
 255
 256/* For the 64-bit guest on 32-bit host case we must emulate
 257 * getdents using getdents64, because otherwise the host
 258 * might hand us back more dirent records than we can fit
 259 * into the guest buffer after structure format conversion.
 260 * Otherwise we emulate getdents with getdents if the host has it.
 261 */
 262#if defined(__NR_getdents) && HOST_LONG_BITS >= TARGET_ABI_BITS
 263#define EMULATE_GETDENTS_WITH_GETDENTS
 264#endif
 265
 266#if defined(TARGET_NR_getdents) && defined(EMULATE_GETDENTS_WITH_GETDENTS)
 267_syscall3(int, sys_getdents, uint, fd, struct linux_dirent *, dirp, uint, count);
 268#endif
 269#if (defined(TARGET_NR_getdents) && \
 270      !defined(EMULATE_GETDENTS_WITH_GETDENTS)) || \
 271    (defined(TARGET_NR_getdents64) && defined(__NR_getdents64))
 272_syscall3(int, sys_getdents64, uint, fd, struct linux_dirent64 *, dirp, uint, count);
 273#endif
 274#if defined(TARGET_NR__llseek) && defined(__NR_llseek)
 275_syscall5(int, _llseek,  uint,  fd, ulong, hi, ulong, lo,
 276          loff_t *, res, uint, wh);
 277#endif
 278_syscall3(int, sys_rt_sigqueueinfo, pid_t, pid, int, sig, siginfo_t *, uinfo)
 279_syscall4(int, sys_rt_tgsigqueueinfo, pid_t, pid, pid_t, tid, int, sig,
 280          siginfo_t *, uinfo)
 281_syscall3(int,sys_syslog,int,type,char*,bufp,int,len)
 282#ifdef __NR_exit_group
 283_syscall1(int,exit_group,int,error_code)
 284#endif
 285#if defined(TARGET_NR_set_tid_address) && defined(__NR_set_tid_address)
 286_syscall1(int,set_tid_address,int *,tidptr)
 287#endif
 288#if defined(TARGET_NR_futex) && defined(__NR_futex)
 289_syscall6(int,sys_futex,int *,uaddr,int,op,int,val,
 290          const struct timespec *,timeout,int *,uaddr2,int,val3)
 291#endif
 292#define __NR_sys_sched_getaffinity __NR_sched_getaffinity
 293_syscall3(int, sys_sched_getaffinity, pid_t, pid, unsigned int, len,
 294          unsigned long *, user_mask_ptr);
 295#define __NR_sys_sched_setaffinity __NR_sched_setaffinity
 296_syscall3(int, sys_sched_setaffinity, pid_t, pid, unsigned int, len,
 297          unsigned long *, user_mask_ptr);
 298#define __NR_sys_getcpu __NR_getcpu
 299_syscall3(int, sys_getcpu, unsigned *, cpu, unsigned *, node, void *, tcache);
 300_syscall4(int, reboot, int, magic1, int, magic2, unsigned int, cmd,
 301          void *, arg);
 302_syscall2(int, capget, struct __user_cap_header_struct *, header,
 303          struct __user_cap_data_struct *, data);
 304_syscall2(int, capset, struct __user_cap_header_struct *, header,
 305          struct __user_cap_data_struct *, data);
 306#if defined(TARGET_NR_ioprio_get) && defined(__NR_ioprio_get)
 307_syscall2(int, ioprio_get, int, which, int, who)
 308#endif
 309#if defined(TARGET_NR_ioprio_set) && defined(__NR_ioprio_set)
 310_syscall3(int, ioprio_set, int, which, int, who, int, ioprio)
 311#endif
 312#if defined(TARGET_NR_getrandom) && defined(__NR_getrandom)
 313_syscall3(int, getrandom, void *, buf, size_t, buflen, unsigned int, flags)
 314#endif
 315
 316#if defined(TARGET_NR_kcmp) && defined(__NR_kcmp)
 317_syscall5(int, kcmp, pid_t, pid1, pid_t, pid2, int, type,
 318          unsigned long, idx1, unsigned long, idx2)
 319#endif
 320
 321/*
 322 * It is assumed that struct statx is architecture independent.
 323 */
 324#if defined(TARGET_NR_statx) && defined(__NR_statx)
 325_syscall5(int, sys_statx, int, dirfd, const char *, pathname, int, flags,
 326          unsigned int, mask, struct target_statx *, statxbuf)
 327#endif
 328
 329static bitmask_transtbl fcntl_flags_tbl[] = {
 330  { TARGET_O_ACCMODE,   TARGET_O_WRONLY,    O_ACCMODE,   O_WRONLY,    },
 331  { TARGET_O_ACCMODE,   TARGET_O_RDWR,      O_ACCMODE,   O_RDWR,      },
 332  { TARGET_O_CREAT,     TARGET_O_CREAT,     O_CREAT,     O_CREAT,     },
 333  { TARGET_O_EXCL,      TARGET_O_EXCL,      O_EXCL,      O_EXCL,      },
 334  { TARGET_O_NOCTTY,    TARGET_O_NOCTTY,    O_NOCTTY,    O_NOCTTY,    },
 335  { TARGET_O_TRUNC,     TARGET_O_TRUNC,     O_TRUNC,     O_TRUNC,     },
 336  { TARGET_O_APPEND,    TARGET_O_APPEND,    O_APPEND,    O_APPEND,    },
 337  { TARGET_O_NONBLOCK,  TARGET_O_NONBLOCK,  O_NONBLOCK,  O_NONBLOCK,  },
 338  { TARGET_O_SYNC,      TARGET_O_DSYNC,     O_SYNC,      O_DSYNC,     },
 339  { TARGET_O_SYNC,      TARGET_O_SYNC,      O_SYNC,      O_SYNC,      },
 340  { TARGET_FASYNC,      TARGET_FASYNC,      FASYNC,      FASYNC,      },
 341  { TARGET_O_DIRECTORY, TARGET_O_DIRECTORY, O_DIRECTORY, O_DIRECTORY, },
 342  { TARGET_O_NOFOLLOW,  TARGET_O_NOFOLLOW,  O_NOFOLLOW,  O_NOFOLLOW,  },
 343#if defined(O_DIRECT)
 344  { TARGET_O_DIRECT,    TARGET_O_DIRECT,    O_DIRECT,    O_DIRECT,    },
 345#endif
 346#if defined(O_NOATIME)
 347  { TARGET_O_NOATIME,   TARGET_O_NOATIME,   O_NOATIME,   O_NOATIME    },
 348#endif
 349#if defined(O_CLOEXEC)
 350  { TARGET_O_CLOEXEC,   TARGET_O_CLOEXEC,   O_CLOEXEC,   O_CLOEXEC    },
 351#endif
 352#if defined(O_PATH)
 353  { TARGET_O_PATH,      TARGET_O_PATH,      O_PATH,      O_PATH       },
 354#endif
 355#if defined(O_TMPFILE)
 356  { TARGET_O_TMPFILE,   TARGET_O_TMPFILE,   O_TMPFILE,   O_TMPFILE    },
 357#endif
 358  /* Don't terminate the list prematurely on 64-bit host+guest.  */
 359#if TARGET_O_LARGEFILE != 0 || O_LARGEFILE != 0
 360  { TARGET_O_LARGEFILE, TARGET_O_LARGEFILE, O_LARGEFILE, O_LARGEFILE, },
 361#endif
 362  { 0, 0, 0, 0 }
 363};
 364
 365static int sys_getcwd1(char *buf, size_t size)
 366{
 367  if (getcwd(buf, size) == NULL) {
 368      /* getcwd() sets errno */
 369      return (-1);
 370  }
 371  return strlen(buf)+1;
 372}
 373
 374#ifdef TARGET_NR_utimensat
 375#if defined(__NR_utimensat)
 376#define __NR_sys_utimensat __NR_utimensat
 377_syscall4(int,sys_utimensat,int,dirfd,const char *,pathname,
 378          const struct timespec *,tsp,int,flags)
 379#else
 380static int sys_utimensat(int dirfd, const char *pathname,
 381                         const struct timespec times[2], int flags)
 382{
 383    errno = ENOSYS;
 384    return -1;
 385}
 386#endif
 387#endif /* TARGET_NR_utimensat */
 388
 389#ifdef TARGET_NR_renameat2
 390#if defined(__NR_renameat2)
 391#define __NR_sys_renameat2 __NR_renameat2
 392_syscall5(int, sys_renameat2, int, oldfd, const char *, old, int, newfd,
 393          const char *, new, unsigned int, flags)
 394#else
 395static int sys_renameat2(int oldfd, const char *old,
 396                         int newfd, const char *new, int flags)
 397{
 398    if (flags == 0) {
 399        return renameat(oldfd, old, newfd, new);
 400    }
 401    errno = ENOSYS;
 402    return -1;
 403}
 404#endif
 405#endif /* TARGET_NR_renameat2 */
 406
 407#ifdef CONFIG_INOTIFY
 408#include <sys/inotify.h>
 409
 410#if defined(TARGET_NR_inotify_init) && defined(__NR_inotify_init)
 411static int sys_inotify_init(void)
 412{
 413  return (inotify_init());
 414}
 415#endif
 416#if defined(TARGET_NR_inotify_add_watch) && defined(__NR_inotify_add_watch)
 417static int sys_inotify_add_watch(int fd,const char *pathname, int32_t mask)
 418{
 419  return (inotify_add_watch(fd, pathname, mask));
 420}
 421#endif
 422#if defined(TARGET_NR_inotify_rm_watch) && defined(__NR_inotify_rm_watch)
 423static int sys_inotify_rm_watch(int fd, int32_t wd)
 424{
 425  return (inotify_rm_watch(fd, wd));
 426}
 427#endif
 428#ifdef CONFIG_INOTIFY1
 429#if defined(TARGET_NR_inotify_init1) && defined(__NR_inotify_init1)
 430static int sys_inotify_init1(int flags)
 431{
 432  return (inotify_init1(flags));
 433}
 434#endif
 435#endif
 436#else
 437/* Userspace can usually survive runtime without inotify */
 438#undef TARGET_NR_inotify_init
 439#undef TARGET_NR_inotify_init1
 440#undef TARGET_NR_inotify_add_watch
 441#undef TARGET_NR_inotify_rm_watch
 442#endif /* CONFIG_INOTIFY  */
 443
 444#if defined(TARGET_NR_prlimit64)
 445#ifndef __NR_prlimit64
 446# define __NR_prlimit64 -1
 447#endif
 448#define __NR_sys_prlimit64 __NR_prlimit64
 449/* The glibc rlimit structure may not be that used by the underlying syscall */
 450struct host_rlimit64 {
 451    uint64_t rlim_cur;
 452    uint64_t rlim_max;
 453};
 454_syscall4(int, sys_prlimit64, pid_t, pid, int, resource,
 455          const struct host_rlimit64 *, new_limit,
 456          struct host_rlimit64 *, old_limit)
 457#endif
 458
 459
 460#if defined(TARGET_NR_timer_create)
 461/* Maxiumum of 32 active POSIX timers allowed at any one time. */
 462static timer_t g_posix_timers[32] = { 0, } ;
 463
 464static inline int next_free_host_timer(void)
 465{
 466    int k ;
 467    /* FIXME: Does finding the next free slot require a lock? */
 468    for (k = 0; k < ARRAY_SIZE(g_posix_timers); k++) {
 469        if (g_posix_timers[k] == 0) {
 470            g_posix_timers[k] = (timer_t) 1;
 471            return k;
 472        }
 473    }
 474    return -1;
 475}
 476#endif
 477
 478/* ARM EABI and MIPS expect 64bit types aligned even on pairs or registers */
 479#ifdef TARGET_ARM
 480static inline int regpairs_aligned(void *cpu_env, int num)
 481{
 482    return ((((CPUARMState *)cpu_env)->eabi) == 1) ;
 483}
 484#elif defined(TARGET_MIPS) && (TARGET_ABI_BITS == 32)
 485static inline int regpairs_aligned(void *cpu_env, int num) { return 1; }
 486#elif defined(TARGET_PPC) && !defined(TARGET_PPC64)
 487/* SysV AVI for PPC32 expects 64bit parameters to be passed on odd/even pairs
 488 * of registers which translates to the same as ARM/MIPS, because we start with
 489 * r3 as arg1 */
 490static inline int regpairs_aligned(void *cpu_env, int num) { return 1; }
 491#elif defined(TARGET_SH4)
 492/* SH4 doesn't align register pairs, except for p{read,write}64 */
 493static inline int regpairs_aligned(void *cpu_env, int num)
 494{
 495    switch (num) {
 496    case TARGET_NR_pread64:
 497    case TARGET_NR_pwrite64:
 498        return 1;
 499
 500    default:
 501        return 0;
 502    }
 503}
 504#elif defined(TARGET_XTENSA)
 505static inline int regpairs_aligned(void *cpu_env, int num) { return 1; }
 506#else
 507static inline int regpairs_aligned(void *cpu_env, int num) { return 0; }
 508#endif
 509
 510#define ERRNO_TABLE_SIZE 1200
 511
 512/* target_to_host_errno_table[] is initialized from
 513 * host_to_target_errno_table[] in syscall_init(). */
 514static uint16_t target_to_host_errno_table[ERRNO_TABLE_SIZE] = {
 515};
 516
 517/*
 518 * This list is the union of errno values overridden in asm-<arch>/errno.h
 519 * minus the errnos that are not actually generic to all archs.
 520 */
 521static uint16_t host_to_target_errno_table[ERRNO_TABLE_SIZE] = {
 522    [EAGAIN]            = TARGET_EAGAIN,
 523    [EIDRM]             = TARGET_EIDRM,
 524    [ECHRNG]            = TARGET_ECHRNG,
 525    [EL2NSYNC]          = TARGET_EL2NSYNC,
 526    [EL3HLT]            = TARGET_EL3HLT,
 527    [EL3RST]            = TARGET_EL3RST,
 528    [ELNRNG]            = TARGET_ELNRNG,
 529    [EUNATCH]           = TARGET_EUNATCH,
 530    [ENOCSI]            = TARGET_ENOCSI,
 531    [EL2HLT]            = TARGET_EL2HLT,
 532    [EDEADLK]           = TARGET_EDEADLK,
 533    [ENOLCK]            = TARGET_ENOLCK,
 534    [EBADE]             = TARGET_EBADE,
 535    [EBADR]             = TARGET_EBADR,
 536    [EXFULL]            = TARGET_EXFULL,
 537    [ENOANO]            = TARGET_ENOANO,
 538    [EBADRQC]           = TARGET_EBADRQC,
 539    [EBADSLT]           = TARGET_EBADSLT,
 540    [EBFONT]            = TARGET_EBFONT,
 541    [ENOSTR]            = TARGET_ENOSTR,
 542    [ENODATA]           = TARGET_ENODATA,
 543    [ETIME]             = TARGET_ETIME,
 544    [ENOSR]             = TARGET_ENOSR,
 545    [ENONET]            = TARGET_ENONET,
 546    [ENOPKG]            = TARGET_ENOPKG,
 547    [EREMOTE]           = TARGET_EREMOTE,
 548    [ENOLINK]           = TARGET_ENOLINK,
 549    [EADV]              = TARGET_EADV,
 550    [ESRMNT]            = TARGET_ESRMNT,
 551    [ECOMM]             = TARGET_ECOMM,
 552    [EPROTO]            = TARGET_EPROTO,
 553    [EDOTDOT]           = TARGET_EDOTDOT,
 554    [EMULTIHOP]         = TARGET_EMULTIHOP,
 555    [EBADMSG]           = TARGET_EBADMSG,
 556    [ENAMETOOLONG]      = TARGET_ENAMETOOLONG,
 557    [EOVERFLOW]         = TARGET_EOVERFLOW,
 558    [ENOTUNIQ]          = TARGET_ENOTUNIQ,
 559    [EBADFD]            = TARGET_EBADFD,
 560    [EREMCHG]           = TARGET_EREMCHG,
 561    [ELIBACC]           = TARGET_ELIBACC,
 562    [ELIBBAD]           = TARGET_ELIBBAD,
 563    [ELIBSCN]           = TARGET_ELIBSCN,
 564    [ELIBMAX]           = TARGET_ELIBMAX,
 565    [ELIBEXEC]          = TARGET_ELIBEXEC,
 566    [EILSEQ]            = TARGET_EILSEQ,
 567    [ENOSYS]            = TARGET_ENOSYS,
 568    [ELOOP]             = TARGET_ELOOP,
 569    [ERESTART]          = TARGET_ERESTART,
 570    [ESTRPIPE]          = TARGET_ESTRPIPE,
 571    [ENOTEMPTY]         = TARGET_ENOTEMPTY,
 572    [EUSERS]            = TARGET_EUSERS,
 573    [ENOTSOCK]          = TARGET_ENOTSOCK,
 574    [EDESTADDRREQ]      = TARGET_EDESTADDRREQ,
 575    [EMSGSIZE]          = TARGET_EMSGSIZE,
 576    [EPROTOTYPE]        = TARGET_EPROTOTYPE,
 577    [ENOPROTOOPT]       = TARGET_ENOPROTOOPT,
 578    [EPROTONOSUPPORT]   = TARGET_EPROTONOSUPPORT,
 579    [ESOCKTNOSUPPORT]   = TARGET_ESOCKTNOSUPPORT,
 580    [EOPNOTSUPP]        = TARGET_EOPNOTSUPP,
 581    [EPFNOSUPPORT]      = TARGET_EPFNOSUPPORT,
 582    [EAFNOSUPPORT]      = TARGET_EAFNOSUPPORT,
 583    [EADDRINUSE]        = TARGET_EADDRINUSE,
 584    [EADDRNOTAVAIL]     = TARGET_EADDRNOTAVAIL,
 585    [ENETDOWN]          = TARGET_ENETDOWN,
 586    [ENETUNREACH]       = TARGET_ENETUNREACH,
 587    [ENETRESET]         = TARGET_ENETRESET,
 588    [ECONNABORTED]      = TARGET_ECONNABORTED,
 589    [ECONNRESET]        = TARGET_ECONNRESET,
 590    [ENOBUFS]           = TARGET_ENOBUFS,
 591    [EISCONN]           = TARGET_EISCONN,
 592    [ENOTCONN]          = TARGET_ENOTCONN,
 593    [EUCLEAN]           = TARGET_EUCLEAN,
 594    [ENOTNAM]           = TARGET_ENOTNAM,
 595    [ENAVAIL]           = TARGET_ENAVAIL,
 596    [EISNAM]            = TARGET_EISNAM,
 597    [EREMOTEIO]         = TARGET_EREMOTEIO,
 598    [EDQUOT]            = TARGET_EDQUOT,
 599    [ESHUTDOWN]         = TARGET_ESHUTDOWN,
 600    [ETOOMANYREFS]      = TARGET_ETOOMANYREFS,
 601    [ETIMEDOUT]         = TARGET_ETIMEDOUT,
 602    [ECONNREFUSED]      = TARGET_ECONNREFUSED,
 603    [EHOSTDOWN]         = TARGET_EHOSTDOWN,
 604    [EHOSTUNREACH]      = TARGET_EHOSTUNREACH,
 605    [EALREADY]          = TARGET_EALREADY,
 606    [EINPROGRESS]       = TARGET_EINPROGRESS,
 607    [ESTALE]            = TARGET_ESTALE,
 608    [ECANCELED]         = TARGET_ECANCELED,
 609    [ENOMEDIUM]         = TARGET_ENOMEDIUM,
 610    [EMEDIUMTYPE]       = TARGET_EMEDIUMTYPE,
 611#ifdef ENOKEY
 612    [ENOKEY]            = TARGET_ENOKEY,
 613#endif
 614#ifdef EKEYEXPIRED
 615    [EKEYEXPIRED]       = TARGET_EKEYEXPIRED,
 616#endif
 617#ifdef EKEYREVOKED
 618    [EKEYREVOKED]       = TARGET_EKEYREVOKED,
 619#endif
 620#ifdef EKEYREJECTED
 621    [EKEYREJECTED]      = TARGET_EKEYREJECTED,
 622#endif
 623#ifdef EOWNERDEAD
 624    [EOWNERDEAD]        = TARGET_EOWNERDEAD,
 625#endif
 626#ifdef ENOTRECOVERABLE
 627    [ENOTRECOVERABLE]   = TARGET_ENOTRECOVERABLE,
 628#endif
 629#ifdef ENOMSG
 630    [ENOMSG]            = TARGET_ENOMSG,
 631#endif
 632#ifdef ERKFILL
 633    [ERFKILL]           = TARGET_ERFKILL,
 634#endif
 635#ifdef EHWPOISON
 636    [EHWPOISON]         = TARGET_EHWPOISON,
 637#endif
 638};
 639
 640static inline int host_to_target_errno(int err)
 641{
 642    if (err >= 0 && err < ERRNO_TABLE_SIZE &&
 643        host_to_target_errno_table[err]) {
 644        return host_to_target_errno_table[err];
 645    }
 646    return err;
 647}
 648
 649static inline int target_to_host_errno(int err)
 650{
 651    if (err >= 0 && err < ERRNO_TABLE_SIZE &&
 652        target_to_host_errno_table[err]) {
 653        return target_to_host_errno_table[err];
 654    }
 655    return err;
 656}
 657
 658static inline abi_long get_errno(abi_long ret)
 659{
 660    if (ret == -1)
 661        return -host_to_target_errno(errno);
 662    else
 663        return ret;
 664}
 665
 666const char *target_strerror(int err)
 667{
 668    if (err == TARGET_ERESTARTSYS) {
 669        return "To be restarted";
 670    }
 671    if (err == TARGET_QEMU_ESIGRETURN) {
 672        return "Successful exit from sigreturn";
 673    }
 674
 675    if ((err >= ERRNO_TABLE_SIZE) || (err < 0)) {
 676        return NULL;
 677    }
 678    return strerror(target_to_host_errno(err));
 679}
 680
 681#define safe_syscall0(type, name) \
 682static type safe_##name(void) \
 683{ \
 684    return safe_syscall(__NR_##name); \
 685}
 686
 687#define safe_syscall1(type, name, type1, arg1) \
 688static type safe_##name(type1 arg1) \
 689{ \
 690    return safe_syscall(__NR_##name, arg1); \
 691}
 692
 693#define safe_syscall2(type, name, type1, arg1, type2, arg2) \
 694static type safe_##name(type1 arg1, type2 arg2) \
 695{ \
 696    return safe_syscall(__NR_##name, arg1, arg2); \
 697}
 698
 699#define safe_syscall3(type, name, type1, arg1, type2, arg2, type3, arg3) \
 700static type safe_##name(type1 arg1, type2 arg2, type3 arg3) \
 701{ \
 702    return safe_syscall(__NR_##name, arg1, arg2, arg3); \
 703}
 704
 705#define safe_syscall4(type, name, type1, arg1, type2, arg2, type3, arg3, \
 706    type4, arg4) \
 707static type safe_##name(type1 arg1, type2 arg2, type3 arg3, type4 arg4) \
 708{ \
 709    return safe_syscall(__NR_##name, arg1, arg2, arg3, arg4); \
 710}
 711
 712#define safe_syscall5(type, name, type1, arg1, type2, arg2, type3, arg3, \
 713    type4, arg4, type5, arg5) \
 714static type safe_##name(type1 arg1, type2 arg2, type3 arg3, type4 arg4, \
 715    type5 arg5) \
 716{ \
 717    return safe_syscall(__NR_##name, arg1, arg2, arg3, arg4, arg5); \
 718}
 719
 720#define safe_syscall6(type, name, type1, arg1, type2, arg2, type3, arg3, \
 721    type4, arg4, type5, arg5, type6, arg6) \
 722static type safe_##name(type1 arg1, type2 arg2, type3 arg3, type4 arg4, \
 723    type5 arg5, type6 arg6) \
 724{ \
 725    return safe_syscall(__NR_##name, arg1, arg2, arg3, arg4, arg5, arg6); \
 726}
 727
 728safe_syscall3(ssize_t, read, int, fd, void *, buff, size_t, count)
 729safe_syscall3(ssize_t, write, int, fd, const void *, buff, size_t, count)
 730safe_syscall4(int, openat, int, dirfd, const char *, pathname, \
 731              int, flags, mode_t, mode)
 732safe_syscall4(pid_t, wait4, pid_t, pid, int *, status, int, options, \
 733              struct rusage *, rusage)
 734safe_syscall5(int, waitid, idtype_t, idtype, id_t, id, siginfo_t *, infop, \
 735              int, options, struct rusage *, rusage)
 736safe_syscall3(int, execve, const char *, filename, char **, argv, char **, envp)
 737safe_syscall6(int, pselect6, int, nfds, fd_set *, readfds, fd_set *, writefds, \
 738              fd_set *, exceptfds, struct timespec *, timeout, void *, sig)
 739safe_syscall5(int, ppoll, struct pollfd *, ufds, unsigned int, nfds,
 740              struct timespec *, tsp, const sigset_t *, sigmask,
 741              size_t, sigsetsize)
 742safe_syscall6(int, epoll_pwait, int, epfd, struct epoll_event *, events,
 743              int, maxevents, int, timeout, const sigset_t *, sigmask,
 744              size_t, sigsetsize)
 745safe_syscall6(int,futex,int *,uaddr,int,op,int,val, \
 746              const struct timespec *,timeout,int *,uaddr2,int,val3)
 747safe_syscall2(int, rt_sigsuspend, sigset_t *, newset, size_t, sigsetsize)
 748safe_syscall2(int, kill, pid_t, pid, int, sig)
 749safe_syscall2(int, tkill, int, tid, int, sig)
 750safe_syscall3(int, tgkill, int, tgid, int, pid, int, sig)
 751safe_syscall3(ssize_t, readv, int, fd, const struct iovec *, iov, int, iovcnt)
 752safe_syscall3(ssize_t, writev, int, fd, const struct iovec *, iov, int, iovcnt)
 753safe_syscall5(ssize_t, preadv, int, fd, const struct iovec *, iov, int, iovcnt,
 754              unsigned long, pos_l, unsigned long, pos_h)
 755safe_syscall5(ssize_t, pwritev, int, fd, const struct iovec *, iov, int, iovcnt,
 756              unsigned long, pos_l, unsigned long, pos_h)
 757safe_syscall3(int, connect, int, fd, const struct sockaddr *, addr,
 758              socklen_t, addrlen)
 759safe_syscall6(ssize_t, sendto, int, fd, const void *, buf, size_t, len,
 760              int, flags, const struct sockaddr *, addr, socklen_t, addrlen)
 761safe_syscall6(ssize_t, recvfrom, int, fd, void *, buf, size_t, len,
 762              int, flags, struct sockaddr *, addr, socklen_t *, addrlen)
 763safe_syscall3(ssize_t, sendmsg, int, fd, const struct msghdr *, msg, int, flags)
 764safe_syscall3(ssize_t, recvmsg, int, fd, struct msghdr *, msg, int, flags)
 765safe_syscall2(int, flock, int, fd, int, operation)
 766safe_syscall4(int, rt_sigtimedwait, const sigset_t *, these, siginfo_t *, uinfo,
 767              const struct timespec *, uts, size_t, sigsetsize)
 768safe_syscall4(int, accept4, int, fd, struct sockaddr *, addr, socklen_t *, len,
 769              int, flags)
 770safe_syscall2(int, nanosleep, const struct timespec *, req,
 771              struct timespec *, rem)
 772#ifdef TARGET_NR_clock_nanosleep
 773safe_syscall4(int, clock_nanosleep, const clockid_t, clock, int, flags,
 774              const struct timespec *, req, struct timespec *, rem)
 775#endif
 776#ifdef __NR_ipc
 777safe_syscall6(int, ipc, int, call, long, first, long, second, long, third,
 778              void *, ptr, long, fifth)
 779#endif
 780#ifdef __NR_msgsnd
 781safe_syscall4(int, msgsnd, int, msgid, const void *, msgp, size_t, sz,
 782              int, flags)
 783#endif
 784#ifdef __NR_msgrcv
 785safe_syscall5(int, msgrcv, int, msgid, void *, msgp, size_t, sz,
 786              long, msgtype, int, flags)
 787#endif
 788#ifdef __NR_semtimedop
 789safe_syscall4(int, semtimedop, int, semid, struct sembuf *, tsops,
 790              unsigned, nsops, const struct timespec *, timeout)
 791#endif
 792#if defined(TARGET_NR_mq_open) && defined(__NR_mq_open)
 793safe_syscall5(int, mq_timedsend, int, mqdes, const char *, msg_ptr,
 794              size_t, len, unsigned, prio, const struct timespec *, timeout)
 795safe_syscall5(int, mq_timedreceive, int, mqdes, char *, msg_ptr,
 796              size_t, len, unsigned *, prio, const struct timespec *, timeout)
 797#endif
 798/* We do ioctl like this rather than via safe_syscall3 to preserve the
 799 * "third argument might be integer or pointer or not present" behaviour of
 800 * the libc function.
 801 */
 802#define safe_ioctl(...) safe_syscall(__NR_ioctl, __VA_ARGS__)
 803/* Similarly for fcntl. Note that callers must always:
 804 *  pass the F_GETLK64 etc constants rather than the unsuffixed F_GETLK
 805 *  use the flock64 struct rather than unsuffixed flock
 806 * This will then work and use a 64-bit offset for both 32-bit and 64-bit hosts.
 807 */
 808#ifdef __NR_fcntl64
 809#define safe_fcntl(...) safe_syscall(__NR_fcntl64, __VA_ARGS__)
 810#else
 811#define safe_fcntl(...) safe_syscall(__NR_fcntl, __VA_ARGS__)
 812#endif
 813
 814static inline int host_to_target_sock_type(int host_type)
 815{
 816    int target_type;
 817
 818    switch (host_type & 0xf /* SOCK_TYPE_MASK */) {
 819    case SOCK_DGRAM:
 820        target_type = TARGET_SOCK_DGRAM;
 821        break;
 822    case SOCK_STREAM:
 823        target_type = TARGET_SOCK_STREAM;
 824        break;
 825    default:
 826        target_type = host_type & 0xf /* SOCK_TYPE_MASK */;
 827        break;
 828    }
 829
 830#if defined(SOCK_CLOEXEC)
 831    if (host_type & SOCK_CLOEXEC) {
 832        target_type |= TARGET_SOCK_CLOEXEC;
 833    }
 834#endif
 835
 836#if defined(SOCK_NONBLOCK)
 837    if (host_type & SOCK_NONBLOCK) {
 838        target_type |= TARGET_SOCK_NONBLOCK;
 839    }
 840#endif
 841
 842    return target_type;
 843}
 844
 845static abi_ulong target_brk;
 846static abi_ulong target_original_brk;
 847static abi_ulong brk_page;
 848
 849void target_set_brk(abi_ulong new_brk)
 850{
 851    target_original_brk = target_brk = HOST_PAGE_ALIGN(new_brk);
 852    brk_page = HOST_PAGE_ALIGN(target_brk);
 853}
 854
 855//#define DEBUGF_BRK(message, args...) do { fprintf(stderr, (message), ## args); } while (0)
 856#define DEBUGF_BRK(message, args...)
 857
 858/* do_brk() must return target values and target errnos. */
 859abi_long do_brk(abi_ulong new_brk)
 860{
 861    abi_long mapped_addr;
 862    abi_ulong new_alloc_size;
 863
 864    DEBUGF_BRK("do_brk(" TARGET_ABI_FMT_lx ") -> ", new_brk);
 865
 866    if (!new_brk) {
 867        DEBUGF_BRK(TARGET_ABI_FMT_lx " (!new_brk)\n", target_brk);
 868        return target_brk;
 869    }
 870    if (new_brk < target_original_brk) {
 871        DEBUGF_BRK(TARGET_ABI_FMT_lx " (new_brk < target_original_brk)\n",
 872                   target_brk);
 873        return target_brk;
 874    }
 875
 876    /* If the new brk is less than the highest page reserved to the
 877     * target heap allocation, set it and we're almost done...  */
 878    if (new_brk <= brk_page) {
 879        /* Heap contents are initialized to zero, as for anonymous
 880         * mapped pages.  */
 881        if (new_brk > target_brk) {
 882            memset(g2h(target_brk), 0, new_brk - target_brk);
 883        }
 884        target_brk = new_brk;
 885        DEBUGF_BRK(TARGET_ABI_FMT_lx " (new_brk <= brk_page)\n", target_brk);
 886        return target_brk;
 887    }
 888
 889    /* We need to allocate more memory after the brk... Note that
 890     * we don't use MAP_FIXED because that will map over the top of
 891     * any existing mapping (like the one with the host libc or qemu
 892     * itself); instead we treat "mapped but at wrong address" as
 893     * a failure and unmap again.
 894     */
 895    new_alloc_size = HOST_PAGE_ALIGN(new_brk - brk_page);
 896    mapped_addr = get_errno(target_mmap(brk_page, new_alloc_size,
 897                                        PROT_READ|PROT_WRITE,
 898                                        MAP_ANON|MAP_PRIVATE, 0, 0));
 899
 900    if (mapped_addr == brk_page) {
 901        /* Heap contents are initialized to zero, as for anonymous
 902         * mapped pages.  Technically the new pages are already
 903         * initialized to zero since they *are* anonymous mapped
 904         * pages, however we have to take care with the contents that
 905         * come from the remaining part of the previous page: it may
 906         * contains garbage data due to a previous heap usage (grown
 907         * then shrunken).  */
 908        memset(g2h(target_brk), 0, brk_page - target_brk);
 909
 910        target_brk = new_brk;
 911        brk_page = HOST_PAGE_ALIGN(target_brk);
 912        DEBUGF_BRK(TARGET_ABI_FMT_lx " (mapped_addr == brk_page)\n",
 913            target_brk);
 914        return target_brk;
 915    } else if (mapped_addr != -1) {
 916        /* Mapped but at wrong address, meaning there wasn't actually
 917         * enough space for this brk.
 918         */
 919        target_munmap(mapped_addr, new_alloc_size);
 920        mapped_addr = -1;
 921        DEBUGF_BRK(TARGET_ABI_FMT_lx " (mapped_addr != -1)\n", target_brk);
 922    }
 923    else {
 924        DEBUGF_BRK(TARGET_ABI_FMT_lx " (otherwise)\n", target_brk);
 925    }
 926
 927#if defined(TARGET_ALPHA)
 928    /* We (partially) emulate OSF/1 on Alpha, which requires we
 929       return a proper errno, not an unchanged brk value.  */
 930    return -TARGET_ENOMEM;
 931#endif
 932    /* For everything else, return the previous break. */
 933    return target_brk;
 934}
 935
 936static inline abi_long copy_from_user_fdset(fd_set *fds,
 937                                            abi_ulong target_fds_addr,
 938                                            int n)
 939{
 940    int i, nw, j, k;
 941    abi_ulong b, *target_fds;
 942
 943    nw = DIV_ROUND_UP(n, TARGET_ABI_BITS);
 944    if (!(target_fds = lock_user(VERIFY_READ,
 945                                 target_fds_addr,
 946                                 sizeof(abi_ulong) * nw,
 947                                 1)))
 948        return -TARGET_EFAULT;
 949
 950    FD_ZERO(fds);
 951    k = 0;
 952    for (i = 0; i < nw; i++) {
 953        /* grab the abi_ulong */
 954        __get_user(b, &target_fds[i]);
 955        for (j = 0; j < TARGET_ABI_BITS; j++) {
 956            /* check the bit inside the abi_ulong */
 957            if ((b >> j) & 1)
 958                FD_SET(k, fds);
 959            k++;
 960        }
 961    }
 962
 963    unlock_user(target_fds, target_fds_addr, 0);
 964
 965    return 0;
 966}
 967
 968static inline abi_ulong copy_from_user_fdset_ptr(fd_set *fds, fd_set **fds_ptr,
 969                                                 abi_ulong target_fds_addr,
 970                                                 int n)
 971{
 972    if (target_fds_addr) {
 973        if (copy_from_user_fdset(fds, target_fds_addr, n))
 974            return -TARGET_EFAULT;
 975        *fds_ptr = fds;
 976    } else {
 977        *fds_ptr = NULL;
 978    }
 979    return 0;
 980}
 981
 982static inline abi_long copy_to_user_fdset(abi_ulong target_fds_addr,
 983                                          const fd_set *fds,
 984                                          int n)
 985{
 986    int i, nw, j, k;
 987    abi_long v;
 988    abi_ulong *target_fds;
 989
 990    nw = DIV_ROUND_UP(n, TARGET_ABI_BITS);
 991    if (!(target_fds = lock_user(VERIFY_WRITE,
 992                                 target_fds_addr,
 993                                 sizeof(abi_ulong) * nw,
 994                                 0)))
 995        return -TARGET_EFAULT;
 996
 997    k = 0;
 998    for (i = 0; i < nw; i++) {
 999        v = 0;
1000        for (j = 0; j < TARGET_ABI_BITS; j++) {
1001            v |= ((abi_ulong)(FD_ISSET(k, fds) != 0) << j);
1002            k++;
1003        }
1004        __put_user(v, &target_fds[i]);
1005    }
1006
1007    unlock_user(target_fds, target_fds_addr, sizeof(abi_ulong) * nw);
1008
1009    return 0;
1010}
1011
1012#if defined(__alpha__)
1013#define HOST_HZ 1024
1014#else
1015#define HOST_HZ 100
1016#endif
1017
1018static inline abi_long host_to_target_clock_t(long ticks)
1019{
1020#if HOST_HZ == TARGET_HZ
1021    return ticks;
1022#else
1023    return ((int64_t)ticks * TARGET_HZ) / HOST_HZ;
1024#endif
1025}
1026
1027static inline abi_long host_to_target_rusage(abi_ulong target_addr,
1028                                             const struct rusage *rusage)
1029{
1030    struct target_rusage *target_rusage;
1031
1032    if (!lock_user_struct(VERIFY_WRITE, target_rusage, target_addr, 0))
1033        return -TARGET_EFAULT;
1034    target_rusage->ru_utime.tv_sec = tswapal(rusage->ru_utime.tv_sec);
1035    target_rusage->ru_utime.tv_usec = tswapal(rusage->ru_utime.tv_usec);
1036    target_rusage->ru_stime.tv_sec = tswapal(rusage->ru_stime.tv_sec);
1037    target_rusage->ru_stime.tv_usec = tswapal(rusage->ru_stime.tv_usec);
1038    target_rusage->ru_maxrss = tswapal(rusage->ru_maxrss);
1039    target_rusage->ru_ixrss = tswapal(rusage->ru_ixrss);
1040    target_rusage->ru_idrss = tswapal(rusage->ru_idrss);
1041    target_rusage->ru_isrss = tswapal(rusage->ru_isrss);
1042    target_rusage->ru_minflt = tswapal(rusage->ru_minflt);
1043    target_rusage->ru_majflt = tswapal(rusage->ru_majflt);
1044    target_rusage->ru_nswap = tswapal(rusage->ru_nswap);
1045    target_rusage->ru_inblock = tswapal(rusage->ru_inblock);
1046    target_rusage->ru_oublock = tswapal(rusage->ru_oublock);
1047    target_rusage->ru_msgsnd = tswapal(rusage->ru_msgsnd);
1048    target_rusage->ru_msgrcv = tswapal(rusage->ru_msgrcv);
1049    target_rusage->ru_nsignals = tswapal(rusage->ru_nsignals);
1050    target_rusage->ru_nvcsw = tswapal(rusage->ru_nvcsw);
1051    target_rusage->ru_nivcsw = tswapal(rusage->ru_nivcsw);
1052    unlock_user_struct(target_rusage, target_addr, 1);
1053
1054    return 0;
1055}
1056
1057static inline rlim_t target_to_host_rlim(abi_ulong target_rlim)
1058{
1059    abi_ulong target_rlim_swap;
1060    rlim_t result;
1061    
1062    target_rlim_swap = tswapal(target_rlim);
1063    if (target_rlim_swap == TARGET_RLIM_INFINITY)
1064        return RLIM_INFINITY;
1065
1066    result = target_rlim_swap;
1067    if (target_rlim_swap != (rlim_t)result)
1068        return RLIM_INFINITY;
1069    
1070    return result;
1071}
1072
1073static inline abi_ulong host_to_target_rlim(rlim_t rlim)
1074{
1075    abi_ulong target_rlim_swap;
1076    abi_ulong result;
1077    
1078    if (rlim == RLIM_INFINITY || rlim != (abi_long)rlim)
1079        target_rlim_swap = TARGET_RLIM_INFINITY;
1080    else
1081        target_rlim_swap = rlim;
1082    result = tswapal(target_rlim_swap);
1083    
1084    return result;
1085}
1086
1087static inline int target_to_host_resource(int code)
1088{
1089    switch (code) {
1090    case TARGET_RLIMIT_AS:
1091        return RLIMIT_AS;
1092    case TARGET_RLIMIT_CORE:
1093        return RLIMIT_CORE;
1094    case TARGET_RLIMIT_CPU:
1095        return RLIMIT_CPU;
1096    case TARGET_RLIMIT_DATA:
1097        return RLIMIT_DATA;
1098    case TARGET_RLIMIT_FSIZE:
1099        return RLIMIT_FSIZE;
1100    case TARGET_RLIMIT_LOCKS:
1101        return RLIMIT_LOCKS;
1102    case TARGET_RLIMIT_MEMLOCK:
1103        return RLIMIT_MEMLOCK;
1104    case TARGET_RLIMIT_MSGQUEUE:
1105        return RLIMIT_MSGQUEUE;
1106    case TARGET_RLIMIT_NICE:
1107        return RLIMIT_NICE;
1108    case TARGET_RLIMIT_NOFILE:
1109        return RLIMIT_NOFILE;
1110    case TARGET_RLIMIT_NPROC:
1111        return RLIMIT_NPROC;
1112    case TARGET_RLIMIT_RSS:
1113        return RLIMIT_RSS;
1114    case TARGET_RLIMIT_RTPRIO:
1115        return RLIMIT_RTPRIO;
1116    case TARGET_RLIMIT_SIGPENDING:
1117        return RLIMIT_SIGPENDING;
1118    case TARGET_RLIMIT_STACK:
1119        return RLIMIT_STACK;
1120    default:
1121        return code;
1122    }
1123}
1124
1125static inline abi_long copy_from_user_timeval(struct timeval *tv,
1126                                              abi_ulong target_tv_addr)
1127{
1128    struct target_timeval *target_tv;
1129
1130    if (!lock_user_struct(VERIFY_READ, target_tv, target_tv_addr, 1)) {
1131        return -TARGET_EFAULT;
1132    }
1133
1134    __get_user(tv->tv_sec, &target_tv->tv_sec);
1135    __get_user(tv->tv_usec, &target_tv->tv_usec);
1136
1137    unlock_user_struct(target_tv, target_tv_addr, 0);
1138
1139    return 0;
1140}
1141
1142static inline abi_long copy_to_user_timeval(abi_ulong target_tv_addr,
1143                                            const struct timeval *tv)
1144{
1145    struct target_timeval *target_tv;
1146
1147    if (!lock_user_struct(VERIFY_WRITE, target_tv, target_tv_addr, 0)) {
1148        return -TARGET_EFAULT;
1149    }
1150
1151    __put_user(tv->tv_sec, &target_tv->tv_sec);
1152    __put_user(tv->tv_usec, &target_tv->tv_usec);
1153
1154    unlock_user_struct(target_tv, target_tv_addr, 1);
1155
1156    return 0;
1157}
1158
1159static inline abi_long copy_to_user_timeval64(abi_ulong target_tv_addr,
1160                                             const struct timeval *tv)
1161{
1162    struct target__kernel_sock_timeval *target_tv;
1163
1164    if (!lock_user_struct(VERIFY_WRITE, target_tv, target_tv_addr, 0)) {
1165        return -TARGET_EFAULT;
1166    }
1167
1168    __put_user(tv->tv_sec, &target_tv->tv_sec);
1169    __put_user(tv->tv_usec, &target_tv->tv_usec);
1170
1171    unlock_user_struct(target_tv, target_tv_addr, 1);
1172
1173    return 0;
1174}
1175
1176static inline abi_long target_to_host_timespec(struct timespec *host_ts,
1177                                               abi_ulong target_addr)
1178{
1179    struct target_timespec *target_ts;
1180
1181    if (!lock_user_struct(VERIFY_READ, target_ts, target_addr, 1)) {
1182        return -TARGET_EFAULT;
1183    }
1184    __get_user(host_ts->tv_sec, &target_ts->tv_sec);
1185    __get_user(host_ts->tv_nsec, &target_ts->tv_nsec);
1186    unlock_user_struct(target_ts, target_addr, 0);
1187    return 0;
1188}
1189
1190static inline abi_long host_to_target_timespec(abi_ulong target_addr,
1191                                               struct timespec *host_ts)
1192{
1193    struct target_timespec *target_ts;
1194
1195    if (!lock_user_struct(VERIFY_WRITE, target_ts, target_addr, 0)) {
1196        return -TARGET_EFAULT;
1197    }
1198    __put_user(host_ts->tv_sec, &target_ts->tv_sec);
1199    __put_user(host_ts->tv_nsec, &target_ts->tv_nsec);
1200    unlock_user_struct(target_ts, target_addr, 1);
1201    return 0;
1202}
1203
1204static inline abi_long host_to_target_timespec64(abi_ulong target_addr,
1205                                                 struct timespec *host_ts)
1206{
1207    struct target__kernel_timespec *target_ts;
1208
1209    if (!lock_user_struct(VERIFY_WRITE, target_ts, target_addr, 0)) {
1210        return -TARGET_EFAULT;
1211    }
1212    __put_user(host_ts->tv_sec, &target_ts->tv_sec);
1213    __put_user(host_ts->tv_nsec, &target_ts->tv_nsec);
1214    unlock_user_struct(target_ts, target_addr, 1);
1215    return 0;
1216}
1217
1218static inline abi_long copy_from_user_timezone(struct timezone *tz,
1219                                               abi_ulong target_tz_addr)
1220{
1221    struct target_timezone *target_tz;
1222
1223    if (!lock_user_struct(VERIFY_READ, target_tz, target_tz_addr, 1)) {
1224        return -TARGET_EFAULT;
1225    }
1226
1227    __get_user(tz->tz_minuteswest, &target_tz->tz_minuteswest);
1228    __get_user(tz->tz_dsttime, &target_tz->tz_dsttime);
1229
1230    unlock_user_struct(target_tz, target_tz_addr, 0);
1231
1232    return 0;
1233}
1234
1235#if defined(TARGET_NR_mq_open) && defined(__NR_mq_open)
1236#include <mqueue.h>
1237
1238static inline abi_long copy_from_user_mq_attr(struct mq_attr *attr,
1239                                              abi_ulong target_mq_attr_addr)
1240{
1241    struct target_mq_attr *target_mq_attr;
1242
1243    if (!lock_user_struct(VERIFY_READ, target_mq_attr,
1244                          target_mq_attr_addr, 1))
1245        return -TARGET_EFAULT;
1246
1247    __get_user(attr->mq_flags, &target_mq_attr->mq_flags);
1248    __get_user(attr->mq_maxmsg, &target_mq_attr->mq_maxmsg);
1249    __get_user(attr->mq_msgsize, &target_mq_attr->mq_msgsize);
1250    __get_user(attr->mq_curmsgs, &target_mq_attr->mq_curmsgs);
1251
1252    unlock_user_struct(target_mq_attr, target_mq_attr_addr, 0);
1253
1254    return 0;
1255}
1256
1257static inline abi_long copy_to_user_mq_attr(abi_ulong target_mq_attr_addr,
1258                                            const struct mq_attr *attr)
1259{
1260    struct target_mq_attr *target_mq_attr;
1261
1262    if (!lock_user_struct(VERIFY_WRITE, target_mq_attr,
1263                          target_mq_attr_addr, 0))
1264        return -TARGET_EFAULT;
1265
1266    __put_user(attr->mq_flags, &target_mq_attr->mq_flags);
1267    __put_user(attr->mq_maxmsg, &target_mq_attr->mq_maxmsg);
1268    __put_user(attr->mq_msgsize, &target_mq_attr->mq_msgsize);
1269    __put_user(attr->mq_curmsgs, &target_mq_attr->mq_curmsgs);
1270
1271    unlock_user_struct(target_mq_attr, target_mq_attr_addr, 1);
1272
1273    return 0;
1274}
1275#endif
1276
1277#if defined(TARGET_NR_select) || defined(TARGET_NR__newselect)
1278/* do_select() must return target values and target errnos. */
1279static abi_long do_select(int n,
1280                          abi_ulong rfd_addr, abi_ulong wfd_addr,
1281                          abi_ulong efd_addr, abi_ulong target_tv_addr)
1282{
1283    fd_set rfds, wfds, efds;
1284    fd_set *rfds_ptr, *wfds_ptr, *efds_ptr;
1285    struct timeval tv;
1286    struct timespec ts, *ts_ptr;
1287    abi_long ret;
1288
1289    ret = copy_from_user_fdset_ptr(&rfds, &rfds_ptr, rfd_addr, n);
1290    if (ret) {
1291        return ret;
1292    }
1293    ret = copy_from_user_fdset_ptr(&wfds, &wfds_ptr, wfd_addr, n);
1294    if (ret) {
1295        return ret;
1296    }
1297    ret = copy_from_user_fdset_ptr(&efds, &efds_ptr, efd_addr, n);
1298    if (ret) {
1299        return ret;
1300    }
1301
1302    if (target_tv_addr) {
1303        if (copy_from_user_timeval(&tv, target_tv_addr))
1304            return -TARGET_EFAULT;
1305        ts.tv_sec = tv.tv_sec;
1306        ts.tv_nsec = tv.tv_usec * 1000;
1307        ts_ptr = &ts;
1308    } else {
1309        ts_ptr = NULL;
1310    }
1311
1312    ret = get_errno(safe_pselect6(n, rfds_ptr, wfds_ptr, efds_ptr,
1313                                  ts_ptr, NULL));
1314
1315    if (!is_error(ret)) {
1316        if (rfd_addr && copy_to_user_fdset(rfd_addr, &rfds, n))
1317            return -TARGET_EFAULT;
1318        if (wfd_addr && copy_to_user_fdset(wfd_addr, &wfds, n))
1319            return -TARGET_EFAULT;
1320        if (efd_addr && copy_to_user_fdset(efd_addr, &efds, n))
1321            return -TARGET_EFAULT;
1322
1323        if (target_tv_addr) {
1324            tv.tv_sec = ts.tv_sec;
1325            tv.tv_usec = ts.tv_nsec / 1000;
1326            if (copy_to_user_timeval(target_tv_addr, &tv)) {
1327                return -TARGET_EFAULT;
1328            }
1329        }
1330    }
1331
1332    return ret;
1333}
1334
1335#if defined(TARGET_WANT_OLD_SYS_SELECT)
1336static abi_long do_old_select(abi_ulong arg1)
1337{
1338    struct target_sel_arg_struct *sel;
1339    abi_ulong inp, outp, exp, tvp;
1340    long nsel;
1341
1342    if (!lock_user_struct(VERIFY_READ, sel, arg1, 1)) {
1343        return -TARGET_EFAULT;
1344    }
1345
1346    nsel = tswapal(sel->n);
1347    inp = tswapal(sel->inp);
1348    outp = tswapal(sel->outp);
1349    exp = tswapal(sel->exp);
1350    tvp = tswapal(sel->tvp);
1351
1352    unlock_user_struct(sel, arg1, 0);
1353
1354    return do_select(nsel, inp, outp, exp, tvp);
1355}
1356#endif
1357#endif
1358
1359static abi_long do_pipe2(int host_pipe[], int flags)
1360{
1361#ifdef CONFIG_PIPE2
1362    return pipe2(host_pipe, flags);
1363#else
1364    return -ENOSYS;
1365#endif
1366}
1367
1368static abi_long do_pipe(void *cpu_env, abi_ulong pipedes,
1369                        int flags, int is_pipe2)
1370{
1371    int host_pipe[2];
1372    abi_long ret;
1373    ret = flags ? do_pipe2(host_pipe, flags) : pipe(host_pipe);
1374
1375    if (is_error(ret))
1376        return get_errno(ret);
1377
1378    /* Several targets have special calling conventions for the original
1379       pipe syscall, but didn't replicate this into the pipe2 syscall.  */
1380    if (!is_pipe2) {
1381#if defined(TARGET_ALPHA)
1382        ((CPUAlphaState *)cpu_env)->ir[IR_A4] = host_pipe[1];
1383        return host_pipe[0];
1384#elif defined(TARGET_MIPS)
1385        ((CPUMIPSState*)cpu_env)->active_tc.gpr[3] = host_pipe[1];
1386        return host_pipe[0];
1387#elif defined(TARGET_SH4)
1388        ((CPUSH4State*)cpu_env)->gregs[1] = host_pipe[1];
1389        return host_pipe[0];
1390#elif defined(TARGET_SPARC)
1391        ((CPUSPARCState*)cpu_env)->regwptr[1] = host_pipe[1];
1392        return host_pipe[0];
1393#endif
1394    }
1395
1396    if (put_user_s32(host_pipe[0], pipedes)
1397        || put_user_s32(host_pipe[1], pipedes + sizeof(host_pipe[0])))
1398        return -TARGET_EFAULT;
1399    return get_errno(ret);
1400}
1401
1402static inline abi_long target_to_host_ip_mreq(struct ip_mreqn *mreqn,
1403                                              abi_ulong target_addr,
1404                                              socklen_t len)
1405{
1406    struct target_ip_mreqn *target_smreqn;
1407
1408    target_smreqn = lock_user(VERIFY_READ, target_addr, len, 1);
1409    if (!target_smreqn)
1410        return -TARGET_EFAULT;
1411    mreqn->imr_multiaddr.s_addr = target_smreqn->imr_multiaddr.s_addr;
1412    mreqn->imr_address.s_addr = target_smreqn->imr_address.s_addr;
1413    if (len == sizeof(struct target_ip_mreqn))
1414        mreqn->imr_ifindex = tswapal(target_smreqn->imr_ifindex);
1415    unlock_user(target_smreqn, target_addr, 0);
1416
1417    return 0;
1418}
1419
1420static inline abi_long target_to_host_sockaddr(int fd, struct sockaddr *addr,
1421                                               abi_ulong target_addr,
1422                                               socklen_t len)
1423{
1424    const socklen_t unix_maxlen = sizeof (struct sockaddr_un);
1425    sa_family_t sa_family;
1426    struct target_sockaddr *target_saddr;
1427
1428    if (fd_trans_target_to_host_addr(fd)) {
1429        return fd_trans_target_to_host_addr(fd)(addr, target_addr, len);
1430    }
1431
1432    target_saddr = lock_user(VERIFY_READ, target_addr, len, 1);
1433    if (!target_saddr)
1434        return -TARGET_EFAULT;
1435
1436    sa_family = tswap16(target_saddr->sa_family);
1437
1438    /* Oops. The caller might send a incomplete sun_path; sun_path
1439     * must be terminated by \0 (see the manual page), but
1440     * unfortunately it is quite common to specify sockaddr_un
1441     * length as "strlen(x->sun_path)" while it should be
1442     * "strlen(...) + 1". We'll fix that here if needed.
1443     * Linux kernel has a similar feature.
1444     */
1445
1446    if (sa_family == AF_UNIX) {
1447        if (len < unix_maxlen && len > 0) {
1448            char *cp = (char*)target_saddr;
1449
1450            if ( cp[len-1] && !cp[len] )
1451                len++;
1452        }
1453        if (len > unix_maxlen)
1454            len = unix_maxlen;
1455    }
1456
1457    memcpy(addr, target_saddr, len);
1458    addr->sa_family = sa_family;
1459    if (sa_family == AF_NETLINK) {
1460        struct sockaddr_nl *nladdr;
1461
1462        nladdr = (struct sockaddr_nl *)addr;
1463        nladdr->nl_pid = tswap32(nladdr->nl_pid);
1464        nladdr->nl_groups = tswap32(nladdr->nl_groups);
1465    } else if (sa_family == AF_PACKET) {
1466        struct target_sockaddr_ll *lladdr;
1467
1468        lladdr = (struct target_sockaddr_ll *)addr;
1469        lladdr->sll_ifindex = tswap32(lladdr->sll_ifindex);
1470        lladdr->sll_hatype = tswap16(lladdr->sll_hatype);
1471    }
1472    unlock_user(target_saddr, target_addr, 0);
1473
1474    return 0;
1475}
1476
1477static inline abi_long host_to_target_sockaddr(abi_ulong target_addr,
1478                                               struct sockaddr *addr,
1479                                               socklen_t len)
1480{
1481    struct target_sockaddr *target_saddr;
1482
1483    if (len == 0) {
1484        return 0;
1485    }
1486    assert(addr);
1487
1488    target_saddr = lock_user(VERIFY_WRITE, target_addr, len, 0);
1489    if (!target_saddr)
1490        return -TARGET_EFAULT;
1491    memcpy(target_saddr, addr, len);
1492    if (len >= offsetof(struct target_sockaddr, sa_family) +
1493        sizeof(target_saddr->sa_family)) {
1494        target_saddr->sa_family = tswap16(addr->sa_family);
1495    }
1496    if (addr->sa_family == AF_NETLINK && len >= sizeof(struct sockaddr_nl)) {
1497        struct sockaddr_nl *target_nl = (struct sockaddr_nl *)target_saddr;
1498        target_nl->nl_pid = tswap32(target_nl->nl_pid);
1499        target_nl->nl_groups = tswap32(target_nl->nl_groups);
1500    } else if (addr->sa_family == AF_PACKET) {
1501        struct sockaddr_ll *target_ll = (struct sockaddr_ll *)target_saddr;
1502        target_ll->sll_ifindex = tswap32(target_ll->sll_ifindex);
1503        target_ll->sll_hatype = tswap16(target_ll->sll_hatype);
1504    } else if (addr->sa_family == AF_INET6 &&
1505               len >= sizeof(struct target_sockaddr_in6)) {
1506        struct target_sockaddr_in6 *target_in6 =
1507               (struct target_sockaddr_in6 *)target_saddr;
1508        target_in6->sin6_scope_id = tswap16(target_in6->sin6_scope_id);
1509    }
1510    unlock_user(target_saddr, target_addr, len);
1511
1512    return 0;
1513}
1514
1515static inline abi_long target_to_host_cmsg(struct msghdr *msgh,
1516                                           struct target_msghdr *target_msgh)
1517{
1518    struct cmsghdr *cmsg = CMSG_FIRSTHDR(msgh);
1519    abi_long msg_controllen;
1520    abi_ulong target_cmsg_addr;
1521    struct target_cmsghdr *target_cmsg, *target_cmsg_start;
1522    socklen_t space = 0;
1523    
1524    msg_controllen = tswapal(target_msgh->msg_controllen);
1525    if (msg_controllen < sizeof (struct target_cmsghdr)) 
1526        goto the_end;
1527    target_cmsg_addr = tswapal(target_msgh->msg_control);
1528    target_cmsg = lock_user(VERIFY_READ, target_cmsg_addr, msg_controllen, 1);
1529    target_cmsg_start = target_cmsg;
1530    if (!target_cmsg)
1531        return -TARGET_EFAULT;
1532
1533    while (cmsg && target_cmsg) {
1534        void *data = CMSG_DATA(cmsg);
1535        void *target_data = TARGET_CMSG_DATA(target_cmsg);
1536
1537        int len = tswapal(target_cmsg->cmsg_len)
1538            - sizeof(struct target_cmsghdr);
1539
1540        space += CMSG_SPACE(len);
1541        if (space > msgh->msg_controllen) {
1542            space -= CMSG_SPACE(len);
1543            /* This is a QEMU bug, since we allocated the payload
1544             * area ourselves (unlike overflow in host-to-target
1545             * conversion, which is just the guest giving us a buffer
1546             * that's too small). It can't happen for the payload types
1547             * we currently support; if it becomes an issue in future
1548             * we would need to improve our allocation strategy to
1549             * something more intelligent than "twice the size of the
1550             * target buffer we're reading from".
1551             */
1552            gemu_log("Host cmsg overflow\n");
1553            break;
1554        }
1555
1556        if (tswap32(target_cmsg->cmsg_level) == TARGET_SOL_SOCKET) {
1557            cmsg->cmsg_level = SOL_SOCKET;
1558        } else {
1559            cmsg->cmsg_level = tswap32(target_cmsg->cmsg_level);
1560        }
1561        cmsg->cmsg_type = tswap32(target_cmsg->cmsg_type);
1562        cmsg->cmsg_len = CMSG_LEN(len);
1563
1564        if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
1565            int *fd = (int *)data;
1566            int *target_fd = (int *)target_data;
1567            int i, numfds = len / sizeof(int);
1568
1569            for (i = 0; i < numfds; i++) {
1570                __get_user(fd[i], target_fd + i);
1571            }
1572        } else if (cmsg->cmsg_level == SOL_SOCKET
1573               &&  cmsg->cmsg_type == SCM_CREDENTIALS) {
1574            struct ucred *cred = (struct ucred *)data;
1575            struct target_ucred *target_cred =
1576                (struct target_ucred *)target_data;
1577
1578            __get_user(cred->pid, &target_cred->pid);
1579            __get_user(cred->uid, &target_cred->uid);
1580            __get_user(cred->gid, &target_cred->gid);
1581        } else {
1582            gemu_log("Unsupported ancillary data: %d/%d\n",
1583                                        cmsg->cmsg_level, cmsg->cmsg_type);
1584            memcpy(data, target_data, len);
1585        }
1586
1587        cmsg = CMSG_NXTHDR(msgh, cmsg);
1588        target_cmsg = TARGET_CMSG_NXTHDR(target_msgh, target_cmsg,
1589                                         target_cmsg_start);
1590    }
1591    unlock_user(target_cmsg, target_cmsg_addr, 0);
1592 the_end:
1593    msgh->msg_controllen = space;
1594    return 0;
1595}
1596
1597static inline abi_long host_to_target_cmsg(struct target_msghdr *target_msgh,
1598                                           struct msghdr *msgh)
1599{
1600    struct cmsghdr *cmsg = CMSG_FIRSTHDR(msgh);
1601    abi_long msg_controllen;
1602    abi_ulong target_cmsg_addr;
1603    struct target_cmsghdr *target_cmsg, *target_cmsg_start;
1604    socklen_t space = 0;
1605
1606    msg_controllen = tswapal(target_msgh->msg_controllen);
1607    if (msg_controllen < sizeof (struct target_cmsghdr)) 
1608        goto the_end;
1609    target_cmsg_addr = tswapal(target_msgh->msg_control);
1610    target_cmsg = lock_user(VERIFY_WRITE, target_cmsg_addr, msg_controllen, 0);
1611    target_cmsg_start = target_cmsg;
1612    if (!target_cmsg)
1613        return -TARGET_EFAULT;
1614
1615    while (cmsg && target_cmsg) {
1616        void *data = CMSG_DATA(cmsg);
1617        void *target_data = TARGET_CMSG_DATA(target_cmsg);
1618
1619        int len = cmsg->cmsg_len - sizeof(struct cmsghdr);
1620        int tgt_len, tgt_space;
1621
1622        /* We never copy a half-header but may copy half-data;
1623         * this is Linux's behaviour in put_cmsg(). Note that
1624         * truncation here is a guest problem (which we report
1625         * to the guest via the CTRUNC bit), unlike truncation
1626         * in target_to_host_cmsg, which is a QEMU bug.
1627         */
1628        if (msg_controllen < sizeof(struct target_cmsghdr)) {
1629            target_msgh->msg_flags |= tswap32(MSG_CTRUNC);
1630            break;
1631        }
1632
1633        if (cmsg->cmsg_level == SOL_SOCKET) {
1634            target_cmsg->cmsg_level = tswap32(TARGET_SOL_SOCKET);
1635        } else {
1636            target_cmsg->cmsg_level = tswap32(cmsg->cmsg_level);
1637        }
1638        target_cmsg->cmsg_type = tswap32(cmsg->cmsg_type);
1639
1640        /* Payload types which need a different size of payload on
1641         * the target must adjust tgt_len here.
1642         */
1643        tgt_len = len;
1644        switch (cmsg->cmsg_level) {
1645        case SOL_SOCKET:
1646            switch (cmsg->cmsg_type) {
1647            case SO_TIMESTAMP:
1648                tgt_len = sizeof(struct target_timeval);
1649                break;
1650            default:
1651                break;
1652            }
1653            break;
1654        default:
1655            break;
1656        }
1657
1658        if (msg_controllen < TARGET_CMSG_LEN(tgt_len)) {
1659            target_msgh->msg_flags |= tswap32(MSG_CTRUNC);
1660            tgt_len = msg_controllen - sizeof(struct target_cmsghdr);
1661        }
1662
1663        /* We must now copy-and-convert len bytes of payload
1664         * into tgt_len bytes of destination space. Bear in mind
1665         * that in both source and destination we may be dealing
1666         * with a truncated value!
1667         */
1668        switch (cmsg->cmsg_level) {
1669        case SOL_SOCKET:
1670            switch (cmsg->cmsg_type) {
1671            case SCM_RIGHTS:
1672            {
1673                int *fd = (int *)data;
1674                int *target_fd = (int *)target_data;
1675                int i, numfds = tgt_len / sizeof(int);
1676
1677                for (i = 0; i < numfds; i++) {
1678                    __put_user(fd[i], target_fd + i);
1679                }
1680                break;
1681            }
1682            case SO_TIMESTAMP:
1683            {
1684                struct timeval *tv = (struct timeval *)data;
1685                struct target_timeval *target_tv =
1686                    (struct target_timeval *)target_data;
1687
1688                if (len != sizeof(struct timeval) ||
1689                    tgt_len != sizeof(struct target_timeval)) {
1690                    goto unimplemented;
1691                }
1692
1693                /* copy struct timeval to target */
1694                __put_user(tv->tv_sec, &target_tv->tv_sec);
1695                __put_user(tv->tv_usec, &target_tv->tv_usec);
1696                break;
1697            }
1698            case SCM_CREDENTIALS:
1699            {
1700                struct ucred *cred = (struct ucred *)data;
1701                struct target_ucred *target_cred =
1702                    (struct target_ucred *)target_data;
1703
1704                __put_user(cred->pid, &target_cred->pid);
1705                __put_user(cred->uid, &target_cred->uid);
1706                __put_user(cred->gid, &target_cred->gid);
1707                break;
1708            }
1709            default:
1710                goto unimplemented;
1711            }
1712            break;
1713
1714        case SOL_IP:
1715            switch (cmsg->cmsg_type) {
1716            case IP_TTL:
1717            {
1718                uint32_t *v = (uint32_t *)data;
1719                uint32_t *t_int = (uint32_t *)target_data;
1720
1721                if (len != sizeof(uint32_t) ||
1722                    tgt_len != sizeof(uint32_t)) {
1723                    goto unimplemented;
1724                }
1725                __put_user(*v, t_int);
1726                break;
1727            }
1728            case IP_RECVERR:
1729            {
1730                struct errhdr_t {
1731                   struct sock_extended_err ee;
1732                   struct sockaddr_in offender;
1733                };
1734                struct errhdr_t *errh = (struct errhdr_t *)data;
1735                struct errhdr_t *target_errh =
1736                    (struct errhdr_t *)target_data;
1737
1738                if (len != sizeof(struct errhdr_t) ||
1739                    tgt_len != sizeof(struct errhdr_t)) {
1740                    goto unimplemented;
1741                }
1742                __put_user(errh->ee.ee_errno, &target_errh->ee.ee_errno);
1743                __put_user(errh->ee.ee_origin, &target_errh->ee.ee_origin);
1744                __put_user(errh->ee.ee_type,  &target_errh->ee.ee_type);
1745                __put_user(errh->ee.ee_code, &target_errh->ee.ee_code);
1746                __put_user(errh->ee.ee_pad, &target_errh->ee.ee_pad);
1747                __put_user(errh->ee.ee_info, &target_errh->ee.ee_info);
1748                __put_user(errh->ee.ee_data, &target_errh->ee.ee_data);
1749                host_to_target_sockaddr((unsigned long) &target_errh->offender,
1750                    (void *) &errh->offender, sizeof(errh->offender));
1751                break;
1752            }
1753            default:
1754                goto unimplemented;
1755            }
1756            break;
1757
1758        case SOL_IPV6:
1759            switch (cmsg->cmsg_type) {
1760            case IPV6_HOPLIMIT:
1761            {
1762                uint32_t *v = (uint32_t *)data;
1763                uint32_t *t_int = (uint32_t *)target_data;
1764
1765                if (len != sizeof(uint32_t) ||
1766                    tgt_len != sizeof(uint32_t)) {
1767                    goto unimplemented;
1768                }
1769                __put_user(*v, t_int);
1770                break;
1771            }
1772            case IPV6_RECVERR:
1773            {
1774                struct errhdr6_t {
1775                   struct sock_extended_err ee;
1776                   struct sockaddr_in6 offender;
1777                };
1778                struct errhdr6_t *errh = (struct errhdr6_t *)data;
1779                struct errhdr6_t *target_errh =
1780                    (struct errhdr6_t *)target_data;
1781
1782                if (len != sizeof(struct errhdr6_t) ||
1783                    tgt_len != sizeof(struct errhdr6_t)) {
1784                    goto unimplemented;
1785                }
1786                __put_user(errh->ee.ee_errno, &target_errh->ee.ee_errno);
1787                __put_user(errh->ee.ee_origin, &target_errh->ee.ee_origin);
1788                __put_user(errh->ee.ee_type,  &target_errh->ee.ee_type);
1789                __put_user(errh->ee.ee_code, &target_errh->ee.ee_code);
1790                __put_user(errh->ee.ee_pad, &target_errh->ee.ee_pad);
1791                __put_user(errh->ee.ee_info, &target_errh->ee.ee_info);
1792                __put_user(errh->ee.ee_data, &target_errh->ee.ee_data);
1793                host_to_target_sockaddr((unsigned long) &target_errh->offender,
1794                    (void *) &errh->offender, sizeof(errh->offender));
1795                break;
1796            }
1797            default:
1798                goto unimplemented;
1799            }
1800            break;
1801
1802        default:
1803        unimplemented:
1804            gemu_log("Unsupported ancillary data: %d/%d\n",
1805                                        cmsg->cmsg_level, cmsg->cmsg_type);
1806            memcpy(target_data, data, MIN(len, tgt_len));
1807            if (tgt_len > len) {
1808                memset(target_data + len, 0, tgt_len - len);
1809            }
1810        }
1811
1812        target_cmsg->cmsg_len = tswapal(TARGET_CMSG_LEN(tgt_len));
1813        tgt_space = TARGET_CMSG_SPACE(tgt_len);
1814        if (msg_controllen < tgt_space) {
1815            tgt_space = msg_controllen;
1816        }
1817        msg_controllen -= tgt_space;
1818        space += tgt_space;
1819        cmsg = CMSG_NXTHDR(msgh, cmsg);
1820        target_cmsg = TARGET_CMSG_NXTHDR(target_msgh, target_cmsg,
1821                                         target_cmsg_start);
1822    }
1823    unlock_user(target_cmsg, target_cmsg_addr, space);
1824 the_end:
1825    target_msgh->msg_controllen = tswapal(space);
1826    return 0;
1827}
1828
1829/* do_setsockopt() Must return target values and target errnos. */
1830static abi_long do_setsockopt(int sockfd, int level, int optname,
1831                              abi_ulong optval_addr, socklen_t optlen)
1832{
1833    abi_long ret;
1834    int val;
1835    struct ip_mreqn *ip_mreq;
1836    struct ip_mreq_source *ip_mreq_source;
1837
1838    switch(level) {
1839    case SOL_TCP:
1840        /* TCP options all take an 'int' value.  */
1841        if (optlen < sizeof(uint32_t))
1842            return -TARGET_EINVAL;
1843
1844        if (get_user_u32(val, optval_addr))
1845            return -TARGET_EFAULT;
1846        ret = get_errno(setsockopt(sockfd, level, optname, &val, sizeof(val)));
1847        break;
1848    case SOL_IP:
1849        switch(optname) {
1850        case IP_TOS:
1851        case IP_TTL:
1852        case IP_HDRINCL:
1853        case IP_ROUTER_ALERT:
1854        case IP_RECVOPTS:
1855        case IP_RETOPTS:
1856        case IP_PKTINFO:
1857        case IP_MTU_DISCOVER:
1858        case IP_RECVERR:
1859        case IP_RECVTTL:
1860        case IP_RECVTOS:
1861#ifdef IP_FREEBIND
1862        case IP_FREEBIND:
1863#endif
1864        case IP_MULTICAST_TTL:
1865        case IP_MULTICAST_LOOP:
1866            val = 0;
1867            if (optlen >= sizeof(uint32_t)) {
1868                if (get_user_u32(val, optval_addr))
1869                    return -TARGET_EFAULT;
1870            } else if (optlen >= 1) {
1871                if (get_user_u8(val, optval_addr))
1872                    return -TARGET_EFAULT;
1873            }
1874            ret = get_errno(setsockopt(sockfd, level, optname, &val, sizeof(val)));
1875            break;
1876        case IP_ADD_MEMBERSHIP:
1877        case IP_DROP_MEMBERSHIP:
1878            if (optlen < sizeof (struct target_ip_mreq) ||
1879                optlen > sizeof (struct target_ip_mreqn))
1880                return -TARGET_EINVAL;
1881
1882            ip_mreq = (struct ip_mreqn *) alloca(optlen);
1883            target_to_host_ip_mreq(ip_mreq, optval_addr, optlen);
1884            ret = get_errno(setsockopt(sockfd, level, optname, ip_mreq, optlen));
1885            break;
1886
1887        case IP_BLOCK_SOURCE:
1888        case IP_UNBLOCK_SOURCE:
1889        case IP_ADD_SOURCE_MEMBERSHIP:
1890        case IP_DROP_SOURCE_MEMBERSHIP:
1891            if (optlen != sizeof (struct target_ip_mreq_source))
1892                return -TARGET_EINVAL;
1893
1894            ip_mreq_source = lock_user(VERIFY_READ, optval_addr, optlen, 1);
1895            ret = get_errno(setsockopt(sockfd, level, optname, ip_mreq_source, optlen));
1896            unlock_user (ip_mreq_source, optval_addr, 0);
1897            break;
1898
1899        default:
1900            goto unimplemented;
1901        }
1902        break;
1903    case SOL_IPV6:
1904        switch (optname) {
1905        case IPV6_MTU_DISCOVER:
1906        case IPV6_MTU:
1907        case IPV6_V6ONLY:
1908        case IPV6_RECVPKTINFO:
1909        case IPV6_UNICAST_HOPS:
1910        case IPV6_MULTICAST_HOPS:
1911        case IPV6_MULTICAST_LOOP:
1912        case IPV6_RECVERR:
1913        case IPV6_RECVHOPLIMIT:
1914        case IPV6_2292HOPLIMIT:
1915        case IPV6_CHECKSUM:
1916        case IPV6_ADDRFORM:
1917        case IPV6_2292PKTINFO:
1918        case IPV6_RECVTCLASS:
1919        case IPV6_RECVRTHDR:
1920        case IPV6_2292RTHDR:
1921        case IPV6_RECVHOPOPTS:
1922        case IPV6_2292HOPOPTS:
1923        case IPV6_RECVDSTOPTS:
1924        case IPV6_2292DSTOPTS:
1925        case IPV6_TCLASS:
1926#ifdef IPV6_RECVPATHMTU
1927        case IPV6_RECVPATHMTU:
1928#endif
1929#ifdef IPV6_TRANSPARENT
1930        case IPV6_TRANSPARENT:
1931#endif
1932#ifdef IPV6_FREEBIND
1933        case IPV6_FREEBIND:
1934#endif
1935#ifdef IPV6_RECVORIGDSTADDR
1936        case IPV6_RECVORIGDSTADDR:
1937#endif
1938            val = 0;
1939            if (optlen < sizeof(uint32_t)) {
1940                return -TARGET_EINVAL;
1941            }
1942            if (get_user_u32(val, optval_addr)) {
1943                return -TARGET_EFAULT;
1944            }
1945            ret = get_errno(setsockopt(sockfd, level, optname,
1946                                       &val, sizeof(val)));
1947            break;
1948        case IPV6_PKTINFO:
1949        {
1950            struct in6_pktinfo pki;
1951
1952            if (optlen < sizeof(pki)) {
1953                return -TARGET_EINVAL;
1954            }
1955
1956            if (copy_from_user(&pki, optval_addr, sizeof(pki))) {
1957                return -TARGET_EFAULT;
1958            }
1959
1960            pki.ipi6_ifindex = tswap32(pki.ipi6_ifindex);
1961
1962            ret = get_errno(setsockopt(sockfd, level, optname,
1963                                       &pki, sizeof(pki)));
1964            break;
1965        }
1966        case IPV6_ADD_MEMBERSHIP:
1967        case IPV6_DROP_MEMBERSHIP:
1968        {
1969            struct ipv6_mreq ipv6mreq;
1970
1971            if (optlen < sizeof(ipv6mreq)) {
1972                return -TARGET_EINVAL;
1973            }
1974
1975            if (copy_from_user(&ipv6mreq, optval_addr, sizeof(ipv6mreq))) {
1976                return -TARGET_EFAULT;
1977            }
1978
1979            ipv6mreq.ipv6mr_interface = tswap32(ipv6mreq.ipv6mr_interface);
1980
1981            ret = get_errno(setsockopt(sockfd, level, optname,
1982                                       &ipv6mreq, sizeof(ipv6mreq)));
1983            break;
1984        }
1985        default:
1986            goto unimplemented;
1987        }
1988        break;
1989    case SOL_ICMPV6:
1990        switch (optname) {
1991        case ICMPV6_FILTER:
1992        {
1993            struct icmp6_filter icmp6f;
1994
1995            if (optlen > sizeof(icmp6f)) {
1996                optlen = sizeof(icmp6f);
1997            }
1998
1999            if (copy_from_user(&icmp6f, optval_addr, optlen)) {
2000                return -TARGET_EFAULT;
2001            }
2002
2003            for (val = 0; val < 8; val++) {
2004                icmp6f.data[val] = tswap32(icmp6f.data[val]);
2005            }
2006
2007            ret = get_errno(setsockopt(sockfd, level, optname,
2008                                       &icmp6f, optlen));
2009            break;
2010        }
2011        default:
2012            goto unimplemented;
2013        }
2014        break;
2015    case SOL_RAW:
2016        switch (optname) {
2017        case ICMP_FILTER:
2018        case IPV6_CHECKSUM:
2019            /* those take an u32 value */
2020            if (optlen < sizeof(uint32_t)) {
2021                return -TARGET_EINVAL;
2022            }
2023
2024            if (get_user_u32(val, optval_addr)) {
2025                return -TARGET_EFAULT;
2026            }
2027            ret = get_errno(setsockopt(sockfd, level, optname,
2028                                       &val, sizeof(val)));
2029            break;
2030
2031        default:
2032            goto unimplemented;
2033        }
2034        break;
2035#if defined(SOL_ALG) && defined(ALG_SET_KEY) && defined(ALG_SET_AEAD_AUTHSIZE)
2036    case SOL_ALG:
2037        switch (optname) {
2038        case ALG_SET_KEY:
2039        {
2040            char *alg_key = g_malloc(optlen);
2041
2042            if (!alg_key) {
2043                return -TARGET_ENOMEM;
2044            }
2045            if (copy_from_user(alg_key, optval_addr, optlen)) {
2046                g_free(alg_key);
2047                return -TARGET_EFAULT;
2048            }
2049            ret = get_errno(setsockopt(sockfd, level, optname,
2050                                       alg_key, optlen));
2051            g_free(alg_key);
2052            break;
2053        }
2054        case ALG_SET_AEAD_AUTHSIZE:
2055        {
2056            ret = get_errno(setsockopt(sockfd, level, optname,
2057                                       NULL, optlen));
2058            break;
2059        }
2060        default:
2061            goto unimplemented;
2062        }
2063        break;
2064#endif
2065    case TARGET_SOL_SOCKET:
2066        switch (optname) {
2067        case TARGET_SO_RCVTIMEO:
2068        {
2069                struct timeval tv;
2070
2071                optname = SO_RCVTIMEO;
2072
2073set_timeout:
2074                if (optlen != sizeof(struct target_timeval)) {
2075                    return -TARGET_EINVAL;
2076                }
2077
2078                if (copy_from_user_timeval(&tv, optval_addr)) {
2079                    return -TARGET_EFAULT;
2080                }
2081
2082                ret = get_errno(setsockopt(sockfd, SOL_SOCKET, optname,
2083                                &tv, sizeof(tv)));
2084                return ret;
2085        }
2086        case TARGET_SO_SNDTIMEO:
2087                optname = SO_SNDTIMEO;
2088                goto set_timeout;
2089        case TARGET_SO_ATTACH_FILTER:
2090        {
2091                struct target_sock_fprog *tfprog;
2092                struct target_sock_filter *tfilter;
2093                struct sock_fprog fprog;
2094                struct sock_filter *filter;
2095                int i;
2096
2097                if (optlen != sizeof(*tfprog)) {
2098                    return -TARGET_EINVAL;
2099                }
2100                if (!lock_user_struct(VERIFY_READ, tfprog, optval_addr, 0)) {
2101                    return -TARGET_EFAULT;
2102                }
2103                if (!lock_user_struct(VERIFY_READ, tfilter,
2104                                      tswapal(tfprog->filter), 0)) {
2105                    unlock_user_struct(tfprog, optval_addr, 1);
2106                    return -TARGET_EFAULT;
2107                }
2108
2109                fprog.len = tswap16(tfprog->len);
2110                filter = g_try_new(struct sock_filter, fprog.len);
2111                if (filter == NULL) {
2112                    unlock_user_struct(tfilter, tfprog->filter, 1);
2113                    unlock_user_struct(tfprog, optval_addr, 1);
2114                    return -TARGET_ENOMEM;
2115                }
2116                for (i = 0; i < fprog.len; i++) {
2117                    filter[i].code = tswap16(tfilter[i].code);
2118                    filter[i].jt = tfilter[i].jt;
2119                    filter[i].jf = tfilter[i].jf;
2120                    filter[i].k = tswap32(tfilter[i].k);
2121                }
2122                fprog.filter = filter;
2123
2124                ret = get_errno(setsockopt(sockfd, SOL_SOCKET,
2125                                SO_ATTACH_FILTER, &fprog, sizeof(fprog)));
2126                g_free(filter);
2127
2128                unlock_user_struct(tfilter, tfprog->filter, 1);
2129                unlock_user_struct(tfprog, optval_addr, 1);
2130                return ret;
2131        }
2132        case TARGET_SO_BINDTODEVICE:
2133        {
2134                char *dev_ifname, *addr_ifname;
2135
2136                if (optlen > IFNAMSIZ - 1) {
2137                    optlen = IFNAMSIZ - 1;
2138                }
2139                dev_ifname = lock_user(VERIFY_READ, optval_addr, optlen, 1);
2140                if (!dev_ifname) {
2141                    return -TARGET_EFAULT;
2142                }
2143                optname = SO_BINDTODEVICE;
2144                addr_ifname = alloca(IFNAMSIZ);
2145                memcpy(addr_ifname, dev_ifname, optlen);
2146                addr_ifname[optlen] = 0;
2147                ret = get_errno(setsockopt(sockfd, SOL_SOCKET, optname,
2148                                           addr_ifname, optlen));
2149                unlock_user (dev_ifname, optval_addr, 0);
2150                return ret;
2151        }
2152        case TARGET_SO_LINGER:
2153        {
2154                struct linger lg;
2155                struct target_linger *tlg;
2156
2157                if (optlen != sizeof(struct target_linger)) {
2158                    return -TARGET_EINVAL;
2159                }
2160                if (!lock_user_struct(VERIFY_READ, tlg, optval_addr, 1)) {
2161                    return -TARGET_EFAULT;
2162                }
2163                __get_user(lg.l_onoff, &tlg->l_onoff);
2164                __get_user(lg.l_linger, &tlg->l_linger);
2165                ret = get_errno(setsockopt(sockfd, SOL_SOCKET, SO_LINGER,
2166                                &lg, sizeof(lg)));
2167                unlock_user_struct(tlg, optval_addr, 0);
2168                return ret;
2169        }
2170            /* Options with 'int' argument.  */
2171        case TARGET_SO_DEBUG:
2172                optname = SO_DEBUG;
2173                break;
2174        case TARGET_SO_REUSEADDR:
2175                optname = SO_REUSEADDR;
2176                break;
2177#ifdef SO_REUSEPORT
2178        case TARGET_SO_REUSEPORT:
2179                optname = SO_REUSEPORT;
2180                break;
2181#endif
2182        case TARGET_SO_TYPE:
2183                optname = SO_TYPE;
2184                break;
2185        case TARGET_SO_ERROR:
2186                optname = SO_ERROR;
2187                break;
2188        case TARGET_SO_DONTROUTE:
2189                optname = SO_DONTROUTE;
2190                break;
2191        case TARGET_SO_BROADCAST:
2192                optname = SO_BROADCAST;
2193                break;
2194        case TARGET_SO_SNDBUF:
2195                optname = SO_SNDBUF;
2196                break;
2197        case TARGET_SO_SNDBUFFORCE:
2198                optname = SO_SNDBUFFORCE;
2199                break;
2200        case TARGET_SO_RCVBUF:
2201                optname = SO_RCVBUF;
2202                break;
2203        case TARGET_SO_RCVBUFFORCE:
2204                optname = SO_RCVBUFFORCE;
2205                break;
2206        case TARGET_SO_KEEPALIVE:
2207                optname = SO_KEEPALIVE;
2208                break;
2209        case TARGET_SO_OOBINLINE:
2210                optname = SO_OOBINLINE;
2211                break;
2212        case TARGET_SO_NO_CHECK:
2213                optname = SO_NO_CHECK;
2214                break;
2215        case TARGET_SO_PRIORITY:
2216                optname = SO_PRIORITY;
2217                break;
2218#ifdef SO_BSDCOMPAT
2219        case TARGET_SO_BSDCOMPAT:
2220                optname = SO_BSDCOMPAT;
2221                break;
2222#endif
2223        case TARGET_SO_PASSCRED:
2224                optname = SO_PASSCRED;
2225                break;
2226        case TARGET_SO_PASSSEC:
2227                optname = SO_PASSSEC;
2228                break;
2229        case TARGET_SO_TIMESTAMP:
2230                optname = SO_TIMESTAMP;
2231                break;
2232        case TARGET_SO_RCVLOWAT:
2233                optname = SO_RCVLOWAT;
2234                break;
2235        default:
2236            goto unimplemented;
2237        }
2238        if (optlen < sizeof(uint32_t))
2239            return -TARGET_EINVAL;
2240
2241        if (get_user_u32(val, optval_addr))
2242            return -TARGET_EFAULT;
2243        ret = get_errno(setsockopt(sockfd, SOL_SOCKET, optname, &val, sizeof(val)));
2244        break;
2245    default:
2246    unimplemented:
2247        gemu_log("Unsupported setsockopt level=%d optname=%d\n", level, optname);
2248        ret = -TARGET_ENOPROTOOPT;
2249    }
2250    return ret;
2251}
2252
2253/* do_getsockopt() Must return target values and target errnos. */
2254static abi_long do_getsockopt(int sockfd, int level, int optname,
2255                              abi_ulong optval_addr, abi_ulong optlen)
2256{
2257    abi_long ret;
2258    int len, val;
2259    socklen_t lv;
2260
2261    switch(level) {
2262    case TARGET_SOL_SOCKET:
2263        level = SOL_SOCKET;
2264        switch (optname) {
2265        /* These don't just return a single integer */
2266        case TARGET_SO_RCVTIMEO:
2267        case TARGET_SO_SNDTIMEO:
2268        case TARGET_SO_PEERNAME:
2269            goto unimplemented;
2270        case TARGET_SO_PEERCRED: {
2271            struct ucred cr;
2272            socklen_t crlen;
2273            struct target_ucred *tcr;
2274
2275            if (get_user_u32(len, optlen)) {
2276                return -TARGET_EFAULT;
2277            }
2278            if (len < 0) {
2279                return -TARGET_EINVAL;
2280            }
2281
2282            crlen = sizeof(cr);
2283            ret = get_errno(getsockopt(sockfd, level, SO_PEERCRED,
2284                                       &cr, &crlen));
2285            if (ret < 0) {
2286                return ret;
2287            }
2288            if (len > crlen) {
2289                len = crlen;
2290            }
2291            if (!lock_user_struct(VERIFY_WRITE, tcr, optval_addr, 0)) {
2292                return -TARGET_EFAULT;
2293            }
2294            __put_user(cr.pid, &tcr->pid);
2295            __put_user(cr.uid, &tcr->uid);
2296            __put_user(cr.gid, &tcr->gid);
2297            unlock_user_struct(tcr, optval_addr, 1);
2298            if (put_user_u32(len, optlen)) {
2299                return -TARGET_EFAULT;
2300            }
2301            break;
2302        }
2303        case TARGET_SO_LINGER:
2304        {
2305            struct linger lg;
2306            socklen_t lglen;
2307            struct target_linger *tlg;
2308
2309            if (get_user_u32(len, optlen)) {
2310                return -TARGET_EFAULT;
2311            }
2312            if (len < 0) {
2313                return -TARGET_EINVAL;
2314            }
2315
2316            lglen = sizeof(lg);
2317            ret = get_errno(getsockopt(sockfd, level, SO_LINGER,
2318                                       &lg, &lglen));
2319            if (ret < 0) {
2320                return ret;
2321            }
2322            if (len > lglen) {
2323                len = lglen;
2324            }
2325            if (!lock_user_struct(VERIFY_WRITE, tlg, optval_addr, 0)) {
2326                return -TARGET_EFAULT;
2327            }
2328            __put_user(lg.l_onoff, &tlg->l_onoff);
2329            __put_user(lg.l_linger, &tlg->l_linger);
2330            unlock_user_struct(tlg, optval_addr, 1);
2331            if (put_user_u32(len, optlen)) {
2332                return -TARGET_EFAULT;
2333            }
2334            break;
2335        }
2336        /* Options with 'int' argument.  */
2337        case TARGET_SO_DEBUG:
2338            optname = SO_DEBUG;
2339            goto int_case;
2340        case TARGET_SO_REUSEADDR:
2341            optname = SO_REUSEADDR;
2342            goto int_case;
2343#ifdef SO_REUSEPORT
2344        case TARGET_SO_REUSEPORT:
2345            optname = SO_REUSEPORT;
2346            goto int_case;
2347#endif
2348        case TARGET_SO_TYPE:
2349            optname = SO_TYPE;
2350            goto int_case;
2351        case TARGET_SO_ERROR:
2352            optname = SO_ERROR;
2353            goto int_case;
2354        case TARGET_SO_DONTROUTE:
2355            optname = SO_DONTROUTE;
2356            goto int_case;
2357        case TARGET_SO_BROADCAST:
2358            optname = SO_BROADCAST;
2359            goto int_case;
2360        case TARGET_SO_SNDBUF:
2361            optname = SO_SNDBUF;
2362            goto int_case;
2363        case TARGET_SO_RCVBUF:
2364            optname = SO_RCVBUF;
2365            goto int_case;
2366        case TARGET_SO_KEEPALIVE:
2367            optname = SO_KEEPALIVE;
2368            goto int_case;
2369        case TARGET_SO_OOBINLINE:
2370            optname = SO_OOBINLINE;
2371            goto int_case;
2372        case TARGET_SO_NO_CHECK:
2373            optname = SO_NO_CHECK;
2374            goto int_case;
2375        case TARGET_SO_PRIORITY:
2376            optname = SO_PRIORITY;
2377            goto int_case;
2378#ifdef SO_BSDCOMPAT
2379        case TARGET_SO_BSDCOMPAT:
2380            optname = SO_BSDCOMPAT;
2381            goto int_case;
2382#endif
2383        case TARGET_SO_PASSCRED:
2384            optname = SO_PASSCRED;
2385            goto int_case;
2386        case TARGET_SO_TIMESTAMP:
2387            optname = SO_TIMESTAMP;
2388            goto int_case;
2389        case TARGET_SO_RCVLOWAT:
2390            optname = SO_RCVLOWAT;
2391            goto int_case;
2392        case TARGET_SO_ACCEPTCONN:
2393            optname = SO_ACCEPTCONN;
2394            goto int_case;
2395        default:
2396            goto int_case;
2397        }
2398        break;
2399    case SOL_TCP:
2400        /* TCP options all take an 'int' value.  */
2401    int_case:
2402        if (get_user_u32(len, optlen))
2403            return -TARGET_EFAULT;
2404        if (len < 0)
2405            return -TARGET_EINVAL;
2406        lv = sizeof(lv);
2407        ret = get_errno(getsockopt(sockfd, level, optname, &val, &lv));
2408        if (ret < 0)
2409            return ret;
2410        if (optname == SO_TYPE) {
2411            val = host_to_target_sock_type(val);
2412        }
2413        if (len > lv)
2414            len = lv;
2415        if (len == 4) {
2416            if (put_user_u32(val, optval_addr))
2417                return -TARGET_EFAULT;
2418        } else {
2419            if (put_user_u8(val, optval_addr))
2420                return -TARGET_EFAULT;
2421        }
2422        if (put_user_u32(len, optlen))
2423            return -TARGET_EFAULT;
2424        break;
2425    case SOL_IP:
2426        switch(optname) {
2427        case IP_TOS:
2428        case IP_TTL:
2429        case IP_HDRINCL:
2430        case IP_ROUTER_ALERT:
2431        case IP_RECVOPTS:
2432        case IP_RETOPTS:
2433        case IP_PKTINFO:
2434        case IP_MTU_DISCOVER:
2435        case IP_RECVERR:
2436        case IP_RECVTOS:
2437#ifdef IP_FREEBIND
2438        case IP_FREEBIND:
2439#endif
2440        case IP_MULTICAST_TTL:
2441        case IP_MULTICAST_LOOP:
2442            if (get_user_u32(len, optlen))
2443                return -TARGET_EFAULT;
2444            if (len < 0)
2445                return -TARGET_EINVAL;
2446            lv = sizeof(lv);
2447            ret = get_errno(getsockopt(sockfd, level, optname, &val, &lv));
2448            if (ret < 0)
2449                return ret;
2450            if (len < sizeof(int) && len > 0 && val >= 0 && val < 255) {
2451                len = 1;
2452                if (put_user_u32(len, optlen)
2453                    || put_user_u8(val, optval_addr))
2454                    return -TARGET_EFAULT;
2455            } else {
2456                if (len > sizeof(int))
2457                    len = sizeof(int);
2458                if (put_user_u32(len, optlen)
2459                    || put_user_u32(val, optval_addr))
2460                    return -TARGET_EFAULT;
2461            }
2462            break;
2463        default:
2464            ret = -TARGET_ENOPROTOOPT;
2465            break;
2466        }
2467        break;
2468    case SOL_IPV6:
2469        switch (optname) {
2470        case IPV6_MTU_DISCOVER:
2471        case IPV6_MTU:
2472        case IPV6_V6ONLY:
2473        case IPV6_RECVPKTINFO:
2474        case IPV6_UNICAST_HOPS:
2475        case IPV6_MULTICAST_HOPS:
2476        case IPV6_MULTICAST_LOOP:
2477        case IPV6_RECVERR:
2478        case IPV6_RECVHOPLIMIT:
2479        case IPV6_2292HOPLIMIT:
2480        case IPV6_CHECKSUM:
2481        case IPV6_ADDRFORM:
2482        case IPV6_2292PKTINFO:
2483        case IPV6_RECVTCLASS:
2484        case IPV6_RECVRTHDR:
2485        case IPV6_2292RTHDR:
2486        case IPV6_RECVHOPOPTS:
2487        case IPV6_2292HOPOPTS:
2488        case IPV6_RECVDSTOPTS:
2489        case IPV6_2292DSTOPTS:
2490        case IPV6_TCLASS:
2491#ifdef IPV6_RECVPATHMTU
2492        case IPV6_RECVPATHMTU:
2493#endif
2494#ifdef IPV6_TRANSPARENT
2495        case IPV6_TRANSPARENT:
2496#endif
2497#ifdef IPV6_FREEBIND
2498        case IPV6_FREEBIND:
2499#endif
2500#ifdef IPV6_RECVORIGDSTADDR
2501        case IPV6_RECVORIGDSTADDR:
2502#endif
2503            if (get_user_u32(len, optlen))
2504                return -TARGET_EFAULT;
2505            if (len < 0)
2506                return -TARGET_EINVAL;
2507            lv = sizeof(lv);
2508            ret = get_errno(getsockopt(sockfd, level, optname, &val, &lv));
2509            if (ret < 0)
2510                return ret;
2511            if (len < sizeof(int) && len > 0 && val >= 0 && val < 255) {
2512                len = 1;
2513                if (put_user_u32(len, optlen)
2514                    || put_user_u8(val, optval_addr))
2515                    return -TARGET_EFAULT;
2516            } else {
2517                if (len > sizeof(int))
2518                    len = sizeof(int);
2519                if (put_user_u32(len, optlen)
2520                    || put_user_u32(val, optval_addr))
2521                    return -TARGET_EFAULT;
2522            }
2523            break;
2524        default:
2525            ret = -TARGET_ENOPROTOOPT;
2526            break;
2527        }
2528        break;
2529    default:
2530    unimplemented:
2531        gemu_log("getsockopt level=%d optname=%d not yet supported\n",
2532                 level, optname);
2533        ret = -TARGET_EOPNOTSUPP;
2534        break;
2535    }
2536    return ret;
2537}
2538
2539/* Convert target low/high pair representing file offset into the host
2540 * low/high pair. This function doesn't handle offsets bigger than 64 bits
2541 * as the kernel doesn't handle them either.
2542 */
2543static void target_to_host_low_high(abi_ulong tlow,
2544                                    abi_ulong thigh,
2545                                    unsigned long *hlow,
2546                                    unsigned long *hhigh)
2547{
2548    uint64_t off = tlow |
2549        ((unsigned long long)thigh << TARGET_LONG_BITS / 2) <<
2550        TARGET_LONG_BITS / 2;
2551
2552    *hlow = off;
2553    *hhigh = (off >> HOST_LONG_BITS / 2) >> HOST_LONG_BITS / 2;
2554}
2555
2556static struct iovec *lock_iovec(int type, abi_ulong target_addr,
2557                                abi_ulong count, int copy)
2558{
2559    struct target_iovec *target_vec;
2560    struct iovec *vec;
2561    abi_ulong total_len, max_len;
2562    int i;
2563    int err = 0;
2564    bool bad_address = false;
2565
2566    if (count == 0) {
2567        errno = 0;
2568        return NULL;
2569    }
2570    if (count > IOV_MAX) {
2571        errno = EINVAL;
2572        return NULL;
2573    }
2574
2575    vec = g_try_new0(struct iovec, count);
2576    if (vec == NULL) {
2577        errno = ENOMEM;
2578        return NULL;
2579    }
2580
2581    target_vec = lock_user(VERIFY_READ, target_addr,
2582                           count * sizeof(struct target_iovec), 1);
2583    if (target_vec == NULL) {
2584        err = EFAULT;
2585        goto fail2;
2586    }
2587
2588    /* ??? If host page size > target page size, this will result in a
2589       value larger than what we can actually support.  */
2590    max_len = 0x7fffffff & TARGET_PAGE_MASK;
2591    total_len = 0;
2592
2593    for (i = 0; i < count; i++) {
2594        abi_ulong base = tswapal(target_vec[i].iov_base);
2595        abi_long len = tswapal(target_vec[i].iov_len);
2596
2597        if (len < 0) {
2598            err = EINVAL;
2599            goto fail;
2600        } else if (len == 0) {
2601            /* Zero length pointer is ignored.  */
2602            vec[i].iov_base = 0;
2603        } else {
2604            vec[i].iov_base = lock_user(type, base, len, copy);
2605            /* If the first buffer pointer is bad, this is a fault.  But
2606             * subsequent bad buffers will result in a partial write; this
2607             * is realized by filling the vector with null pointers and
2608             * zero lengths. */
2609            if (!vec[i].iov_base) {
2610                if (i == 0) {
2611                    err = EFAULT;
2612                    goto fail;
2613                } else {
2614                    bad_address = true;
2615                }
2616            }
2617            if (bad_address) {
2618                len = 0;
2619            }
2620            if (len > max_len - total_len) {
2621                len = max_len - total_len;
2622            }
2623        }
2624        vec[i].iov_len = len;
2625        total_len += len;
2626    }
2627
2628    unlock_user(target_vec, target_addr, 0);
2629    return vec;
2630
2631 fail:
2632    while (--i >= 0) {
2633        if (tswapal(target_vec[i].iov_len) > 0) {
2634            unlock_user(vec[i].iov_base, tswapal(target_vec[i].iov_base), 0);
2635        }
2636    }
2637    unlock_user(target_vec, target_addr, 0);
2638 fail2:
2639    g_free(vec);
2640    errno = err;
2641    return NULL;
2642}
2643
2644static void unlock_iovec(struct iovec *vec, abi_ulong target_addr,
2645                         abi_ulong count, int copy)
2646{
2647    struct target_iovec *target_vec;
2648    int i;
2649
2650    target_vec = lock_user(VERIFY_READ, target_addr,
2651                           count * sizeof(struct target_iovec), 1);
2652    if (target_vec) {
2653        for (i = 0; i < count; i++) {
2654            abi_ulong base = tswapal(target_vec[i].iov_base);
2655            abi_long len = tswapal(target_vec[i].iov_len);
2656            if (len < 0) {
2657                break;
2658            }
2659            unlock_user(vec[i].iov_base, base, copy ? vec[i].iov_len : 0);
2660        }
2661        unlock_user(target_vec, target_addr, 0);
2662    }
2663
2664    g_free(vec);
2665}
2666
2667static inline int target_to_host_sock_type(int *type)
2668{
2669    int host_type = 0;
2670    int target_type = *type;
2671
2672    switch (target_type & TARGET_SOCK_TYPE_MASK) {
2673    case TARGET_SOCK_DGRAM:
2674        host_type = SOCK_DGRAM;
2675        break;
2676    case TARGET_SOCK_STREAM:
2677        host_type = SOCK_STREAM;
2678        break;
2679    default:
2680        host_type = target_type & TARGET_SOCK_TYPE_MASK;
2681        break;
2682    }
2683    if (target_type & TARGET_SOCK_CLOEXEC) {
2684#if defined(SOCK_CLOEXEC)
2685        host_type |= SOCK_CLOEXEC;
2686#else
2687        return -TARGET_EINVAL;
2688#endif
2689    }
2690    if (target_type & TARGET_SOCK_NONBLOCK) {
2691#if defined(SOCK_NONBLOCK)
2692        host_type |= SOCK_NONBLOCK;
2693#elif !defined(O_NONBLOCK)
2694        return -TARGET_EINVAL;
2695#endif
2696    }
2697    *type = host_type;
2698    return 0;
2699}
2700
2701/* Try to emulate socket type flags after socket creation.  */
2702static int sock_flags_fixup(int fd, int target_type)
2703{
2704#if !defined(SOCK_NONBLOCK) && defined(O_NONBLOCK)
2705    if (target_type & TARGET_SOCK_NONBLOCK) {
2706        int flags = fcntl(fd, F_GETFL);
2707        if (fcntl(fd, F_SETFL, O_NONBLOCK | flags) == -1) {
2708            close(fd);
2709            return -TARGET_EINVAL;
2710        }
2711    }
2712#endif
2713    return fd;
2714}
2715
2716/* do_socket() Must return target values and target errnos. */
2717static abi_long do_socket(int domain, int type, int protocol)
2718{
2719    int target_type = type;
2720    int ret;
2721
2722    ret = target_to_host_sock_type(&type);
2723    if (ret) {
2724        return ret;
2725    }
2726
2727    if (domain == PF_NETLINK && !(
2728#ifdef CONFIG_RTNETLINK
2729         protocol == NETLINK_ROUTE ||
2730#endif
2731         protocol == NETLINK_KOBJECT_UEVENT ||
2732         protocol == NETLINK_AUDIT)) {
2733        return -EPFNOSUPPORT;
2734    }
2735
2736    if (domain == AF_PACKET ||
2737        (domain == AF_INET && type == SOCK_PACKET)) {
2738        protocol = tswap16(protocol);
2739    }
2740
2741    ret = get_errno(socket(domain, type, protocol));
2742    if (ret >= 0) {
2743        ret = sock_flags_fixup(ret, target_type);
2744        if (type == SOCK_PACKET) {
2745            /* Manage an obsolete case :
2746             * if socket type is SOCK_PACKET, bind by name
2747             */
2748            fd_trans_register(ret, &target_packet_trans);
2749        } else if (domain == PF_NETLINK) {
2750            switch (protocol) {
2751#ifdef CONFIG_RTNETLINK
2752            case NETLINK_ROUTE:
2753                fd_trans_register(ret, &target_netlink_route_trans);
2754                break;
2755#endif
2756            case NETLINK_KOBJECT_UEVENT:
2757                /* nothing to do: messages are strings */
2758                break;
2759            case NETLINK_AUDIT:
2760                fd_trans_register(ret, &target_netlink_audit_trans);
2761                break;
2762            default:
2763                g_assert_not_reached();
2764            }
2765        }
2766    }
2767    return ret;
2768}
2769
2770/* do_bind() Must return target values and target errnos. */
2771static abi_long do_bind(int sockfd, abi_ulong target_addr,
2772                        socklen_t addrlen)
2773{
2774    void *addr;
2775    abi_long ret;
2776
2777    if ((int)addrlen < 0) {
2778        return -TARGET_EINVAL;
2779    }
2780
2781    addr = alloca(addrlen+1);
2782
2783    ret = target_to_host_sockaddr(sockfd, addr, target_addr, addrlen);
2784    if (ret)
2785        return ret;
2786
2787    return get_errno(bind(sockfd, addr, addrlen));
2788}
2789
2790/* do_connect() Must return target values and target errnos. */
2791static abi_long do_connect(int sockfd, abi_ulong target_addr,
2792                           socklen_t addrlen)
2793{
2794    void *addr;
2795    abi_long ret;
2796
2797    if ((int)addrlen < 0) {
2798        return -TARGET_EINVAL;
2799    }
2800
2801    addr = alloca(addrlen+1);
2802
2803    ret = target_to_host_sockaddr(sockfd, addr, target_addr, addrlen);
2804    if (ret)
2805        return ret;
2806
2807    return get_errno(safe_connect(sockfd, addr, addrlen));
2808}
2809
2810/* do_sendrecvmsg_locked() Must return target values and target errnos. */
2811static abi_long do_sendrecvmsg_locked(int fd, struct target_msghdr *msgp,
2812                                      int flags, int send)
2813{
2814    abi_long ret, len;
2815    struct msghdr msg;
2816    abi_ulong count;
2817    struct iovec *vec;
2818    abi_ulong target_vec;
2819
2820    if (msgp->msg_name) {
2821        msg.msg_namelen = tswap32(msgp->msg_namelen);
2822        msg.msg_name = alloca(msg.msg_namelen+1);
2823        ret = target_to_host_sockaddr(fd, msg.msg_name,
2824                                      tswapal(msgp->msg_name),
2825                                      msg.msg_namelen);
2826        if (ret == -TARGET_EFAULT) {
2827            /* For connected sockets msg_name and msg_namelen must
2828             * be ignored, so returning EFAULT immediately is wrong.
2829             * Instead, pass a bad msg_name to the host kernel, and
2830             * let it decide whether to return EFAULT or not.
2831             */
2832            msg.msg_name = (void *)-1;
2833        } else if (ret) {
2834            goto out2;
2835        }
2836    } else {
2837        msg.msg_name = NULL;
2838        msg.msg_namelen = 0;
2839    }
2840    msg.msg_controllen = 2 * tswapal(msgp->msg_controllen);
2841    msg.msg_control = alloca(msg.msg_controllen);
2842    memset(msg.msg_control, 0, msg.msg_controllen);
2843
2844    msg.msg_flags = tswap32(msgp->msg_flags);
2845
2846    count = tswapal(msgp->msg_iovlen);
2847    target_vec = tswapal(msgp->msg_iov);
2848
2849    if (count > IOV_MAX) {
2850        /* sendrcvmsg returns a different errno for this condition than
2851         * readv/writev, so we must catch it here before lock_iovec() does.
2852         */
2853        ret = -TARGET_EMSGSIZE;
2854        goto out2;
2855    }
2856
2857    vec = lock_iovec(send ? VERIFY_READ : VERIFY_WRITE,
2858                     target_vec, count, send);
2859    if (vec == NULL) {
2860        ret = -host_to_target_errno(errno);
2861        goto out2;
2862    }
2863    msg.msg_iovlen = count;
2864    msg.msg_iov = vec;
2865
2866    if (send) {
2867        if (fd_trans_target_to_host_data(fd)) {
2868            void *host_msg;
2869
2870            host_msg = g_malloc(msg.msg_iov->iov_len);
2871            memcpy(host_msg, msg.msg_iov->iov_base, msg.msg_iov->iov_len);
2872            ret = fd_trans_target_to_host_data(fd)(host_msg,
2873                                                   msg.msg_iov->iov_len);
2874            if (ret >= 0) {
2875                msg.msg_iov->iov_base = host_msg;
2876                ret = get_errno(safe_sendmsg(fd, &msg, flags));
2877            }
2878            g_free(host_msg);
2879        } else {
2880            ret = target_to_host_cmsg(&msg, msgp);
2881            if (ret == 0) {
2882                ret = get_errno(safe_sendmsg(fd, &msg, flags));
2883            }
2884        }
2885    } else {
2886        ret = get_errno(safe_recvmsg(fd, &msg, flags));
2887        if (!is_error(ret)) {
2888            len = ret;
2889            if (fd_trans_host_to_target_data(fd)) {
2890                ret = fd_trans_host_to_target_data(fd)(msg.msg_iov->iov_base,
2891                                               MIN(msg.msg_iov->iov_len, len));
2892            } else {
2893                ret = host_to_target_cmsg(msgp, &msg);
2894            }
2895            if (!is_error(ret)) {
2896                msgp->msg_namelen = tswap32(msg.msg_namelen);
2897                msgp->msg_flags = tswap32(msg.msg_flags);
2898                if (msg.msg_name != NULL && msg.msg_name != (void *)-1) {
2899                    ret = host_to_target_sockaddr(tswapal(msgp->msg_name),
2900                                    msg.msg_name, msg.msg_namelen);
2901                    if (ret) {
2902                        goto out;
2903                    }
2904                }
2905
2906                ret = len;
2907            }
2908        }
2909    }
2910
2911out:
2912    unlock_iovec(vec, target_vec, count, !send);
2913out2:
2914    return ret;
2915}
2916
2917static abi_long do_sendrecvmsg(int fd, abi_ulong target_msg,
2918                               int flags, int send)
2919{
2920    abi_long ret;
2921    struct target_msghdr *msgp;
2922
2923    if (!lock_user_struct(send ? VERIFY_READ : VERIFY_WRITE,
2924                          msgp,
2925                          target_msg,
2926                          send ? 1 : 0)) {
2927        return -TARGET_EFAULT;
2928    }
2929    ret = do_sendrecvmsg_locked(fd, msgp, flags, send);
2930    unlock_user_struct(msgp, target_msg, send ? 0 : 1);
2931    return ret;
2932}
2933
2934/* We don't rely on the C library to have sendmmsg/recvmmsg support,
2935 * so it might not have this *mmsg-specific flag either.
2936 */
2937#ifndef MSG_WAITFORONE
2938#define MSG_WAITFORONE 0x10000
2939#endif
2940
2941static abi_long do_sendrecvmmsg(int fd, abi_ulong target_msgvec,
2942                                unsigned int vlen, unsigned int flags,
2943                                int send)
2944{
2945    struct target_mmsghdr *mmsgp;
2946    abi_long ret = 0;
2947    int i;
2948
2949    if (vlen > UIO_MAXIOV) {
2950        vlen = UIO_MAXIOV;
2951    }
2952
2953    mmsgp = lock_user(VERIFY_WRITE, target_msgvec, sizeof(*mmsgp) * vlen, 1);
2954    if (!mmsgp) {
2955        return -TARGET_EFAULT;
2956    }
2957
2958    for (i = 0; i < vlen; i++) {
2959        ret = do_sendrecvmsg_locked(fd, &mmsgp[i].msg_hdr, flags, send);
2960        if (is_error(ret)) {
2961            break;
2962        }
2963        mmsgp[i].msg_len = tswap32(ret);
2964        /* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */
2965        if (flags & MSG_WAITFORONE) {
2966            flags |= MSG_DONTWAIT;
2967        }
2968    }
2969
2970    unlock_user(mmsgp, target_msgvec, sizeof(*mmsgp) * i);
2971
2972    /* Return number of datagrams sent if we sent any at all;
2973     * otherwise return the error.
2974     */
2975    if (i) {
2976        return i;
2977    }
2978    return ret;
2979}
2980
2981/* do_accept4() Must return target values and target errnos. */
2982static abi_long do_accept4(int fd, abi_ulong target_addr,
2983                           abi_ulong target_addrlen_addr, int flags)
2984{
2985    socklen_t addrlen, ret_addrlen;
2986    void *addr;
2987    abi_long ret;
2988    int host_flags;
2989
2990    host_flags = target_to_host_bitmask(flags, fcntl_flags_tbl);
2991
2992    if (target_addr == 0) {
2993        return get_errno(safe_accept4(fd, NULL, NULL, host_flags));
2994    }
2995
2996    /* linux returns EINVAL if addrlen pointer is invalid */
2997    if (get_user_u32(addrlen, target_addrlen_addr))
2998        return -TARGET_EINVAL;
2999
3000    if ((int)addrlen < 0) {
3001        return -TARGET_EINVAL;
3002    }
3003
3004    if (!access_ok(VERIFY_WRITE, target_addr, addrlen))
3005        return -TARGET_EINVAL;
3006
3007    addr = alloca(addrlen);
3008
3009    ret_addrlen = addrlen;
3010    ret = get_errno(safe_accept4(fd, addr, &ret_addrlen, host_flags));
3011    if (!is_error(ret)) {
3012        host_to_target_sockaddr(target_addr, addr, MIN(addrlen, ret_addrlen));
3013        if (put_user_u32(ret_addrlen, target_addrlen_addr)) {
3014            ret = -TARGET_EFAULT;
3015        }
3016    }
3017    return ret;
3018}
3019
3020/* do_getpeername() Must return target values and target errnos. */
3021static abi_long do_getpeername(int fd, abi_ulong target_addr,
3022                               abi_ulong target_addrlen_addr)
3023{
3024    socklen_t addrlen, ret_addrlen;
3025    void *addr;
3026    abi_long ret;
3027
3028    if (get_user_u32(addrlen, target_addrlen_addr))
3029        return -TARGET_EFAULT;
3030
3031    if ((int)addrlen < 0) {
3032        return -TARGET_EINVAL;
3033    }
3034
3035    if (!access_ok(VERIFY_WRITE, target_addr, addrlen))
3036        return -TARGET_EFAULT;
3037
3038    addr = alloca(addrlen);
3039
3040    ret_addrlen = addrlen;
3041    ret = get_errno(getpeername(fd, addr, &ret_addrlen));
3042    if (!is_error(ret)) {
3043        host_to_target_sockaddr(target_addr, addr, MIN(addrlen, ret_addrlen));
3044        if (put_user_u32(ret_addrlen, target_addrlen_addr)) {
3045            ret = -TARGET_EFAULT;
3046        }
3047    }
3048    return ret;
3049}
3050
3051/* do_getsockname() Must return target values and target errnos. */
3052static abi_long do_getsockname(int fd, abi_ulong target_addr,
3053                               abi_ulong target_addrlen_addr)
3054{
3055    socklen_t addrlen, ret_addrlen;
3056    void *addr;
3057    abi_long ret;
3058
3059    if (get_user_u32(addrlen, target_addrlen_addr))
3060        return -TARGET_EFAULT;
3061
3062    if ((int)addrlen < 0) {
3063        return -TARGET_EINVAL;
3064    }
3065
3066    if (!access_ok(VERIFY_WRITE, target_addr, addrlen))
3067        return -TARGET_EFAULT;
3068
3069    addr = alloca(addrlen);
3070
3071    ret_addrlen = addrlen;
3072    ret = get_errno(getsockname(fd, addr, &ret_addrlen));
3073    if (!is_error(ret)) {
3074        host_to_target_sockaddr(target_addr, addr, MIN(addrlen, ret_addrlen));
3075        if (put_user_u32(ret_addrlen, target_addrlen_addr)) {
3076            ret = -TARGET_EFAULT;
3077        }
3078    }
3079    return ret;
3080}
3081
3082/* do_socketpair() Must return target values and target errnos. */
3083static abi_long do_socketpair(int domain, int type, int protocol,
3084                              abi_ulong target_tab_addr)
3085{
3086    int tab[2];
3087    abi_long ret;
3088
3089    target_to_host_sock_type(&type);
3090
3091    ret = get_errno(socketpair(domain, type, protocol, tab));
3092    if (!is_error(ret)) {
3093        if (put_user_s32(tab[0], target_tab_addr)
3094            || put_user_s32(tab[1], target_tab_addr + sizeof(tab[0])))
3095            ret = -TARGET_EFAULT;
3096    }
3097    return ret;
3098}
3099
3100/* do_sendto() Must return target values and target errnos. */
3101static abi_long do_sendto(int fd, abi_ulong msg, size_t len, int flags,
3102                          abi_ulong target_addr, socklen_t addrlen)
3103{
3104    void *addr;
3105    void *host_msg;
3106    void *copy_msg = NULL;
3107    abi_long ret;
3108
3109    if ((int)addrlen < 0) {
3110        return -TARGET_EINVAL;
3111    }
3112
3113    host_msg = lock_user(VERIFY_READ, msg, len, 1);
3114    if (!host_msg)
3115        return -TARGET_EFAULT;
3116    if (fd_trans_target_to_host_data(fd)) {
3117        copy_msg = host_msg;
3118        host_msg = g_malloc(len);
3119        memcpy(host_msg, copy_msg, len);
3120        ret = fd_trans_target_to_host_data(fd)(host_msg, len);
3121        if (ret < 0) {
3122            goto fail;
3123        }
3124    }
3125    if (target_addr) {
3126        addr = alloca(addrlen+1);
3127        ret = target_to_host_sockaddr(fd, addr, target_addr, addrlen);
3128        if (ret) {
3129            goto fail;
3130        }
3131        ret = get_errno(safe_sendto(fd, host_msg, len, flags, addr, addrlen));
3132    } else {
3133        ret = get_errno(safe_sendto(fd, host_msg, len, flags, NULL, 0));
3134    }
3135fail:
3136    if (copy_msg) {
3137        g_free(host_msg);
3138        host_msg = copy_msg;
3139    }
3140    unlock_user(host_msg, msg, 0);
3141    return ret;
3142}
3143
3144/* do_recvfrom() Must return target values and target errnos. */
3145static abi_long do_recvfrom(int fd, abi_ulong msg, size_t len, int flags,
3146                            abi_ulong target_addr,
3147                            abi_ulong target_addrlen)
3148{
3149    socklen_t addrlen, ret_addrlen;
3150    void *addr;
3151    void *host_msg;
3152    abi_long ret;
3153
3154    host_msg = lock_user(VERIFY_WRITE, msg, len, 0);
3155    if (!host_msg)
3156        return -TARGET_EFAULT;
3157    if (target_addr) {
3158        if (get_user_u32(addrlen, target_addrlen)) {
3159            ret = -TARGET_EFAULT;
3160            goto fail;
3161        }
3162        if ((int)addrlen < 0) {
3163            ret = -TARGET_EINVAL;
3164            goto fail;
3165        }
3166        addr = alloca(addrlen);
3167        ret_addrlen = addrlen;
3168        ret = get_errno(safe_recvfrom(fd, host_msg, len, flags,
3169                                      addr, &ret_addrlen));
3170    } else {
3171        addr = NULL; /* To keep compiler quiet.  */
3172        addrlen = 0; /* To keep compiler quiet.  */
3173        ret = get_errno(safe_recvfrom(fd, host_msg, len, flags, NULL, 0));
3174    }
3175    if (!is_error(ret)) {
3176        if (fd_trans_host_to_target_data(fd)) {
3177            abi_long trans;
3178            trans = fd_trans_host_to_target_data(fd)(host_msg, MIN(ret, len));
3179            if (is_error(trans)) {
3180                ret = trans;
3181                goto fail;
3182            }
3183        }
3184        if (target_addr) {
3185            host_to_target_sockaddr(target_addr, addr,
3186                                    MIN(addrlen, ret_addrlen));
3187            if (put_user_u32(ret_addrlen, target_addrlen)) {
3188                ret = -TARGET_EFAULT;
3189                goto fail;
3190            }
3191        }
3192        unlock_user(host_msg, msg, len);
3193    } else {
3194fail:
3195        unlock_user(host_msg, msg, 0);
3196    }
3197    return ret;
3198}
3199
3200#ifdef TARGET_NR_socketcall
3201/* do_socketcall() must return target values and target errnos. */
3202static abi_long do_socketcall(int num, abi_ulong vptr)
3203{
3204    static const unsigned nargs[] = { /* number of arguments per operation */
3205        [TARGET_SYS_SOCKET] = 3,      /* domain, type, protocol */
3206        [TARGET_SYS_BIND] = 3,        /* fd, addr, addrlen */
3207        [TARGET_SYS_CONNECT] = 3,     /* fd, addr, addrlen */
3208        [TARGET_SYS_LISTEN] = 2,      /* fd, backlog */
3209        [TARGET_SYS_ACCEPT] = 3,      /* fd, addr, addrlen */
3210        [TARGET_SYS_GETSOCKNAME] = 3, /* fd, addr, addrlen */
3211        [TARGET_SYS_GETPEERNAME] = 3, /* fd, addr, addrlen */
3212        [TARGET_SYS_SOCKETPAIR] = 4,  /* domain, type, protocol, tab */
3213        [TARGET_SYS_SEND] = 4,        /* fd, msg, len, flags */
3214        [TARGET_SYS_RECV] = 4,        /* fd, msg, len, flags */
3215        [TARGET_SYS_SENDTO] = 6,      /* fd, msg, len, flags, addr, addrlen */
3216        [TARGET_SYS_RECVFROM] = 6,    /* fd, msg, len, flags, addr, addrlen */
3217        [TARGET_SYS_SHUTDOWN] = 2,    /* fd, how */
3218        [TARGET_SYS_SETSOCKOPT] = 5,  /* fd, level, optname, optval, optlen */
3219        [TARGET_SYS_GETSOCKOPT] = 5,  /* fd, level, optname, optval, optlen */
3220        [TARGET_SYS_SENDMSG] = 3,     /* fd, msg, flags */
3221        [TARGET_SYS_RECVMSG] = 3,     /* fd, msg, flags */
3222        [TARGET_SYS_ACCEPT4] = 4,     /* fd, addr, addrlen, flags */
3223        [TARGET_SYS_RECVMMSG] = 4,    /* fd, msgvec, vlen, flags */
3224        [TARGET_SYS_SENDMMSG] = 4,    /* fd, msgvec, vlen, flags */
3225    };
3226    abi_long a[6]; /* max 6 args */
3227    unsigned i;
3228
3229    /* check the range of the first argument num */
3230    /* (TARGET_SYS_SENDMMSG is the highest among TARGET_SYS_xxx) */
3231    if (num < 1 || num > TARGET_SYS_SENDMMSG) {
3232        return -TARGET_EINVAL;
3233    }
3234    /* ensure we have space for args */
3235    if (nargs[num] > ARRAY_SIZE(a)) {
3236        return -TARGET_EINVAL;
3237    }
3238    /* collect the arguments in a[] according to nargs[] */
3239    for (i = 0; i < nargs[num]; ++i) {
3240        if (get_user_ual(a[i], vptr + i * sizeof(abi_long)) != 0) {
3241            return -TARGET_EFAULT;
3242        }
3243    }
3244    /* now when we have the args, invoke the appropriate underlying function */
3245    switch (num) {
3246    case TARGET_SYS_SOCKET: /* domain, type, protocol */
3247        return do_socket(a[0], a[1], a[2]);
3248    case TARGET_SYS_BIND: /* sockfd, addr, addrlen */
3249        return do_bind(a[0], a[1], a[2]);
3250    case TARGET_SYS_CONNECT: /* sockfd, addr, addrlen */
3251        return do_connect(a[0], a[1], a[2]);
3252    case TARGET_SYS_LISTEN: /* sockfd, backlog */
3253        return get_errno(listen(a[0], a[1]));
3254    case TARGET_SYS_ACCEPT: /* sockfd, addr, addrlen */
3255        return do_accept4(a[0], a[1], a[2], 0);
3256    case TARGET_SYS_GETSOCKNAME: /* sockfd, addr, addrlen */
3257        return do_getsockname(a[0], a[1], a[2]);
3258    case TARGET_SYS_GETPEERNAME: /* sockfd, addr, addrlen */
3259        return do_getpeername(a[0], a[1], a[2]);
3260    case TARGET_SYS_SOCKETPAIR: /* domain, type, protocol, tab */
3261        return do_socketpair(a[0], a[1], a[2], a[3]);
3262    case TARGET_SYS_SEND: /* sockfd, msg, len, flags */
3263        return do_sendto(a[0], a[1], a[2], a[3], 0, 0);
3264    case TARGET_SYS_RECV: /* sockfd, msg, len, flags */
3265        return do_recvfrom(a[0], a[1], a[2], a[3], 0, 0);
3266    case TARGET_SYS_SENDTO: /* sockfd, msg, len, flags, addr, addrlen */
3267        return do_sendto(a[0], a[1], a[2], a[3], a[4], a[5]);
3268    case TARGET_SYS_RECVFROM: /* sockfd, msg, len, flags, addr, addrlen */
3269        return do_recvfrom(a[0], a[1], a[2], a[3], a[4], a[5]);
3270    case TARGET_SYS_SHUTDOWN: /* sockfd, how */
3271        return get_errno(shutdown(a[0], a[1]));
3272    case TARGET_SYS_SETSOCKOPT: /* sockfd, level, optname, optval, optlen */
3273        return do_setsockopt(a[0], a[1], a[2], a[3], a[4]);
3274    case TARGET_SYS_GETSOCKOPT: /* sockfd, level, optname, optval, optlen */
3275        return do_getsockopt(a[0], a[1], a[2], a[3], a[4]);
3276    case TARGET_SYS_SENDMSG: /* sockfd, msg, flags */
3277        return do_sendrecvmsg(a[0], a[1], a[2], 1);
3278    case TARGET_SYS_RECVMSG: /* sockfd, msg, flags */
3279        return do_sendrecvmsg(a[0], a[1], a[2], 0);
3280    case TARGET_SYS_ACCEPT4: /* sockfd, addr, addrlen, flags */
3281        return do_accept4(a[0], a[1], a[2], a[3]);
3282    case TARGET_SYS_RECVMMSG: /* sockfd, msgvec, vlen, flags */
3283        return do_sendrecvmmsg(a[0], a[1], a[2], a[3], 0);
3284    case TARGET_SYS_SENDMMSG: /* sockfd, msgvec, vlen, flags */
3285        return do_sendrecvmmsg(a[0], a[1], a[2], a[3], 1);
3286    default:
3287        gemu_log("Unsupported socketcall: %d\n", num);
3288        return -TARGET_EINVAL;
3289    }
3290}
3291#endif
3292
3293#define N_SHM_REGIONS   32
3294
3295static struct shm_region {
3296    abi_ulong start;
3297    abi_ulong size;
3298    bool in_use;
3299} shm_regions[N_SHM_REGIONS];
3300
3301#ifndef TARGET_SEMID64_DS
3302/* asm-generic version of this struct */
3303struct target_semid64_ds
3304{
3305  struct target_ipc_perm sem_perm;
3306  abi_ulong sem_otime;
3307#if TARGET_ABI_BITS == 32
3308  abi_ulong __unused1;
3309#endif
3310  abi_ulong sem_ctime;
3311#if TARGET_ABI_BITS == 32
3312  abi_ulong __unused2;
3313#endif
3314  abi_ulong sem_nsems;
3315  abi_ulong __unused3;
3316  abi_ulong __unused4;
3317};
3318#endif
3319
3320static inline abi_long target_to_host_ipc_perm(struct ipc_perm *host_ip,
3321                                               abi_ulong target_addr)
3322{
3323    struct target_ipc_perm *target_ip;
3324    struct target_semid64_ds *target_sd;
3325
3326    if (!lock_user_struct(VERIFY_READ, target_sd, target_addr, 1))
3327        return -TARGET_EFAULT;
3328    target_ip = &(target_sd->sem_perm);
3329    host_ip->__key = tswap32(target_ip->__key);
3330    host_ip->uid = tswap32(target_ip->uid);
3331    host_ip->gid = tswap32(target_ip->gid);
3332    host_ip->cuid = tswap32(target_ip->cuid);
3333    host_ip->cgid = tswap32(target_ip->cgid);
3334#if defined(TARGET_ALPHA) || defined(TARGET_MIPS) || defined(TARGET_PPC)
3335    host_ip->mode = tswap32(target_ip->mode);
3336#else
3337    host_ip->mode = tswap16(target_ip->mode);
3338#endif
3339#if defined(TARGET_PPC)
3340    host_ip->__seq = tswap32(target_ip->__seq);
3341#else
3342    host_ip->__seq = tswap16(target_ip->__seq);
3343#endif
3344    unlock_user_struct(target_sd, target_addr, 0);
3345    return 0;
3346}
3347
3348static inline abi_long host_to_target_ipc_perm(abi_ulong target_addr,
3349                                               struct ipc_perm *host_ip)
3350{
3351    struct target_ipc_perm *target_ip;
3352    struct target_semid64_ds *target_sd;
3353
3354    if (!lock_user_struct(VERIFY_WRITE, target_sd, target_addr, 0))
3355        return -TARGET_EFAULT;
3356    target_ip = &(target_sd->sem_perm);
3357    target_ip->__key = tswap32(host_ip->__key);
3358    target_ip->uid = tswap32(host_ip->uid);
3359    target_ip->gid = tswap32(host_ip->gid);
3360    target_ip->cuid = tswap32(host_ip->cuid);
3361    target_ip->cgid = tswap32(host_ip->cgid);
3362#if defined(TARGET_ALPHA) || defined(TARGET_MIPS) || defined(TARGET_PPC)
3363    target_ip->mode = tswap32(host_ip->mode);
3364#else
3365    target_ip->mode = tswap16(host_ip->mode);
3366#endif
3367#if defined(TARGET_PPC)
3368    target_ip->__seq = tswap32(host_ip->__seq);
3369#else
3370    target_ip->__seq = tswap16(host_ip->__seq);
3371#endif
3372    unlock_user_struct(target_sd, target_addr, 1);
3373    return 0;
3374}
3375
3376static inline abi_long target_to_host_semid_ds(struct semid_ds *host_sd,
3377                                               abi_ulong target_addr)
3378{
3379    struct target_semid64_ds *target_sd;
3380
3381    if (!lock_user_struct(VERIFY_READ, target_sd, target_addr, 1))
3382        return -TARGET_EFAULT;
3383    if (target_to_host_ipc_perm(&(host_sd->sem_perm),target_addr))
3384        return -TARGET_EFAULT;
3385    host_sd->sem_nsems = tswapal(target_sd->sem_nsems);
3386    host_sd->sem_otime = tswapal(target_sd->sem_otime);
3387    host_sd->sem_ctime = tswapal(target_sd->sem_ctime);
3388    unlock_user_struct(target_sd, target_addr, 0);
3389    return 0;
3390}
3391
3392static inline abi_long host_to_target_semid_ds(abi_ulong target_addr,
3393                                               struct semid_ds *host_sd)
3394{
3395    struct target_semid64_ds *target_sd;
3396
3397    if (!lock_user_struct(VERIFY_WRITE, target_sd, target_addr, 0))
3398        return -TARGET_EFAULT;
3399    if (host_to_target_ipc_perm(target_addr,&(host_sd->sem_perm)))
3400        return -TARGET_EFAULT;
3401    target_sd->sem_nsems = tswapal(host_sd->sem_nsems);
3402    target_sd->sem_otime = tswapal(host_sd->sem_otime);
3403    target_sd->sem_ctime = tswapal(host_sd->sem_ctime);
3404    unlock_user_struct(target_sd, target_addr, 1);
3405    return 0;
3406}
3407
3408struct target_seminfo {
3409    int semmap;
3410    int semmni;
3411    int semmns;
3412    int semmnu;
3413    int semmsl;
3414    int semopm;
3415    int semume;
3416    int semusz;
3417    int semvmx;
3418    int semaem;
3419};
3420
3421static inline abi_long host_to_target_seminfo(abi_ulong target_addr,
3422                                              struct seminfo *host_seminfo)
3423{
3424    struct target_seminfo *target_seminfo;
3425    if (!lock_user_struct(VERIFY_WRITE, target_seminfo, target_addr, 0))
3426        return -TARGET_EFAULT;
3427    __put_user(host_seminfo->semmap, &target_seminfo->semmap);
3428    __put_user(host_seminfo->semmni, &target_seminfo->semmni);
3429    __put_user(host_seminfo->semmns, &target_seminfo->semmns);
3430    __put_user(host_seminfo->semmnu, &target_seminfo->semmnu);
3431    __put_user(host_seminfo->semmsl, &target_seminfo->semmsl);
3432    __put_user(host_seminfo->semopm, &target_seminfo->semopm);
3433    __put_user(host_seminfo->semume, &target_seminfo->semume);
3434    __put_user(host_seminfo->semusz, &target_seminfo->semusz);
3435    __put_user(host_seminfo->semvmx, &target_seminfo->semvmx);
3436    __put_user(host_seminfo->semaem, &target_seminfo->semaem);
3437    unlock_user_struct(target_seminfo, target_addr, 1);
3438    return 0;
3439}
3440
3441union semun {
3442        int val;
3443        struct semid_ds *buf;
3444        unsigned short *array;
3445        struct seminfo *__buf;
3446};
3447
3448union target_semun {
3449        int val;
3450        abi_ulong buf;
3451        abi_ulong array;
3452        abi_ulong __buf;
3453};
3454
3455static inline abi_long target_to_host_semarray(int semid, unsigned short **host_array,
3456                                               abi_ulong target_addr)
3457{
3458    int nsems;
3459    unsigned short *array;
3460    union semun semun;
3461    struct semid_ds semid_ds;
3462    int i, ret;
3463
3464    semun.buf = &semid_ds;
3465
3466    ret = semctl(semid, 0, IPC_STAT, semun);
3467    if (ret == -1)
3468        return get_errno(ret);
3469
3470    nsems = semid_ds.sem_nsems;
3471
3472    *host_array = g_try_new(unsigned short, nsems);
3473    if (!*host_array) {
3474        return -TARGET_ENOMEM;
3475    }
3476    array = lock_user(VERIFY_READ, target_addr,
3477                      nsems*sizeof(unsigned short), 1);
3478    if (!array) {
3479        g_free(*host_array);
3480        return -TARGET_EFAULT;
3481    }
3482
3483    for(i=0; i<nsems; i++) {
3484        __get_user((*host_array)[i], &array[i]);
3485    }
3486    unlock_user(array, target_addr, 0);
3487
3488    return 0;
3489}
3490
3491static inline abi_long host_to_target_semarray(int semid, abi_ulong target_addr,
3492                                               unsigned short **host_array)
3493{
3494    int nsems;
3495    unsigned short *array;
3496    union semun semun;
3497    struct semid_ds semid_ds;
3498    int i, ret;
3499
3500    semun.buf = &semid_ds;
3501
3502    ret = semctl(semid, 0, IPC_STAT, semun);
3503    if (ret == -1)
3504        return get_errno(ret);
3505
3506    nsems = semid_ds.sem_nsems;
3507
3508    array = lock_user(VERIFY_WRITE, target_addr,
3509                      nsems*sizeof(unsigned short), 0);
3510    if (!array)
3511        return -TARGET_EFAULT;
3512
3513    for(i=0; i<nsems; i++) {
3514        __put_user((*host_array)[i], &array[i]);
3515    }
3516    g_free(*host_array);
3517    unlock_user(array, target_addr, 1);
3518
3519    return 0;
3520}
3521
3522static inline abi_long do_semctl(int semid, int semnum, int cmd,
3523                                 abi_ulong target_arg)
3524{
3525    union target_semun target_su = { .buf = target_arg };
3526    union semun arg;
3527    struct semid_ds dsarg;
3528    unsigned short *array = NULL;
3529    struct seminfo seminfo;
3530    abi_long ret = -TARGET_EINVAL;
3531    abi_long err;
3532    cmd &= 0xff;
3533
3534    switch( cmd ) {
3535        case GETVAL:
3536        case SETVAL:
3537            /* In 64 bit cross-endian situations, we will erroneously pick up
3538             * the wrong half of the union for the "val" element.  To rectify
3539             * this, the entire 8-byte structure is byteswapped, followed by
3540             * a swap of the 4 byte val field. In other cases, the data is
3541             * already in proper host byte order. */
3542            if (sizeof(target_su.val) != (sizeof(target_su.buf))) {
3543                target_su.buf = tswapal(target_su.buf);
3544                arg.val = tswap32(target_su.val);
3545            } else {
3546                arg.val = target_su.val;
3547            }
3548            ret = get_errno(semctl(semid, semnum, cmd, arg));
3549            break;
3550        case GETALL:
3551        case SETALL:
3552            err = target_to_host_semarray(semid, &array, target_su.array);
3553            if (err)
3554                return err;
3555            arg.array = array;
3556            ret = get_errno(semctl(semid, semnum, cmd, arg));
3557            err = host_to_target_semarray(semid, target_su.array, &array);
3558            if (err)
3559                return err;
3560            break;
3561        case IPC_STAT:
3562        case IPC_SET:
3563        case SEM_STAT:
3564            err = target_to_host_semid_ds(&dsarg, target_su.buf);
3565            if (err)
3566                return err;
3567            arg.buf = &dsarg;
3568            ret = get_errno(semctl(semid, semnum, cmd, arg));
3569            err = host_to_target_semid_ds(target_su.buf, &dsarg);
3570            if (err)
3571                return err;
3572            break;
3573        case IPC_INFO:
3574        case SEM_INFO:
3575            arg.__buf = &seminfo;
3576            ret = get_errno(semctl(semid, semnum, cmd, arg));
3577            err = host_to_target_seminfo(target_su.__buf, &seminfo);
3578            if (err)
3579                return err;
3580            break;
3581        case IPC_RMID:
3582        case GETPID:
3583        case GETNCNT:
3584        case GETZCNT:
3585            ret = get_errno(semctl(semid, semnum, cmd, NULL));
3586            break;
3587    }
3588
3589    return ret;
3590}
3591
3592struct target_sembuf {
3593    unsigned short sem_num;
3594    short sem_op;
3595    short sem_flg;
3596};
3597
3598static inline abi_long target_to_host_sembuf(struct sembuf *host_sembuf,
3599                                             abi_ulong target_addr,
3600                                             unsigned nsops)
3601{
3602    struct target_sembuf *target_sembuf;
3603    int i;
3604
3605    target_sembuf = lock_user(VERIFY_READ, target_addr,
3606                              nsops*sizeof(struct target_sembuf), 1);
3607    if (!target_sembuf)
3608        return -TARGET_EFAULT;
3609
3610    for(i=0; i<nsops; i++) {
3611        __get_user(host_sembuf[i].sem_num, &target_sembuf[i].sem_num);
3612        __get_user(host_sembuf[i].sem_op, &target_sembuf[i].sem_op);
3613        __get_user(host_sembuf[i].sem_flg, &target_sembuf[i].sem_flg);
3614    }
3615
3616    unlock_user(target_sembuf, target_addr, 0);
3617
3618    return 0;
3619}
3620
3621static inline abi_long do_semop(int semid, abi_long ptr, unsigned nsops)
3622{
3623    struct sembuf sops[nsops];
3624    abi_long ret;
3625
3626    if (target_to_host_sembuf(sops, ptr, nsops))
3627        return -TARGET_EFAULT;
3628
3629    ret = -TARGET_ENOSYS;
3630#ifdef __NR_semtimedop
3631    ret = get_errno(safe_semtimedop(semid, sops, nsops, NULL));
3632#endif
3633#ifdef __NR_ipc
3634    if (ret == -TARGET_ENOSYS) {
3635        ret = get_errno(safe_ipc(IPCOP_semtimedop, semid, nsops, 0, sops, 0));
3636    }
3637#endif
3638    return ret;
3639}
3640
3641struct target_msqid_ds
3642{
3643    struct target_ipc_perm msg_perm;
3644    abi_ulong msg_stime;
3645#if TARGET_ABI_BITS == 32
3646    abi_ulong __unused1;
3647#endif
3648    abi_ulong msg_rtime;
3649#if TARGET_ABI_BITS == 32
3650    abi_ulong __unused2;
3651#endif
3652    abi_ulong msg_ctime;
3653#if TARGET_ABI_BITS == 32
3654    abi_ulong __unused3;
3655#endif
3656    abi_ulong __msg_cbytes;
3657    abi_ulong msg_qnum;
3658    abi_ulong msg_qbytes;
3659    abi_ulong msg_lspid;
3660    abi_ulong msg_lrpid;
3661    abi_ulong __unused4;
3662    abi_ulong __unused5;
3663};
3664
3665static inline abi_long target_to_host_msqid_ds(struct msqid_ds *host_md,
3666                                               abi_ulong target_addr)
3667{
3668    struct target_msqid_ds *target_md;
3669
3670    if (!lock_user_struct(VERIFY_READ, target_md, target_addr, 1))
3671        return -TARGET_EFAULT;
3672    if (target_to_host_ipc_perm(&(host_md->msg_perm),target_addr))
3673        return -TARGET_EFAULT;
3674    host_md->msg_stime = tswapal(target_md->msg_stime);
3675    host_md->msg_rtime = tswapal(target_md->msg_rtime);
3676    host_md->msg_ctime = tswapal(target_md->msg_ctime);
3677    host_md->__msg_cbytes = tswapal(target_md->__msg_cbytes);
3678    host_md->msg_qnum = tswapal(target_md->msg_qnum);
3679    host_md->msg_qbytes = tswapal(target_md->msg_qbytes);
3680    host_md->msg_lspid = tswapal(target_md->msg_lspid);
3681    host_md->msg_lrpid = tswapal(target_md->msg_lrpid);
3682    unlock_user_struct(target_md, target_addr, 0);
3683    return 0;
3684}
3685
3686static inline abi_long host_to_target_msqid_ds(abi_ulong target_addr,
3687                                               struct msqid_ds *host_md)
3688{
3689    struct target_msqid_ds *target_md;
3690
3691    if (!lock_user_struct(VERIFY_WRITE, target_md, target_addr, 0))
3692        return -TARGET_EFAULT;
3693    if (host_to_target_ipc_perm(target_addr,&(host_md->msg_perm)))
3694        return -TARGET_EFAULT;
3695    target_md->msg_stime = tswapal(host_md->msg_stime);
3696    target_md->msg_rtime = tswapal(host_md->msg_rtime);
3697    target_md->msg_ctime = tswapal(host_md->msg_ctime);
3698    target_md->__msg_cbytes = tswapal(host_md->__msg_cbytes);
3699    target_md->msg_qnum = tswapal(host_md->msg_qnum);
3700    target_md->msg_qbytes = tswapal(host_md->msg_qbytes);
3701    target_md->msg_lspid = tswapal(host_md->msg_lspid);
3702    target_md->msg_lrpid = tswapal(host_md->msg_lrpid);
3703    unlock_user_struct(target_md, target_addr, 1);
3704    return 0;
3705}
3706
3707struct target_msginfo {
3708    int msgpool;
3709    int msgmap;
3710    int msgmax;
3711    int msgmnb;
3712    int msgmni;
3713    int msgssz;
3714    int msgtql;
3715    unsigned short int msgseg;
3716};
3717
3718static inline abi_long host_to_target_msginfo(abi_ulong target_addr,
3719                                              struct msginfo *host_msginfo)
3720{
3721    struct target_msginfo *target_msginfo;
3722    if (!lock_user_struct(VERIFY_WRITE, target_msginfo, target_addr, 0))
3723        return -TARGET_EFAULT;
3724    __put_user(host_msginfo->msgpool, &target_msginfo->msgpool);
3725    __put_user(host_msginfo->msgmap, &target_msginfo->msgmap);
3726    __put_user(host_msginfo->msgmax, &target_msginfo->msgmax);
3727    __put_user(host_msginfo->msgmnb, &target_msginfo->msgmnb);
3728    __put_user(host_msginfo->msgmni, &target_msginfo->msgmni);
3729    __put_user(host_msginfo->msgssz, &target_msginfo->msgssz);
3730    __put_user(host_msginfo->msgtql, &target_msginfo->msgtql);
3731    __put_user(host_msginfo->msgseg, &target_msginfo->msgseg);
3732    unlock_user_struct(target_msginfo, target_addr, 1);
3733    return 0;
3734}
3735
3736static inline abi_long do_msgctl(int msgid, int cmd, abi_long ptr)
3737{
3738    struct msqid_ds dsarg;
3739    struct msginfo msginfo;
3740    abi_long ret = -TARGET_EINVAL;
3741
3742    cmd &= 0xff;
3743
3744    switch (cmd) {
3745    case IPC_STAT:
3746    case IPC_SET:
3747    case MSG_STAT:
3748        if (target_to_host_msqid_ds(&dsarg,ptr))
3749            return -TARGET_EFAULT;
3750        ret = get_errno(msgctl(msgid, cmd, &dsarg));
3751        if (host_to_target_msqid_ds(ptr,&dsarg))
3752            return -TARGET_EFAULT;
3753        break;
3754    case IPC_RMID:
3755        ret = get_errno(msgctl(msgid, cmd, NULL));
3756        break;
3757    case IPC_INFO:
3758    case MSG_INFO:
3759        ret = get_errno(msgctl(msgid, cmd, (struct msqid_ds *)&msginfo));
3760        if (host_to_target_msginfo(ptr, &msginfo))
3761            return -TARGET_EFAULT;
3762        break;
3763    }
3764
3765    return ret;
3766}
3767
3768struct target_msgbuf {
3769    abi_long mtype;
3770    char        mtext[1];
3771};
3772
3773static inline abi_long do_msgsnd(int msqid, abi_long msgp,
3774                                 ssize_t msgsz, int msgflg)
3775{
3776    struct target_msgbuf *target_mb;
3777    struct msgbuf *host_mb;
3778    abi_long ret = 0;
3779
3780    if (msgsz < 0) {
3781        return -TARGET_EINVAL;
3782    }
3783
3784    if (!lock_user_struct(VERIFY_READ, target_mb, msgp, 0))
3785        return -TARGET_EFAULT;
3786    host_mb = g_try_malloc(msgsz + sizeof(long));
3787    if (!host_mb) {
3788        unlock_user_struct(target_mb, msgp, 0);
3789        return -TARGET_ENOMEM;
3790    }
3791    host_mb->mtype = (abi_long) tswapal(target_mb->mtype);
3792    memcpy(host_mb->mtext, target_mb->mtext, msgsz);
3793    ret = -TARGET_ENOSYS;
3794#ifdef __NR_msgsnd
3795    ret = get_errno(safe_msgsnd(msqid, host_mb, msgsz, msgflg));
3796#endif
3797#ifdef __NR_ipc
3798    if (ret == -TARGET_ENOSYS) {
3799        ret = get_errno(safe_ipc(IPCOP_msgsnd, msqid, msgsz, msgflg,
3800                                 host_mb, 0));
3801    }
3802#endif
3803    g_free(host_mb);
3804    unlock_user_struct(target_mb, msgp, 0);
3805
3806    return ret;
3807}
3808
3809static inline abi_long do_msgrcv(int msqid, abi_long msgp,
3810                                 ssize_t msgsz, abi_long msgtyp,
3811                                 int msgflg)
3812{
3813    struct target_msgbuf *target_mb;
3814    char *target_mtext;
3815    struct msgbuf *host_mb;
3816    abi_long ret = 0;
3817
3818    if (msgsz < 0) {
3819        return -TARGET_EINVAL;
3820    }
3821
3822    if (!lock_user_struct(VERIFY_WRITE, target_mb, msgp, 0))
3823        return -TARGET_EFAULT;
3824
3825    host_mb = g_try_malloc(msgsz + sizeof(long));
3826    if (!host_mb) {
3827        ret = -TARGET_ENOMEM;
3828        goto end;
3829    }
3830    ret = -TARGET_ENOSYS;
3831#ifdef __NR_msgrcv
3832    ret = get_errno(safe_msgrcv(msqid, host_mb, msgsz, msgtyp, msgflg));
3833#endif
3834#ifdef __NR_ipc
3835    if (ret == -TARGET_ENOSYS) {
3836        ret = get_errno(safe_ipc(IPCOP_CALL(1, IPCOP_msgrcv), msqid, msgsz,
3837                        msgflg, host_mb, msgtyp));
3838    }
3839#endif
3840
3841    if (ret > 0) {
3842        abi_ulong target_mtext_addr = msgp + sizeof(abi_ulong);
3843        target_mtext = lock_user(VERIFY_WRITE, target_mtext_addr, ret, 0);
3844        if (!target_mtext) {
3845            ret = -TARGET_EFAULT;
3846            goto end;
3847        }
3848        memcpy(target_mb->mtext, host_mb->mtext, ret);
3849        unlock_user(target_mtext, target_mtext_addr, ret);
3850    }
3851
3852    target_mb->mtype = tswapal(host_mb->mtype);
3853
3854end:
3855    if (target_mb)
3856        unlock_user_struct(target_mb, msgp, 1);
3857    g_free(host_mb);
3858    return ret;
3859}
3860
3861static inline abi_long target_to_host_shmid_ds(struct shmid_ds *host_sd,
3862                                               abi_ulong target_addr)
3863{
3864    struct target_shmid_ds *target_sd;
3865
3866    if (!lock_user_struct(VERIFY_READ, target_sd, target_addr, 1))
3867        return -TARGET_EFAULT;
3868    if (target_to_host_ipc_perm(&(host_sd->shm_perm), target_addr))
3869        return -TARGET_EFAULT;
3870    __get_user(host_sd->shm_segsz, &target_sd->shm_segsz);
3871    __get_user(host_sd->shm_atime, &target_sd->shm_atime);
3872    __get_user(host_sd->shm_dtime, &target_sd->shm_dtime);
3873    __get_user(host_sd->shm_ctime, &target_sd->shm_ctime);
3874    __get_user(host_sd->shm_cpid, &target_sd->shm_cpid);
3875    __get_user(host_sd->shm_lpid, &target_sd->shm_lpid);
3876    __get_user(host_sd->shm_nattch, &target_sd->shm_nattch);
3877    unlock_user_struct(target_sd, target_addr, 0);
3878    return 0;
3879}
3880
3881static inline abi_long host_to_target_shmid_ds(abi_ulong target_addr,
3882                                               struct shmid_ds *host_sd)
3883{
3884    struct target_shmid_ds *target_sd;
3885
3886    if (!lock_user_struct(VERIFY_WRITE, target_sd, target_addr, 0))
3887        return -TARGET_EFAULT;
3888    if (host_to_target_ipc_perm(target_addr, &(host_sd->shm_perm)))
3889        return -TARGET_EFAULT;
3890    __put_user(host_sd->shm_segsz, &target_sd->shm_segsz);
3891    __put_user(host_sd->shm_atime, &target_sd->shm_atime);
3892    __put_user(host_sd->shm_dtime, &target_sd->shm_dtime);
3893    __put_user(host_sd->shm_ctime, &target_sd->shm_ctime);
3894    __put_user(host_sd->shm_cpid, &target_sd->shm_cpid);
3895    __put_user(host_sd->shm_lpid, &target_sd->shm_lpid);
3896    __put_user(host_sd->shm_nattch, &target_sd->shm_nattch);
3897    unlock_user_struct(target_sd, target_addr, 1);
3898    return 0;
3899}
3900
3901struct  target_shminfo {
3902    abi_ulong shmmax;
3903    abi_ulong shmmin;
3904    abi_ulong shmmni;
3905    abi_ulong shmseg;
3906    abi_ulong shmall;
3907};
3908
3909static inline abi_long host_to_target_shminfo(abi_ulong target_addr,
3910                                              struct shminfo *host_shminfo)
3911{
3912    struct target_shminfo *target_shminfo;
3913    if (!lock_user_struct(VERIFY_WRITE, target_shminfo, target_addr, 0))
3914        return -TARGET_EFAULT;
3915    __put_user(host_shminfo->shmmax, &target_shminfo->shmmax);
3916    __put_user(host_shminfo->shmmin, &target_shminfo->shmmin);
3917    __put_user(host_shminfo->shmmni, &target_shminfo->shmmni);
3918    __put_user(host_shminfo->shmseg, &target_shminfo->shmseg);
3919    __put_user(host_shminfo->shmall, &target_shminfo->shmall);
3920    unlock_user_struct(target_shminfo, target_addr, 1);
3921    return 0;
3922}
3923
3924struct target_shm_info {
3925    int used_ids;
3926    abi_ulong shm_tot;
3927    abi_ulong shm_rss;
3928    abi_ulong shm_swp;
3929    abi_ulong swap_attempts;
3930    abi_ulong swap_successes;
3931};
3932
3933static inline abi_long host_to_target_shm_info(abi_ulong target_addr,
3934                                               struct shm_info *host_shm_info)
3935{
3936    struct target_shm_info *target_shm_info;
3937    if (!lock_user_struct(VERIFY_WRITE, target_shm_info, target_addr, 0))
3938        return -TARGET_EFAULT;
3939    __put_user(host_shm_info->used_ids, &target_shm_info->used_ids);
3940    __put_user(host_shm_info->shm_tot, &target_shm_info->shm_tot);
3941    __put_user(host_shm_info->shm_rss, &target_shm_info->shm_rss);
3942    __put_user(host_shm_info->shm_swp, &target_shm_info->shm_swp);
3943    __put_user(host_shm_info->swap_attempts, &target_shm_info->swap_attempts);
3944    __put_user(host_shm_info->swap_successes, &target_shm_info->swap_successes);
3945    unlock_user_struct(target_shm_info, target_addr, 1);
3946    return 0;
3947}
3948
3949static inline abi_long do_shmctl(int shmid, int cmd, abi_long buf)
3950{
3951    struct shmid_ds dsarg;
3952    struct shminfo shminfo;
3953    struct shm_info shm_info;
3954    abi_long ret = -TARGET_EINVAL;
3955
3956    cmd &= 0xff;
3957
3958    switch(cmd) {
3959    case IPC_STAT:
3960    case IPC_SET:
3961    case SHM_STAT:
3962        if (target_to_host_shmid_ds(&dsarg, buf))
3963            return -TARGET_EFAULT;
3964        ret = get_errno(shmctl(shmid, cmd, &dsarg));
3965        if (host_to_target_shmid_ds(buf, &dsarg))
3966            return -TARGET_EFAULT;
3967        break;
3968    case IPC_INFO:
3969        ret = get_errno(shmctl(shmid, cmd, (struct shmid_ds *)&shminfo));
3970        if (host_to_target_shminfo(buf, &shminfo))
3971            return -TARGET_EFAULT;
3972        break;
3973    case SHM_INFO:
3974        ret = get_errno(shmctl(shmid, cmd, (struct shmid_ds *)&shm_info));
3975        if (host_to_target_shm_info(buf, &shm_info))
3976            return -TARGET_EFAULT;
3977        break;
3978    case IPC_RMID:
3979    case SHM_LOCK:
3980    case SHM_UNLOCK:
3981        ret = get_errno(shmctl(shmid, cmd, NULL));
3982        break;
3983    }
3984
3985    return ret;
3986}
3987
3988#ifndef TARGET_FORCE_SHMLBA
3989/* For most architectures, SHMLBA is the same as the page size;
3990 * some architectures have larger values, in which case they should
3991 * define TARGET_FORCE_SHMLBA and provide a target_shmlba() function.
3992 * This corresponds to the kernel arch code defining __ARCH_FORCE_SHMLBA
3993 * and defining its own value for SHMLBA.
3994 *
3995 * The kernel also permits SHMLBA to be set by the architecture to a
3996 * value larger than the page size without setting __ARCH_FORCE_SHMLBA;
3997 * this means that addresses are rounded to the large size if
3998 * SHM_RND is set but addresses not aligned to that size are not rejected
3999 * as long as they are at least page-aligned. Since the only architecture
4000 * which uses this is ia64 this code doesn't provide for that oddity.
4001 */
4002static inline abi_ulong target_shmlba(CPUArchState *cpu_env)
4003{
4004    return TARGET_PAGE_SIZE;
4005}
4006#endif
4007
4008static inline abi_ulong do_shmat(CPUArchState *cpu_env,
4009                                 int shmid, abi_ulong shmaddr, int shmflg)
4010{
4011    abi_long raddr;
4012    void *host_raddr;
4013    struct shmid_ds shm_info;
4014    int i,ret;
4015    abi_ulong shmlba;
4016
4017    /* find out the length of the shared memory segment */
4018    ret = get_errno(shmctl(shmid, IPC_STAT, &shm_info));
4019    if (is_error(ret)) {
4020        /* can't get length, bail out */
4021        return ret;
4022    }
4023
4024    shmlba = target_shmlba(cpu_env);
4025
4026    if (shmaddr & (shmlba - 1)) {
4027        if (shmflg & SHM_RND) {
4028            shmaddr &= ~(shmlba - 1);
4029        } else {
4030            return -TARGET_EINVAL;
4031        }
4032    }
4033    if (!guest_range_valid(shmaddr, shm_info.shm_segsz)) {
4034        return -TARGET_EINVAL;
4035    }
4036
4037    mmap_lock();
4038
4039    if (shmaddr)
4040        host_raddr = shmat(shmid, (void *)g2h(shmaddr), shmflg);
4041    else {
4042        abi_ulong mmap_start;
4043
4044        /* In order to use the host shmat, we need to honor host SHMLBA.  */
4045        mmap_start = mmap_find_vma(0, shm_info.shm_segsz, MAX(SHMLBA, shmlba));
4046
4047        if (mmap_start == -1) {
4048            errno = ENOMEM;
4049            host_raddr = (void *)-1;
4050        } else
4051            host_raddr = shmat(shmid, g2h(mmap_start), shmflg | SHM_REMAP);
4052    }
4053
4054    if (host_raddr == (void *)-1) {
4055        mmap_unlock();
4056        return get_errno((long)host_raddr);
4057    }
4058    raddr=h2g((unsigned long)host_raddr);
4059
4060    page_set_flags(raddr, raddr + shm_info.shm_segsz,
4061                   PAGE_VALID | PAGE_READ |
4062                   ((shmflg & SHM_RDONLY)? 0 : PAGE_WRITE));
4063
4064    for (i = 0; i < N_SHM_REGIONS; i++) {
4065        if (!shm_regions[i].in_use) {
4066            shm_regions[i].in_use = true;
4067            shm_regions[i].start = raddr;
4068            shm_regions[i].size = shm_info.shm_segsz;
4069            break;
4070        }
4071    }
4072
4073    mmap_unlock();
4074    return raddr;
4075
4076}
4077
4078static inline abi_long do_shmdt(abi_ulong shmaddr)
4079{
4080    int i;
4081    abi_long rv;
4082
4083    mmap_lock();
4084
4085    for (i = 0; i < N_SHM_REGIONS; ++i) {
4086        if (shm_regions[i].in_use && shm_regions[i].start == shmaddr) {
4087            shm_regions[i].in_use = false;
4088            page_set_flags(shmaddr, shmaddr + shm_regions[i].size, 0);
4089            break;
4090        }
4091    }
4092    rv = get_errno(shmdt(g2h(shmaddr)));
4093
4094    mmap_unlock();
4095
4096    return rv;
4097}
4098
4099#ifdef TARGET_NR_ipc
4100/* ??? This only works with linear mappings.  */
4101/* do_ipc() must return target values and target errnos. */
4102static abi_long do_ipc(CPUArchState *cpu_env,
4103                       unsigned int call, abi_long first,
4104                       abi_long second, abi_long third,
4105                       abi_long ptr, abi_long fifth)
4106{
4107    int version;
4108    abi_long ret = 0;
4109
4110    version = call >> 16;
4111    call &= 0xffff;
4112
4113    switch (call) {
4114    case IPCOP_semop:
4115        ret = do_semop(first, ptr, second);
4116        break;
4117
4118    case IPCOP_semget:
4119        ret = get_errno(semget(first, second, third));
4120        break;
4121
4122    case IPCOP_semctl: {
4123        /* The semun argument to semctl is passed by value, so dereference the
4124         * ptr argument. */
4125        abi_ulong atptr;
4126        get_user_ual(atptr, ptr);
4127        ret = do_semctl(first, second, third, atptr);
4128        break;
4129    }
4130
4131    case IPCOP_msgget:
4132        ret = get_errno(msgget(first, second));
4133        break;
4134
4135    case IPCOP_msgsnd:
4136        ret = do_msgsnd(first, ptr, second, third);
4137        break;
4138
4139    case IPCOP_msgctl:
4140        ret = do_msgctl(first, second, ptr);
4141        break;
4142
4143    case IPCOP_msgrcv:
4144        switch (version) {
4145        case 0:
4146            {
4147                struct target_ipc_kludge {
4148                    abi_long msgp;
4149                    abi_long msgtyp;
4150                } *tmp;
4151
4152                if (!lock_user_struct(VERIFY_READ, tmp, ptr, 1)) {
4153                    ret = -TARGET_EFAULT;
4154                    break;
4155                }
4156
4157                ret = do_msgrcv(first, tswapal(tmp->msgp), second, tswapal(tmp->msgtyp), third);
4158
4159                unlock_user_struct(tmp, ptr, 0);
4160                break;
4161            }
4162        default:
4163            ret = do_msgrcv(first, ptr, second, fifth, third);
4164        }
4165        break;
4166
4167    case IPCOP_shmat:
4168        switch (version) {
4169        default:
4170        {
4171            abi_ulong raddr;
4172            raddr = do_shmat(cpu_env, first, ptr, second);
4173            if (is_error(raddr))
4174                return get_errno(raddr);
4175            if (put_user_ual(raddr, third))
4176                return -TARGET_EFAULT;
4177            break;
4178        }
4179        case 1:
4180            ret = -TARGET_EINVAL;
4181            break;
4182        }
4183        break;
4184    case IPCOP_shmdt:
4185        ret = do_shmdt(ptr);
4186        break;
4187
4188    case IPCOP_shmget:
4189        /* IPC_* flag values are the same on all linux platforms */
4190        ret = get_errno(shmget(first, second, third));
4191        break;
4192
4193        /* IPC_* and SHM_* command values are the same on all linux platforms */
4194    case IPCOP_shmctl:
4195        ret = do_shmctl(first, second, ptr);
4196        break;
4197    default:
4198        gemu_log("Unsupported ipc call: %d (version %d)\n", call, version);
4199        ret = -TARGET_ENOSYS;
4200        break;
4201    }
4202    return ret;
4203}
4204#endif
4205
4206/* kernel structure types definitions */
4207
4208#define STRUCT(name, ...) STRUCT_ ## name,
4209#define STRUCT_SPECIAL(name) STRUCT_ ## name,
4210enum {
4211#include "syscall_types.h"
4212STRUCT_MAX
4213};
4214#undef STRUCT
4215#undef STRUCT_SPECIAL
4216
4217#define STRUCT(name, ...) static const argtype struct_ ## name ## _def[] = {  __VA_ARGS__, TYPE_NULL };
4218#define STRUCT_SPECIAL(name)
4219#include "syscall_types.h"
4220#undef STRUCT
4221#undef STRUCT_SPECIAL
4222
4223typedef struct IOCTLEntry IOCTLEntry;
4224
4225typedef abi_long do_ioctl_fn(const IOCTLEntry *ie, uint8_t *buf_temp,
4226                             int fd, int cmd, abi_long arg);
4227
4228struct IOCTLEntry {
4229    int target_cmd;
4230    unsigned int host_cmd;
4231    const char *name;
4232    int access;
4233    do_ioctl_fn *do_ioctl;
4234    const argtype arg_type[5];
4235};
4236
4237#define IOC_R 0x0001
4238#define IOC_W 0x0002
4239#define IOC_RW (IOC_R | IOC_W)
4240
4241#define MAX_STRUCT_SIZE 4096
4242
4243#ifdef CONFIG_FIEMAP
4244/* So fiemap access checks don't overflow on 32 bit systems.
4245 * This is very slightly smaller than the limit imposed by
4246 * the underlying kernel.
4247 */
4248#define FIEMAP_MAX_EXTENTS ((UINT_MAX - sizeof(struct fiemap))  \
4249                            / sizeof(struct fiemap_extent))
4250
4251static abi_long do_ioctl_fs_ioc_fiemap(const IOCTLEntry *ie, uint8_t *buf_temp,
4252                                       int fd, int cmd, abi_long arg)
4253{
4254    /* The parameter for this ioctl is a struct fiemap followed
4255     * by an array of struct fiemap_extent whose size is set
4256     * in fiemap->fm_extent_count. The array is filled in by the
4257     * ioctl.
4258     */
4259    int target_size_in, target_size_out;
4260    struct fiemap *fm;
4261    const argtype *arg_type = ie->arg_type;
4262    const argtype extent_arg_type[] = { MK_STRUCT(STRUCT_fiemap_extent) };
4263    void *argptr, *p;
4264    abi_long ret;
4265    int i, extent_size = thunk_type_size(extent_arg_type, 0);
4266    uint32_t outbufsz;
4267    int free_fm = 0;
4268
4269    assert(arg_type[0] == TYPE_PTR);
4270    assert(ie->access == IOC_RW);
4271    arg_type++;
4272    target_size_in = thunk_type_size(arg_type, 0);
4273    argptr = lock_user(VERIFY_READ, arg, target_size_in, 1);
4274    if (!argptr) {
4275        return -TARGET_EFAULT;
4276    }
4277    thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
4278    unlock_user(argptr, arg, 0);
4279    fm = (struct fiemap *)buf_temp;
4280    if (fm->fm_extent_count > FIEMAP_MAX_EXTENTS) {
4281        return -TARGET_EINVAL;
4282    }
4283
4284    outbufsz = sizeof (*fm) +
4285        (sizeof(struct fiemap_extent) * fm->fm_extent_count);
4286
4287    if (outbufsz > MAX_STRUCT_SIZE) {
4288        /* We can't fit all the extents into the fixed size buffer.
4289         * Allocate one that is large enough and use it instead.
4290         */
4291        fm = g_try_malloc(outbufsz);
4292        if (!fm) {
4293            return -TARGET_ENOMEM;
4294        }
4295        memcpy(fm, buf_temp, sizeof(struct fiemap));
4296        free_fm = 1;
4297    }
4298    ret = get_errno(safe_ioctl(fd, ie->host_cmd, fm));
4299    if (!is_error(ret)) {
4300        target_size_out = target_size_in;
4301        /* An extent_count of 0 means we were only counting the extents
4302         * so there are no structs to copy
4303         */
4304        if (fm->fm_extent_count != 0) {
4305            target_size_out += fm->fm_mapped_extents * extent_size;
4306        }
4307        argptr = lock_user(VERIFY_WRITE, arg, target_size_out, 0);
4308        if (!argptr) {
4309            ret = -TARGET_EFAULT;
4310        } else {
4311            /* Convert the struct fiemap */
4312            thunk_convert(argptr, fm, arg_type, THUNK_TARGET);
4313            if (fm->fm_extent_count != 0) {
4314                p = argptr + target_size_in;
4315                /* ...and then all the struct fiemap_extents */
4316                for (i = 0; i < fm->fm_mapped_extents; i++) {
4317                    thunk_convert(p, &fm->fm_extents[i], extent_arg_type,
4318                                  THUNK_TARGET);
4319                    p += extent_size;
4320                }
4321            }
4322            unlock_user(argptr, arg, target_size_out);
4323        }
4324    }
4325    if (free_fm) {
4326        g_free(fm);
4327    }
4328    return ret;
4329}
4330#endif
4331
4332static abi_long do_ioctl_ifconf(const IOCTLEntry *ie, uint8_t *buf_temp,
4333                                int fd, int cmd, abi_long arg)
4334{
4335    const argtype *arg_type = ie->arg_type;
4336    int target_size;
4337    void *argptr;
4338    int ret;
4339    struct ifconf *host_ifconf;
4340    uint32_t outbufsz;
4341    const argtype ifreq_arg_type[] = { MK_STRUCT(STRUCT_sockaddr_ifreq) };
4342    int target_ifreq_size;
4343    int nb_ifreq;
4344    int free_buf = 0;
4345    int i;
4346    int target_ifc_len;
4347    abi_long target_ifc_buf;
4348    int host_ifc_len;
4349    char *host_ifc_buf;
4350
4351    assert(arg_type[0] == TYPE_PTR);
4352    assert(ie->access == IOC_RW);
4353
4354    arg_type++;
4355    target_size = thunk_type_size(arg_type, 0);
4356
4357    argptr = lock_user(VERIFY_READ, arg, target_size, 1);
4358    if (!argptr)
4359        return -TARGET_EFAULT;
4360    thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
4361    unlock_user(argptr, arg, 0);
4362
4363    host_ifconf = (struct ifconf *)(unsigned long)buf_temp;
4364    target_ifc_buf = (abi_long)(unsigned long)host_ifconf->ifc_buf;
4365    target_ifreq_size = thunk_type_size(ifreq_arg_type, 0);
4366
4367    if (target_ifc_buf != 0) {
4368        target_ifc_len = host_ifconf->ifc_len;
4369        nb_ifreq = target_ifc_len / target_ifreq_size;
4370        host_ifc_len = nb_ifreq * sizeof(struct ifreq);
4371
4372        outbufsz = sizeof(*host_ifconf) + host_ifc_len;
4373        if (outbufsz > MAX_STRUCT_SIZE) {
4374            /*
4375             * We can't fit all the extents into the fixed size buffer.
4376             * Allocate one that is large enough and use it instead.
4377             */
4378            host_ifconf = malloc(outbufsz);
4379            if (!host_ifconf) {
4380                return -TARGET_ENOMEM;
4381            }
4382            memcpy(host_ifconf, buf_temp, sizeof(*host_ifconf));
4383            free_buf = 1;
4384        }
4385        host_ifc_buf = (char *)host_ifconf + sizeof(*host_ifconf);
4386
4387        host_ifconf->ifc_len = host_ifc_len;
4388    } else {
4389      host_ifc_buf = NULL;
4390    }
4391    host_ifconf->ifc_buf = host_ifc_buf;
4392
4393    ret = get_errno(safe_ioctl(fd, ie->host_cmd, host_ifconf));
4394    if (!is_error(ret)) {
4395        /* convert host ifc_len to target ifc_len */
4396
4397        nb_ifreq = host_ifconf->ifc_len / sizeof(struct ifreq);
4398        target_ifc_len = nb_ifreq * target_ifreq_size;
4399        host_ifconf->ifc_len = target_ifc_len;
4400
4401        /* restore target ifc_buf */
4402
4403        host_ifconf->ifc_buf = (char *)(unsigned long)target_ifc_buf;
4404
4405        /* copy struct ifconf to target user */
4406
4407        argptr = lock_user(VERIFY_WRITE, arg, target_size, 0);
4408        if (!argptr)
4409            return -TARGET_EFAULT;
4410        thunk_convert(argptr, host_ifconf, arg_type, THUNK_TARGET);
4411        unlock_user(argptr, arg, target_size);
4412
4413        if (target_ifc_buf != 0) {
4414            /* copy ifreq[] to target user */
4415            argptr = lock_user(VERIFY_WRITE, target_ifc_buf, target_ifc_len, 0);
4416            for (i = 0; i < nb_ifreq ; i++) {
4417                thunk_convert(argptr + i * target_ifreq_size,
4418                              host_ifc_buf + i * sizeof(struct ifreq),
4419                              ifreq_arg_type, THUNK_TARGET);
4420            }
4421            unlock_user(argptr, target_ifc_buf, target_ifc_len);
4422        }
4423    }
4424
4425    if (free_buf) {
4426        free(host_ifconf);
4427    }
4428
4429    return ret;
4430}
4431
4432#if defined(CONFIG_USBFS)
4433#if HOST_LONG_BITS > 64
4434#error USBDEVFS thunks do not support >64 bit hosts yet.
4435#endif
4436struct live_urb {
4437    uint64_t target_urb_adr;
4438    uint64_t target_buf_adr;
4439    char *target_buf_ptr;
4440    struct usbdevfs_urb host_urb;
4441};
4442
4443static GHashTable *usbdevfs_urb_hashtable(void)
4444{
4445    static GHashTable *urb_hashtable;
4446
4447    if (!urb_hashtable) {
4448        urb_hashtable = g_hash_table_new(g_int64_hash, g_int64_equal);
4449    }
4450    return urb_hashtable;
4451}
4452
4453static void urb_hashtable_insert(struct live_urb *urb)
4454{
4455    GHashTable *urb_hashtable = usbdevfs_urb_hashtable();
4456    g_hash_table_insert(urb_hashtable, urb, urb);
4457}
4458
4459static struct live_urb *urb_hashtable_lookup(uint64_t target_urb_adr)
4460{
4461    GHashTable *urb_hashtable = usbdevfs_urb_hashtable();
4462    return g_hash_table_lookup(urb_hashtable, &target_urb_adr);
4463}
4464
4465static void urb_hashtable_remove(struct live_urb *urb)
4466{
4467    GHashTable *urb_hashtable = usbdevfs_urb_hashtable();
4468    g_hash_table_remove(urb_hashtable, urb);
4469}
4470
4471static abi_long
4472do_ioctl_usbdevfs_reapurb(const IOCTLEntry *ie, uint8_t *buf_temp,
4473                          int fd, int cmd, abi_long arg)
4474{
4475    const argtype usbfsurb_arg_type[] = { MK_STRUCT(STRUCT_usbdevfs_urb) };
4476    const argtype ptrvoid_arg_type[] = { TYPE_PTRVOID, 0, 0 };
4477    struct live_urb *lurb;
4478    void *argptr;
4479    uint64_t hurb;
4480    int target_size;
4481    uintptr_t target_urb_adr;
4482    abi_long ret;
4483
4484    target_size = thunk_type_size(usbfsurb_arg_type, THUNK_TARGET);
4485
4486    memset(buf_temp, 0, sizeof(uint64_t));
4487    ret = get_errno(safe_ioctl(fd, ie->host_cmd, buf_temp));
4488    if (is_error(ret)) {
4489        return ret;
4490    }
4491
4492    memcpy(&hurb, buf_temp, sizeof(uint64_t));
4493    lurb = (void *)((uintptr_t)hurb - offsetof(struct live_urb, host_urb));
4494    if (!lurb->target_urb_adr) {
4495        return -TARGET_EFAULT;
4496    }
4497    urb_hashtable_remove(lurb);
4498    unlock_user(lurb->target_buf_ptr, lurb->target_buf_adr,
4499        lurb->host_urb.buffer_length);
4500    lurb->target_buf_ptr = NULL;
4501
4502    /* restore the guest buffer pointer */
4503    lurb->host_urb.buffer = (void *)(uintptr_t)lurb->target_buf_adr;
4504
4505    /* update the guest urb struct */
4506    argptr = lock_user(VERIFY_WRITE, lurb->target_urb_adr, target_size, 0);
4507    if (!argptr) {
4508        g_free(lurb);
4509        return -TARGET_EFAULT;
4510    }
4511    thunk_convert(argptr, &lurb->host_urb, usbfsurb_arg_type, THUNK_TARGET);
4512    unlock_user(argptr, lurb->target_urb_adr, target_size);
4513
4514    target_size = thunk_type_size(ptrvoid_arg_type, THUNK_TARGET);
4515    /* write back the urb handle */
4516    argptr = lock_user(VERIFY_WRITE, arg, target_size, 0);
4517    if (!argptr) {
4518        g_free(lurb);
4519        return -TARGET_EFAULT;
4520    }
4521
4522    /* GHashTable uses 64-bit keys but thunk_convert expects uintptr_t */
4523    target_urb_adr = lurb->target_urb_adr;
4524    thunk_convert(argptr, &target_urb_adr, ptrvoid_arg_type, THUNK_TARGET);
4525    unlock_user(argptr, arg, target_size);
4526
4527    g_free(lurb);
4528    return ret;
4529}
4530
4531static abi_long
4532do_ioctl_usbdevfs_discardurb(const IOCTLEntry *ie,
4533                             uint8_t *buf_temp __attribute__((unused)),
4534                             int fd, int cmd, abi_long arg)
4535{
4536    struct live_urb *lurb;
4537
4538    /* map target address back to host URB with metadata. */
4539    lurb = urb_hashtable_lookup(arg);
4540    if (!lurb) {
4541        return -TARGET_EFAULT;
4542    }
4543    return get_errno(safe_ioctl(fd, ie->host_cmd, &lurb->host_urb));
4544}
4545
4546static abi_long
4547do_ioctl_usbdevfs_submiturb(const IOCTLEntry *ie, uint8_t *buf_temp,
4548                            int fd, int cmd, abi_long arg)
4549{
4550    const argtype *arg_type = ie->arg_type;
4551    int target_size;
4552    abi_long ret;
4553    void *argptr;
4554    int rw_dir;
4555    struct live_urb *lurb;
4556
4557    /*
4558     * each submitted URB needs to map to a unique ID for the
4559     * kernel, and that unique ID needs to be a pointer to
4560     * host memory.  hence, we need to malloc for each URB.
4561     * isochronous transfers have a variable length struct.
4562     */
4563    arg_type++;
4564    target_size = thunk_type_size(arg_type, THUNK_TARGET);
4565
4566    /* construct host copy of urb and metadata */
4567    lurb = g_try_malloc0(sizeof(struct live_urb));
4568    if (!lurb) {
4569        return -TARGET_ENOMEM;
4570    }
4571
4572    argptr = lock_user(VERIFY_READ, arg, target_size, 1);
4573    if (!argptr) {
4574        g_free(lurb);
4575        return -TARGET_EFAULT;
4576    }
4577    thunk_convert(&lurb->host_urb, argptr, arg_type, THUNK_HOST);
4578    unlock_user(argptr, arg, 0);
4579
4580    lurb->target_urb_adr = arg;
4581    lurb->target_buf_adr = (uintptr_t)lurb->host_urb.buffer;
4582
4583    /* buffer space used depends on endpoint type so lock the entire buffer */
4584    /* control type urbs should check the buffer contents for true direction */
4585    rw_dir = lurb->host_urb.endpoint & USB_DIR_IN ? VERIFY_WRITE : VERIFY_READ;
4586    lurb->target_buf_ptr = lock_user(rw_dir, lurb->target_buf_adr,
4587        lurb->host_urb.buffer_length, 1);
4588    if (lurb->target_buf_ptr == NULL) {
4589        g_free(lurb);
4590        return -TARGET_EFAULT;
4591    }
4592
4593    /* update buffer pointer in host copy */
4594    lurb->host_urb.buffer = lurb->target_buf_ptr;
4595
4596    ret = get_errno(safe_ioctl(fd, ie->host_cmd, &lurb->host_urb));
4597    if (is_error(ret)) {
4598        unlock_user(lurb->target_buf_ptr, lurb->target_buf_adr, 0);
4599        g_free(lurb);
4600    } else {
4601        urb_hashtable_insert(lurb);
4602    }
4603
4604    return ret;
4605}
4606#endif /* CONFIG_USBFS */
4607
4608static abi_long do_ioctl_dm(const IOCTLEntry *ie, uint8_t *buf_temp, int fd,
4609                            int cmd, abi_long arg)
4610{
4611    void *argptr;
4612    struct dm_ioctl *host_dm;
4613    abi_long guest_data;
4614    uint32_t guest_data_size;
4615    int target_size;
4616    const argtype *arg_type = ie->arg_type;
4617    abi_long ret;
4618    void *big_buf = NULL;
4619    char *host_data;
4620
4621    arg_type++;
4622    target_size = thunk_type_size(arg_type, 0);
4623    argptr = lock_user(VERIFY_READ, arg, target_size, 1);
4624    if (!argptr) {
4625        ret = -TARGET_EFAULT;
4626        goto out;
4627    }
4628    thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
4629    unlock_user(argptr, arg, 0);
4630
4631    /* buf_temp is too small, so fetch things into a bigger buffer */
4632    big_buf = g_malloc0(((struct dm_ioctl*)buf_temp)->data_size * 2);
4633    memcpy(big_buf, buf_temp, target_size);
4634    buf_temp = big_buf;
4635    host_dm = big_buf;
4636
4637    guest_data = arg + host_dm->data_start;
4638    if ((guest_data - arg) < 0) {
4639        ret = -TARGET_EINVAL;
4640        goto out;
4641    }
4642    guest_data_size = host_dm->data_size - host_dm->data_start;
4643    host_data = (char*)host_dm + host_dm->data_start;
4644
4645    argptr = lock_user(VERIFY_READ, guest_data, guest_data_size, 1);
4646    if (!argptr) {
4647        ret = -TARGET_EFAULT;
4648        goto out;
4649    }
4650
4651    switch (ie->host_cmd) {
4652    case DM_REMOVE_ALL:
4653    case DM_LIST_DEVICES:
4654    case DM_DEV_CREATE:
4655    case DM_DEV_REMOVE:
4656    case DM_DEV_SUSPEND:
4657    case DM_DEV_STATUS:
4658    case DM_DEV_WAIT:
4659    case DM_TABLE_STATUS:
4660    case DM_TABLE_CLEAR:
4661    case DM_TABLE_DEPS:
4662    case DM_LIST_VERSIONS:
4663        /* no input data */
4664        break;
4665    case DM_DEV_RENAME:
4666    case DM_DEV_SET_GEOMETRY:
4667        /* data contains only strings */
4668        memcpy(host_data, argptr, guest_data_size);
4669        break;
4670    case DM_TARGET_MSG:
4671        memcpy(host_data, argptr, guest_data_size);
4672        *(uint64_t*)host_data = tswap64(*(uint64_t*)argptr);
4673        break;
4674    case DM_TABLE_LOAD:
4675    {
4676        void *gspec = argptr;
4677        void *cur_data = host_data;
4678        const argtype arg_type[] = { MK_STRUCT(STRUCT_dm_target_spec) };
4679        int spec_size = thunk_type_size(arg_type, 0);
4680        int i;
4681
4682        for (i = 0; i < host_dm->target_count; i++) {
4683            struct dm_target_spec *spec = cur_data;
4684            uint32_t next;
4685            int slen;
4686
4687            thunk_convert(spec, gspec, arg_type, THUNK_HOST);
4688            slen = strlen((char*)gspec + spec_size) + 1;
4689            next = spec->next;
4690            spec->next = sizeof(*spec) + slen;
4691            strcpy((char*)&spec[1], gspec + spec_size);
4692            gspec += next;
4693            cur_data += spec->next;
4694        }
4695        break;
4696    }
4697    default:
4698        ret = -TARGET_EINVAL;
4699        unlock_user(argptr, guest_data, 0);
4700        goto out;
4701    }
4702    unlock_user(argptr, guest_data, 0);
4703
4704    ret = get_errno(safe_ioctl(fd, ie->host_cmd, buf_temp));
4705    if (!is_error(ret)) {
4706        guest_data = arg + host_dm->data_start;
4707        guest_data_size = host_dm->data_size - host_dm->data_start;
4708        argptr = lock_user(VERIFY_WRITE, guest_data, guest_data_size, 0);
4709        switch (ie->host_cmd) {
4710        case DM_REMOVE_ALL:
4711        case DM_DEV_CREATE:
4712        case DM_DEV_REMOVE:
4713        case DM_DEV_RENAME:
4714        case DM_DEV_SUSPEND:
4715        case DM_DEV_STATUS:
4716        case DM_TABLE_LOAD:
4717        case DM_TABLE_CLEAR:
4718        case DM_TARGET_MSG:
4719        case DM_DEV_SET_GEOMETRY:
4720            /* no return data */
4721            break;
4722        case DM_LIST_DEVICES:
4723        {
4724            struct dm_name_list *nl = (void*)host_dm + host_dm->data_start;
4725            uint32_t remaining_data = guest_data_size;
4726            void *cur_data = argptr;
4727            const argtype arg_type[] = { MK_STRUCT(STRUCT_dm_name_list) };
4728            int nl_size = 12; /* can't use thunk_size due to alignment */
4729
4730            while (1) {
4731                uint32_t next = nl->next;
4732                if (next) {
4733                    nl->next = nl_size + (strlen(nl->name) + 1);
4734                }
4735                if (remaining_data < nl->next) {
4736                    host_dm->flags |= DM_BUFFER_FULL_FLAG;
4737                    break;
4738                }
4739                thunk_convert(cur_data, nl, arg_type, THUNK_TARGET);
4740                strcpy(cur_data + nl_size, nl->name);
4741                cur_data += nl->next;
4742                remaining_data -= nl->next;
4743                if (!next) {
4744                    break;
4745                }
4746                nl = (void*)nl + next;
4747            }
4748            break;
4749        }
4750        case DM_DEV_WAIT:
4751        case DM_TABLE_STATUS:
4752        {
4753            struct dm_target_spec *spec = (void*)host_dm + host_dm->data_start;
4754            void *cur_data = argptr;
4755            const argtype arg_type[] = { MK_STRUCT(STRUCT_dm_target_spec) };
4756            int spec_size = thunk_type_size(arg_type, 0);
4757            int i;
4758
4759            for (i = 0; i < host_dm->target_count; i++) {
4760                uint32_t next = spec->next;
4761                int slen = strlen((char*)&spec[1]) + 1;
4762                spec->next = (cur_data - argptr) + spec_size + slen;
4763                if (guest_data_size < spec->next) {
4764                    host_dm->flags |= DM_BUFFER_FULL_FLAG;
4765                    break;
4766                }
4767                thunk_convert(cur_data, spec, arg_type, THUNK_TARGET);
4768                strcpy(cur_data + spec_size, (char*)&spec[1]);
4769                cur_data = argptr + spec->next;
4770                spec = (void*)host_dm + host_dm->data_start + next;
4771            }
4772            break;
4773        }
4774        case DM_TABLE_DEPS:
4775        {
4776            void *hdata = (void*)host_dm + host_dm->data_start;
4777            int count = *(uint32_t*)hdata;
4778            uint64_t *hdev = hdata + 8;
4779            uint64_t *gdev = argptr + 8;
4780            int i;
4781
4782            *(uint32_t*)argptr = tswap32(count);
4783            for (i = 0; i < count; i++) {
4784                *gdev = tswap64(*hdev);
4785                gdev++;
4786                hdev++;
4787            }
4788            break;
4789        }
4790        case DM_LIST_VERSIONS:
4791        {
4792            struct dm_target_versions *vers = (void*)host_dm + host_dm->data_start;
4793            uint32_t remaining_data = guest_data_size;
4794            void *cur_data = argptr;
4795            const argtype arg_type[] = { MK_STRUCT(STRUCT_dm_target_versions) };
4796            int vers_size = thunk_type_size(arg_type, 0);
4797
4798            while (1) {
4799                uint32_t next = vers->next;
4800                if (next) {
4801                    vers->next = vers_size + (strlen(vers->name) + 1);
4802                }
4803                if (remaining_data < vers->next) {
4804                    host_dm->flags |= DM_BUFFER_FULL_FLAG;
4805                    break;
4806                }
4807                thunk_convert(cur_data, vers, arg_type, THUNK_TARGET);
4808                strcpy(cur_data + vers_size, vers->name);
4809                cur_data += vers->next;
4810                remaining_data -= vers->next;
4811                if (!next) {
4812                    break;
4813                }
4814                vers = (void*)vers + next;
4815            }
4816            break;
4817        }
4818        default:
4819            unlock_user(argptr, guest_data, 0);
4820            ret = -TARGET_EINVAL;
4821            goto out;
4822        }
4823        unlock_user(argptr, guest_data, guest_data_size);
4824
4825        argptr = lock_user(VERIFY_WRITE, arg, target_size, 0);
4826        if (!argptr) {
4827            ret = -TARGET_EFAULT;
4828            goto out;
4829        }
4830        thunk_convert(argptr, buf_temp, arg_type, THUNK_TARGET);
4831        unlock_user(argptr, arg, target_size);
4832    }
4833out:
4834    g_free(big_buf);
4835    return ret;
4836}
4837
4838static abi_long do_ioctl_blkpg(const IOCTLEntry *ie, uint8_t *buf_temp, int fd,
4839                               int cmd, abi_long arg)
4840{
4841    void *argptr;
4842    int target_size;
4843    const argtype *arg_type = ie->arg_type;
4844    const argtype part_arg_type[] = { MK_STRUCT(STRUCT_blkpg_partition) };
4845    abi_long ret;
4846
4847    struct blkpg_ioctl_arg *host_blkpg = (void*)buf_temp;
4848    struct blkpg_partition host_part;
4849
4850    /* Read and convert blkpg */
4851    arg_type++;
4852    target_size = thunk_type_size(arg_type, 0);
4853    argptr = lock_user(VERIFY_READ, arg, target_size, 1);
4854    if (!argptr) {
4855        ret = -TARGET_EFAULT;
4856        goto out;
4857    }
4858    thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
4859    unlock_user(argptr, arg, 0);
4860
4861    switch (host_blkpg->op) {
4862    case BLKPG_ADD_PARTITION:
4863    case BLKPG_DEL_PARTITION:
4864        /* payload is struct blkpg_partition */
4865        break;
4866    default:
4867        /* Unknown opcode */
4868        ret = -TARGET_EINVAL;
4869        goto out;
4870    }
4871
4872    /* Read and convert blkpg->data */
4873    arg = (abi_long)(uintptr_t)host_blkpg->data;
4874    target_size = thunk_type_size(part_arg_type, 0);
4875    argptr = lock_user(VERIFY_READ, arg, target_size, 1);
4876    if (!argptr) {
4877        ret = -TARGET_EFAULT;
4878        goto out;
4879    }
4880    thunk_convert(&host_part, argptr, part_arg_type, THUNK_HOST);
4881    unlock_user(argptr, arg, 0);
4882
4883    /* Swizzle the data pointer to our local copy and call! */
4884    host_blkpg->data = &host_part;
4885    ret = get_errno(safe_ioctl(fd, ie->host_cmd, host_blkpg));
4886
4887out:
4888    return ret;
4889}
4890
4891static abi_long do_ioctl_rt(const IOCTLEntry *ie, uint8_t *buf_temp,
4892                                int fd, int cmd, abi_long arg)
4893{
4894    const argtype *arg_type = ie->arg_type;
4895    const StructEntry *se;
4896    const argtype *field_types;
4897    const int *dst_offsets, *src_offsets;
4898    int target_size;
4899    void *argptr;
4900    abi_ulong *target_rt_dev_ptr = NULL;
4901    unsigned long *host_rt_dev_ptr = NULL;
4902    abi_long ret;
4903    int i;
4904
4905    assert(ie->access == IOC_W);
4906    assert(*arg_type == TYPE_PTR);
4907    arg_type++;
4908    assert(*arg_type == TYPE_STRUCT);
4909    target_size = thunk_type_size(arg_type, 0);
4910    argptr = lock_user(VERIFY_READ, arg, target_size, 1);
4911    if (!argptr) {
4912        return -TARGET_EFAULT;
4913    }
4914    arg_type++;
4915    assert(*arg_type == (int)STRUCT_rtentry);
4916    se = struct_entries + *arg_type++;
4917    assert(se->convert[0] == NULL);
4918    /* convert struct here to be able to catch rt_dev string */
4919    field_types = se->field_types;
4920    dst_offsets = se->field_offsets[THUNK_HOST];
4921    src_offsets = se->field_offsets[THUNK_TARGET];
4922    for (i = 0; i < se->nb_fields; i++) {
4923        if (dst_offsets[i] == offsetof(struct rtentry, rt_dev)) {
4924            assert(*field_types == TYPE_PTRVOID);
4925            target_rt_dev_ptr = (abi_ulong *)(argptr + src_offsets[i]);
4926            host_rt_dev_ptr = (unsigned long *)(buf_temp + dst_offsets[i]);
4927            if (*target_rt_dev_ptr != 0) {
4928                *host_rt_dev_ptr = (unsigned long)lock_user_string(
4929                                                  tswapal(*target_rt_dev_ptr));
4930                if (!*host_rt_dev_ptr) {
4931                    unlock_user(argptr, arg, 0);
4932                    return -TARGET_EFAULT;
4933                }
4934            } else {
4935                *host_rt_dev_ptr = 0;
4936            }
4937            field_types++;
4938            continue;
4939        }
4940        field_types = thunk_convert(buf_temp + dst_offsets[i],
4941                                    argptr + src_offsets[i],
4942                                    field_types, THUNK_HOST);
4943    }
4944    unlock_user(argptr, arg, 0);
4945
4946    ret = get_errno(safe_ioctl(fd, ie->host_cmd, buf_temp));
4947
4948    assert(host_rt_dev_ptr != NULL);
4949    assert(target_rt_dev_ptr != NULL);
4950    if (*host_rt_dev_ptr != 0) {
4951        unlock_user((void *)*host_rt_dev_ptr,
4952                    *target_rt_dev_ptr, 0);
4953    }
4954    return ret;
4955}
4956
4957static abi_long do_ioctl_kdsigaccept(const IOCTLEntry *ie, uint8_t *buf_temp,
4958                                     int fd, int cmd, abi_long arg)
4959{
4960    int sig = target_to_host_signal(arg);
4961    return get_errno(safe_ioctl(fd, ie->host_cmd, sig));
4962}
4963
4964static abi_long do_ioctl_SIOCGSTAMP(const IOCTLEntry *ie, uint8_t *buf_temp,
4965                                    int fd, int cmd, abi_long arg)
4966{
4967    struct timeval tv;
4968    abi_long ret;
4969
4970    ret = get_errno(safe_ioctl(fd, SIOCGSTAMP, &tv));
4971    if (is_error(ret)) {
4972        return ret;
4973    }
4974
4975    if (cmd == (int)TARGET_SIOCGSTAMP_OLD) {
4976        if (copy_to_user_timeval(arg, &tv)) {
4977            return -TARGET_EFAULT;
4978        }
4979    } else {
4980        if (copy_to_user_timeval64(arg, &tv)) {
4981            return -TARGET_EFAULT;
4982        }
4983    }
4984
4985    return ret;
4986}
4987
4988static abi_long do_ioctl_SIOCGSTAMPNS(const IOCTLEntry *ie, uint8_t *buf_temp,
4989                                      int fd, int cmd, abi_long arg)
4990{
4991    struct timespec ts;
4992    abi_long ret;
4993
4994    ret = get_errno(safe_ioctl(fd, SIOCGSTAMPNS, &ts));
4995    if (is_error(ret)) {
4996        return ret;
4997    }
4998
4999    if (cmd == (int)TARGET_SIOCGSTAMPNS_OLD) {
5000        if (host_to_target_timespec(arg, &ts)) {
5001            return -TARGET_EFAULT;
5002        }
5003    } else{
5004        if (host_to_target_timespec64(arg, &ts)) {
5005            return -TARGET_EFAULT;
5006        }
5007    }
5008
5009    return ret;
5010}
5011
5012#ifdef TIOCGPTPEER
5013static abi_long do_ioctl_tiocgptpeer(const IOCTLEntry *ie, uint8_t *buf_temp,
5014                                     int fd, int cmd, abi_long arg)
5015{
5016    int flags = target_to_host_bitmask(arg, fcntl_flags_tbl);
5017    return get_errno(safe_ioctl(fd, ie->host_cmd, flags));
5018}
5019#endif
5020
5021static IOCTLEntry ioctl_entries[] = {
5022#define IOCTL(cmd, access, ...) \
5023    { TARGET_ ## cmd, cmd, #cmd, access, 0, {  __VA_ARGS__ } },
5024#define IOCTL_SPECIAL(cmd, access, dofn, ...)                      \
5025    { TARGET_ ## cmd, cmd, #cmd, access, dofn, {  __VA_ARGS__ } },
5026#define IOCTL_IGNORE(cmd) \
5027    { TARGET_ ## cmd, 0, #cmd },
5028#include "ioctls.h"
5029    { 0, 0, },
5030};
5031
5032/* ??? Implement proper locking for ioctls.  */
5033/* do_ioctl() Must return target values and target errnos. */
5034static abi_long do_ioctl(int fd, int cmd, abi_long arg)
5035{
5036    const IOCTLEntry *ie;
5037    const argtype *arg_type;
5038    abi_long ret;
5039    uint8_t buf_temp[MAX_STRUCT_SIZE];
5040    int target_size;
5041    void *argptr;
5042
5043    ie = ioctl_entries;
5044    for(;;) {
5045        if (ie->target_cmd == 0) {
5046            gemu_log("Unsupported ioctl: cmd=0x%04lx\n", (long)cmd);
5047            return -TARGET_ENOSYS;
5048        }
5049        if (ie->target_cmd == cmd)
5050            break;
5051        ie++;
5052    }
5053    arg_type = ie->arg_type;
5054    if (ie->do_ioctl) {
5055        return ie->do_ioctl(ie, buf_temp, fd, cmd, arg);
5056    } else if (!ie->host_cmd) {
5057        /* Some architectures define BSD ioctls in their headers
5058           that are not implemented in Linux.  */
5059        return -TARGET_ENOSYS;
5060    }
5061
5062    switch(arg_type[0]) {
5063    case TYPE_NULL:
5064        /* no argument */
5065        ret = get_errno(safe_ioctl(fd, ie->host_cmd));
5066        break;
5067    case TYPE_PTRVOID:
5068    case TYPE_INT:
5069        ret = get_errno(safe_ioctl(fd, ie->host_cmd, arg));
5070        break;
5071    case TYPE_PTR:
5072        arg_type++;
5073        target_size = thunk_type_size(arg_type, 0);
5074        switch(ie->access) {
5075        case IOC_R:
5076            ret = get_errno(safe_ioctl(fd, ie->host_cmd, buf_temp));
5077            if (!is_error(ret)) {
5078                argptr = lock_user(VERIFY_WRITE, arg, target_size, 0);
5079                if (!argptr)
5080                    return -TARGET_EFAULT;
5081                thunk_convert(argptr, buf_temp, arg_type, THUNK_TARGET);
5082                unlock_user(argptr, arg, target_size);
5083            }
5084            break;
5085        case IOC_W:
5086            argptr = lock_user(VERIFY_READ, arg, target_size, 1);
5087            if (!argptr)
5088                return -TARGET_EFAULT;
5089            thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
5090            unlock_user(argptr, arg, 0);
5091            ret = get_errno(safe_ioctl(fd, ie->host_cmd, buf_temp));
5092            break;
5093        default:
5094        case IOC_RW:
5095            argptr = lock_user(VERIFY_READ, arg, target_size, 1);
5096            if (!argptr)
5097                return -TARGET_EFAULT;
5098            thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
5099            unlock_user(argptr, arg, 0);
5100            ret = get_errno(safe_ioctl(fd, ie->host_cmd, buf_temp));
5101            if (!is_error(ret)) {
5102                argptr = lock_user(VERIFY_WRITE, arg, target_size, 0);
5103                if (!argptr)
5104                    return -TARGET_EFAULT;
5105                thunk_convert(argptr, buf_temp, arg_type, THUNK_TARGET);
5106                unlock_user(argptr, arg, target_size);
5107            }
5108            break;
5109        }
5110        break;
5111    default:
5112        gemu_log("Unsupported ioctl type: cmd=0x%04lx type=%d\n",
5113                 (long)cmd, arg_type[0]);
5114        ret = -TARGET_ENOSYS;
5115        break;
5116    }
5117    return ret;
5118}
5119
5120static const bitmask_transtbl iflag_tbl[] = {
5121        { TARGET_IGNBRK, TARGET_IGNBRK, IGNBRK, IGNBRK },
5122        { TARGET_BRKINT, TARGET_BRKINT, BRKINT, BRKINT },
5123        { TARGET_IGNPAR, TARGET_IGNPAR, IGNPAR, IGNPAR },
5124        { TARGET_PARMRK, TARGET_PARMRK, PARMRK, PARMRK },
5125        { TARGET_INPCK, TARGET_INPCK, INPCK, INPCK },
5126        { TARGET_ISTRIP, TARGET_ISTRIP, ISTRIP, ISTRIP },
5127        { TARGET_INLCR, TARGET_INLCR, INLCR, INLCR },
5128        { TARGET_IGNCR, TARGET_IGNCR, IGNCR, IGNCR },
5129        { TARGET_ICRNL, TARGET_ICRNL, ICRNL, ICRNL },
5130        { TARGET_IUCLC, TARGET_IUCLC, IUCLC, IUCLC },
5131        { TARGET_IXON, TARGET_IXON, IXON, IXON },
5132        { TARGET_IXANY, TARGET_IXANY, IXANY, IXANY },
5133        { TARGET_IXOFF, TARGET_IXOFF, IXOFF, IXOFF },
5134        { TARGET_IMAXBEL, TARGET_IMAXBEL, IMAXBEL, IMAXBEL },
5135        { 0, 0, 0, 0 }
5136};
5137
5138static const bitmask_transtbl oflag_tbl[] = {
5139        { TARGET_OPOST, TARGET_OPOST, OPOST, OPOST },
5140        { TARGET_OLCUC, TARGET_OLCUC, OLCUC, OLCUC },
5141        { TARGET_ONLCR, TARGET_ONLCR, ONLCR, ONLCR },
5142        { TARGET_OCRNL, TARGET_OCRNL, OCRNL, OCRNL },
5143        { TARGET_ONOCR, TARGET_ONOCR, ONOCR, ONOCR },
5144        { TARGET_ONLRET, TARGET_ONLRET, ONLRET, ONLRET },
5145        { TARGET_OFILL, TARGET_OFILL, OFILL, OFILL },
5146        { TARGET_OFDEL, TARGET_OFDEL, OFDEL, OFDEL },
5147        { TARGET_NLDLY, TARGET_NL0, NLDLY, NL0 },
5148        { TARGET_NLDLY, TARGET_NL1, NLDLY, NL1 },
5149        { TARGET_CRDLY, TARGET_CR0, CRDLY, CR0 },
5150        { TARGET_CRDLY, TARGET_CR1, CRDLY, CR1 },
5151        { TARGET_CRDLY, TARGET_CR2, CRDLY, CR2 },
5152        { TARGET_CRDLY, TARGET_CR3, CRDLY, CR3 },
5153        { TARGET_TABDLY, TARGET_TAB0, TABDLY, TAB0 },
5154        { TARGET_TABDLY, TARGET_TAB1, TABDLY, TAB1 },
5155        { TARGET_TABDLY, TARGET_TAB2, TABDLY, TAB2 },
5156        { TARGET_TABDLY, TARGET_TAB3, TABDLY, TAB3 },
5157        { TARGET_BSDLY, TARGET_BS0, BSDLY, BS0 },
5158        { TARGET_BSDLY, TARGET_BS1, BSDLY, BS1 },
5159        { TARGET_VTDLY, TARGET_VT0, VTDLY, VT0 },
5160        { TARGET_VTDLY, TARGET_VT1, VTDLY, VT1 },
5161        { TARGET_FFDLY, TARGET_FF0, FFDLY, FF0 },
5162        { TARGET_FFDLY, TARGET_FF1, FFDLY, FF1 },
5163        { 0, 0, 0, 0 }
5164};
5165
5166static const bitmask_transtbl cflag_tbl[] = {
5167        { TARGET_CBAUD, TARGET_B0, CBAUD, B0 },
5168        { TARGET_CBAUD, TARGET_B50, CBAUD, B50 },
5169        { TARGET_CBAUD, TARGET_B75, CBAUD, B75 },
5170        { TARGET_CBAUD, TARGET_B110, CBAUD, B110 },
5171        { TARGET_CBAUD, TARGET_B134, CBAUD, B134 },
5172        { TARGET_CBAUD, TARGET_B150, CBAUD, B150 },
5173        { TARGET_CBAUD, TARGET_B200, CBAUD, B200 },
5174        { TARGET_CBAUD, TARGET_B300, CBAUD, B300 },
5175        { TARGET_CBAUD, TARGET_B600, CBAUD, B600 },
5176        { TARGET_CBAUD, TARGET_B1200, CBAUD, B1200 },
5177        { TARGET_CBAUD, TARGET_B1800, CBAUD, B1800 },
5178        { TARGET_CBAUD, TARGET_B2400, CBAUD, B2400 },
5179        { TARGET_CBAUD, TARGET_B4800, CBAUD, B4800 },
5180        { TARGET_CBAUD, TARGET_B9600, CBAUD, B9600 },
5181        { TARGET_CBAUD, TARGET_B19200, CBAUD, B19200 },
5182        { TARGET_CBAUD, TARGET_B38400, CBAUD, B38400 },
5183        { TARGET_CBAUD, TARGET_B57600, CBAUD, B57600 },
5184        { TARGET_CBAUD, TARGET_B115200, CBAUD, B115200 },
5185        { TARGET_CBAUD, TARGET_B230400, CBAUD, B230400 },
5186        { TARGET_CBAUD, TARGET_B460800, CBAUD, B460800 },
5187        { TARGET_CSIZE, TARGET_CS5, CSIZE, CS5 },
5188        { TARGET_CSIZE, TARGET_CS6, CSIZE, CS6 },
5189        { TARGET_CSIZE, TARGET_CS7, CSIZE, CS7 },
5190        { TARGET_CSIZE, TARGET_CS8, CSIZE, CS8 },
5191        { TARGET_CSTOPB, TARGET_CSTOPB, CSTOPB, CSTOPB },
5192        { TARGET_CREAD, TARGET_CREAD, CREAD, CREAD },
5193        { TARGET_PARENB, TARGET_PARENB, PARENB, PARENB },
5194        { TARGET_PARODD, TARGET_PARODD, PARODD, PARODD },
5195        { TARGET_HUPCL, TARGET_HUPCL, HUPCL, HUPCL },
5196        { TARGET_CLOCAL, TARGET_CLOCAL, CLOCAL, CLOCAL },
5197        { TARGET_CRTSCTS, TARGET_CRTSCTS, CRTSCTS, CRTSCTS },
5198        { 0, 0, 0, 0 }
5199};
5200
5201static const bitmask_transtbl lflag_tbl[] = {
5202        { TARGET_ISIG, TARGET_ISIG, ISIG, ISIG },
5203        { TARGET_ICANON, TARGET_ICANON, ICANON, ICANON },
5204        { TARGET_XCASE, TARGET_XCASE, XCASE, XCASE },
5205        { TARGET_ECHO, TARGET_ECHO, ECHO, ECHO },
5206        { TARGET_ECHOE, TARGET_ECHOE, ECHOE, ECHOE },
5207        { TARGET_ECHOK, TARGET_ECHOK, ECHOK, ECHOK },
5208        { TARGET_ECHONL, TARGET_ECHONL, ECHONL, ECHONL },
5209        { TARGET_NOFLSH, TARGET_NOFLSH, NOFLSH, NOFLSH },
5210        { TARGET_TOSTOP, TARGET_TOSTOP, TOSTOP, TOSTOP },
5211        { TARGET_ECHOCTL, TARGET_ECHOCTL, ECHOCTL, ECHOCTL },
5212        { TARGET_ECHOPRT, TARGET_ECHOPRT, ECHOPRT, ECHOPRT },
5213        { TARGET_ECHOKE, TARGET_ECHOKE, ECHOKE, ECHOKE },
5214        { TARGET_FLUSHO, TARGET_FLUSHO, FLUSHO, FLUSHO },
5215        { TARGET_PENDIN, TARGET_PENDIN, PENDIN, PENDIN },
5216        { TARGET_IEXTEN, TARGET_IEXTEN, IEXTEN, IEXTEN },
5217        { 0, 0, 0, 0 }
5218};
5219
5220static void target_to_host_termios (void *dst, const void *src)
5221{
5222    struct host_termios *host = dst;
5223    const struct target_termios *target = src;
5224
5225    host->c_iflag =
5226        target_to_host_bitmask(tswap32(target->c_iflag), iflag_tbl);
5227    host->c_oflag =
5228        target_to_host_bitmask(tswap32(target->c_oflag), oflag_tbl);
5229    host->c_cflag =
5230        target_to_host_bitmask(tswap32(target->c_cflag), cflag_tbl);
5231    host->c_lflag =
5232        target_to_host_bitmask(tswap32(target->c_lflag), lflag_tbl);
5233    host->c_line = target->c_line;
5234
5235    memset(host->c_cc, 0, sizeof(host->c_cc));
5236    host->c_cc[VINTR] = target->c_cc[TARGET_VINTR];
5237    host->c_cc[VQUIT] = target->c_cc[TARGET_VQUIT];
5238    host->c_cc[VERASE] = target->c_cc[TARGET_VERASE];
5239    host->c_cc[VKILL] = target->c_cc[TARGET_VKILL];
5240    host->c_cc[VEOF] = target->c_cc[TARGET_VEOF];
5241    host->c_cc[VTIME] = target->c_cc[TARGET_VTIME];
5242    host->c_cc[VMIN] = target->c_cc[TARGET_VMIN];
5243    host->c_cc[VSWTC] = target->c_cc[TARGET_VSWTC];
5244    host->c_cc[VSTART] = target->c_cc[TARGET_VSTART];
5245    host->c_cc[VSTOP] = target->c_cc[TARGET_VSTOP];
5246    host->c_cc[VSUSP] = target->c_cc[TARGET_VSUSP];
5247    host->c_cc[VEOL] = target->c_cc[TARGET_VEOL];
5248    host->c_cc[VREPRINT] = target->c_cc[TARGET_VREPRINT];
5249    host->c_cc[VDISCARD] = target->c_cc[TARGET_VDISCARD];
5250    host->c_cc[VWERASE] = target->c_cc[TARGET_VWERASE];
5251    host->c_cc[VLNEXT] = target->c_cc[TARGET_VLNEXT];
5252    host->c_cc[VEOL2] = target->c_cc[TARGET_VEOL2];
5253}
5254
5255static void host_to_target_termios (void *dst, const void *src)
5256{
5257    struct target_termios *target = dst;
5258    const struct host_termios *host = src;
5259
5260    target->c_iflag =
5261        tswap32(host_to_target_bitmask(host->c_iflag, iflag_tbl));
5262    target->c_oflag =
5263        tswap32(host_to_target_bitmask(host->c_oflag, oflag_tbl));
5264    target->c_cflag =
5265        tswap32(host_to_target_bitmask(host->c_cflag, cflag_tbl));
5266    target->c_lflag =
5267        tswap32(host_to_target_bitmask(host->c_lflag, lflag_tbl));
5268    target->c_line = host->c_line;
5269
5270    memset(target->c_cc, 0, sizeof(target->c_cc));
5271    target->c_cc[TARGET_VINTR] = host->c_cc[VINTR];
5272    target->c_cc[TARGET_VQUIT] = host->c_cc[VQUIT];
5273    target->c_cc[TARGET_VERASE] = host->c_cc[VERASE];
5274    target->c_cc[TARGET_VKILL] = host->c_cc[VKILL];
5275    target->c_cc[TARGET_VEOF] = host->c_cc[VEOF];
5276    target->c_cc[TARGET_VTIME] = host->c_cc[VTIME];
5277    target->c_cc[TARGET_VMIN] = host->c_cc[VMIN];
5278    target->c_cc[TARGET_VSWTC] = host->c_cc[VSWTC];
5279    target->c_cc[TARGET_VSTART] = host->c_cc[VSTART];
5280    target->c_cc[TARGET_VSTOP] = host->c_cc[VSTOP];
5281    target->c_cc[TARGET_VSUSP] = host->c_cc[VSUSP];
5282    target->c_cc[TARGET_VEOL] = host->c_cc[VEOL];
5283    target->c_cc[TARGET_VREPRINT] = host->c_cc[VREPRINT];
5284    target->c_cc[TARGET_VDISCARD] = host->c_cc[VDISCARD];
5285    target->c_cc[TARGET_VWERASE] = host->c_cc[VWERASE];
5286    target->c_cc[TARGET_VLNEXT] = host->c_cc[VLNEXT];
5287    target->c_cc[TARGET_VEOL2] = host->c_cc[VEOL2];
5288}
5289
5290static const StructEntry struct_termios_def = {
5291    .convert = { host_to_target_termios, target_to_host_termios },
5292    .size = { sizeof(struct target_termios), sizeof(struct host_termios) },
5293    .align = { __alignof__(struct target_termios), __alignof__(struct host_termios) },
5294};
5295
5296static bitmask_transtbl mmap_flags_tbl[] = {
5297    { TARGET_MAP_SHARED, TARGET_MAP_SHARED, MAP_SHARED, MAP_SHARED },
5298    { TARGET_MAP_PRIVATE, TARGET_MAP_PRIVATE, MAP_PRIVATE, MAP_PRIVATE },
5299    { TARGET_MAP_FIXED, TARGET_MAP_FIXED, MAP_FIXED, MAP_FIXED },
5300    { TARGET_MAP_ANONYMOUS, TARGET_MAP_ANONYMOUS,
5301      MAP_ANONYMOUS, MAP_ANONYMOUS },
5302    { TARGET_MAP_GROWSDOWN, TARGET_MAP_GROWSDOWN,
5303      MAP_GROWSDOWN, MAP_GROWSDOWN },
5304    { TARGET_MAP_DENYWRITE, TARGET_MAP_DENYWRITE,
5305      MAP_DENYWRITE, MAP_DENYWRITE },
5306    { TARGET_MAP_EXECUTABLE, TARGET_MAP_EXECUTABLE,
5307      MAP_EXECUTABLE, MAP_EXECUTABLE },
5308    { TARGET_MAP_LOCKED, TARGET_MAP_LOCKED, MAP_LOCKED, MAP_LOCKED },
5309    { TARGET_MAP_NORESERVE, TARGET_MAP_NORESERVE,
5310      MAP_NORESERVE, MAP_NORESERVE },
5311    { TARGET_MAP_HUGETLB, TARGET_MAP_HUGETLB, MAP_HUGETLB, MAP_HUGETLB },
5312    /* MAP_STACK had been ignored by the kernel for quite some time.
5313       Recognize it for the target insofar as we do not want to pass
5314       it through to the host.  */
5315    { TARGET_MAP_STACK, TARGET_MAP_STACK, 0, 0 },
5316    { 0, 0, 0, 0 }
5317};
5318
5319#if defined(TARGET_I386)
5320
5321/* NOTE: there is really one LDT for all the threads */
5322static uint8_t *ldt_table;
5323
5324static abi_long read_ldt(abi_ulong ptr, unsigned long bytecount)
5325{
5326    int size;
5327    void *p;
5328
5329    if (!ldt_table)
5330        return 0;
5331    size = TARGET_LDT_ENTRIES * TARGET_LDT_ENTRY_SIZE;
5332    if (size > bytecount)
5333        size = bytecount;
5334    p = lock_user(VERIFY_WRITE, ptr, size, 0);
5335    if (!p)
5336        return -TARGET_EFAULT;
5337    /* ??? Should this by byteswapped?  */
5338    memcpy(p, ldt_table, size);
5339    unlock_user(p, ptr, size);
5340    return size;
5341}
5342
5343/* XXX: add locking support */
5344static abi_long write_ldt(CPUX86State *env,
5345                          abi_ulong ptr, unsigned long bytecount, int oldmode)
5346{
5347    struct target_modify_ldt_ldt_s ldt_info;
5348    struct target_modify_ldt_ldt_s *target_ldt_info;
5349    int seg_32bit, contents, read_exec_only, limit_in_pages;
5350    int seg_not_present, useable, lm;
5351    uint32_t *lp, entry_1, entry_2;
5352
5353    if (bytecount != sizeof(ldt_info))
5354        return -TARGET_EINVAL;
5355    if (!lock_user_struct(VERIFY_READ, target_ldt_info, ptr, 1))
5356        return -TARGET_EFAULT;
5357    ldt_info.entry_number = tswap32(target_ldt_info->entry_number);
5358    ldt_info.base_addr = tswapal(target_ldt_info->base_addr);
5359    ldt_info.limit = tswap32(target_ldt_info->limit);
5360    ldt_info.flags = tswap32(target_ldt_info->flags);
5361    unlock_user_struct(target_ldt_info, ptr, 0);