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