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