qemu/linux-user/main.c
<<
>>
Prefs
   1/*
   2 *  qemu user main
   3 *
   4 *  Copyright (c) 2003-2008 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#include "qemu/osdep.h"
  20#include <sys/mman.h>
  21#include <sys/syscall.h>
  22#include <sys/resource.h>
  23
  24#include "qemu.h"
  25#include "qemu/path.h"
  26#include "qemu/cutils.h"
  27#include "qemu/help_option.h"
  28#include "cpu.h"
  29#include "exec/exec-all.h"
  30#include "tcg.h"
  31#include "qemu/timer.h"
  32#include "qemu/envlist.h"
  33#include "elf.h"
  34#include "exec/log.h"
  35
  36char *exec_path;
  37
  38bool tcg_tb_chain = true;
  39int singlestep;
  40static const char *filename;
  41static const char *argv0;
  42static int gdbstub_port;
  43static envlist_t *envlist;
  44static const char *cpu_model;
  45unsigned long mmap_min_addr;
  46unsigned long guest_base;
  47int have_guest_base;
  48
  49#define EXCP_DUMP(env, fmt, ...)                                        \
  50do {                                                                    \
  51    CPUState *cs = ENV_GET_CPU(env);                                    \
  52    fprintf(stderr, fmt , ## __VA_ARGS__);                              \
  53    cpu_dump_state(cs, stderr, fprintf, 0);                             \
  54    if (qemu_log_separate()) {                                          \
  55        qemu_log(fmt, ## __VA_ARGS__);                                  \
  56        log_cpu_state(cs, 0);                                           \
  57    }                                                                   \
  58} while (0)
  59
  60#if (TARGET_LONG_BITS == 32) && (HOST_LONG_BITS == 64)
  61/*
  62 * When running 32-on-64 we should make sure we can fit all of the possible
  63 * guest address space into a contiguous chunk of virtual host memory.
  64 *
  65 * This way we will never overlap with our own libraries or binaries or stack
  66 * or anything else that QEMU maps.
  67 */
  68# ifdef TARGET_MIPS
  69/* MIPS only supports 31 bits of virtual address space for user space */
  70unsigned long reserved_va = 0x77000000;
  71# else
  72unsigned long reserved_va = 0xf7000000;
  73# endif
  74#else
  75unsigned long reserved_va;
  76#endif
  77
  78static void usage(int exitcode);
  79
  80static const char *interp_prefix = CONFIG_QEMU_INTERP_PREFIX;
  81const char *qemu_uname_release;
  82
  83/* XXX: on x86 MAP_GROWSDOWN only works if ESP <= address + 32, so
  84   we allocate a bigger stack. Need a better solution, for example
  85   by remapping the process stack directly at the right place */
  86unsigned long guest_stack_size = 8 * 1024 * 1024UL;
  87
  88void gemu_log(const char *fmt, ...)
  89{
  90    va_list ap;
  91
  92    va_start(ap, fmt);
  93    vfprintf(stderr, fmt, ap);
  94    va_end(ap);
  95}
  96
  97#if defined(TARGET_I386)
  98int cpu_get_pic_interrupt(CPUX86State *env)
  99{
 100    return -1;
 101}
 102#endif
 103
 104/***********************************************************/
 105/* Helper routines for implementing atomic operations.  */
 106
 107/* To implement exclusive operations we force all cpus to syncronise.
 108   We don't require a full sync, only that no cpus are executing guest code.
 109   The alternative is to map target atomic ops onto host equivalents,
 110   which requires quite a lot of per host/target work.  */
 111static pthread_mutex_t cpu_list_mutex = PTHREAD_MUTEX_INITIALIZER;
 112static pthread_mutex_t exclusive_lock = PTHREAD_MUTEX_INITIALIZER;
 113static pthread_cond_t exclusive_cond = PTHREAD_COND_INITIALIZER;
 114static pthread_cond_t exclusive_resume = PTHREAD_COND_INITIALIZER;
 115static int pending_cpus;
 116
 117/* Make sure everything is in a consistent state for calling fork().  */
 118void fork_start(void)
 119{
 120    qemu_mutex_lock(&tcg_ctx.tb_ctx.tb_lock);
 121    pthread_mutex_lock(&exclusive_lock);
 122    mmap_fork_start();
 123}
 124
 125void fork_end(int child)
 126{
 127    mmap_fork_end(child);
 128    if (child) {
 129        CPUState *cpu, *next_cpu;
 130        /* Child processes created by fork() only have a single thread.
 131           Discard information about the parent threads.  */
 132        CPU_FOREACH_SAFE(cpu, next_cpu) {
 133            if (cpu != thread_cpu) {
 134                QTAILQ_REMOVE(&cpus, thread_cpu, node);
 135            }
 136        }
 137        pending_cpus = 0;
 138        pthread_mutex_init(&exclusive_lock, NULL);
 139        pthread_mutex_init(&cpu_list_mutex, NULL);
 140        pthread_cond_init(&exclusive_cond, NULL);
 141        pthread_cond_init(&exclusive_resume, NULL);
 142        qemu_mutex_init(&tcg_ctx.tb_ctx.tb_lock);
 143        gdbserver_fork(thread_cpu);
 144    } else {
 145        pthread_mutex_unlock(&exclusive_lock);
 146        qemu_mutex_unlock(&tcg_ctx.tb_ctx.tb_lock);
 147    }
 148}
 149
 150/* Wait for pending exclusive operations to complete.  The exclusive lock
 151   must be held.  */
 152static inline void exclusive_idle(void)
 153{
 154    while (pending_cpus) {
 155        pthread_cond_wait(&exclusive_resume, &exclusive_lock);
 156    }
 157}
 158
 159/* Start an exclusive operation.
 160   Must only be called from outside cpu_arm_exec.   */
 161static inline void start_exclusive(void)
 162{
 163    CPUState *other_cpu;
 164
 165    pthread_mutex_lock(&exclusive_lock);
 166    exclusive_idle();
 167
 168    pending_cpus = 1;
 169    /* Make all other cpus stop executing.  */
 170    CPU_FOREACH(other_cpu) {
 171        if (other_cpu->running) {
 172            pending_cpus++;
 173            cpu_exit(other_cpu);
 174        }
 175    }
 176    if (pending_cpus > 1) {
 177        pthread_cond_wait(&exclusive_cond, &exclusive_lock);
 178    }
 179}
 180
 181/* Finish an exclusive operation.  */
 182static inline void __attribute__((unused)) end_exclusive(void)
 183{
 184    pending_cpus = 0;
 185    pthread_cond_broadcast(&exclusive_resume);
 186    pthread_mutex_unlock(&exclusive_lock);
 187}
 188
 189/* Wait for exclusive ops to finish, and begin cpu execution.  */
 190static inline void cpu_exec_start(CPUState *cpu)
 191{
 192    pthread_mutex_lock(&exclusive_lock);
 193    exclusive_idle();
 194    cpu->running = true;
 195    pthread_mutex_unlock(&exclusive_lock);
 196}
 197
 198/* Mark cpu as not executing, and release pending exclusive ops.  */
 199static inline void cpu_exec_end(CPUState *cpu)
 200{
 201    pthread_mutex_lock(&exclusive_lock);
 202    cpu->running = false;
 203    if (pending_cpus > 1) {
 204        pending_cpus--;
 205        if (pending_cpus == 1) {
 206            pthread_cond_signal(&exclusive_cond);
 207        }
 208    }
 209    exclusive_idle();
 210    pthread_mutex_unlock(&exclusive_lock);
 211}
 212
 213void cpu_list_lock(void)
 214{
 215    pthread_mutex_lock(&cpu_list_mutex);
 216}
 217
 218void cpu_list_unlock(void)
 219{
 220    pthread_mutex_unlock(&cpu_list_mutex);
 221}
 222
 223
 224#ifdef TARGET_I386
 225/***********************************************************/
 226/* CPUX86 core interface */
 227
 228uint64_t cpu_get_tsc(CPUX86State *env)
 229{
 230    return cpu_get_host_ticks();
 231}
 232
 233static void write_dt(void *ptr, unsigned long addr, unsigned long limit,
 234                     int flags)
 235{
 236    unsigned int e1, e2;
 237    uint32_t *p;
 238    e1 = (addr << 16) | (limit & 0xffff);
 239    e2 = ((addr >> 16) & 0xff) | (addr & 0xff000000) | (limit & 0x000f0000);
 240    e2 |= flags;
 241    p = ptr;
 242    p[0] = tswap32(e1);
 243    p[1] = tswap32(e2);
 244}
 245
 246static uint64_t *idt_table;
 247#ifdef TARGET_X86_64
 248static void set_gate64(void *ptr, unsigned int type, unsigned int dpl,
 249                       uint64_t addr, unsigned int sel)
 250{
 251    uint32_t *p, e1, e2;
 252    e1 = (addr & 0xffff) | (sel << 16);
 253    e2 = (addr & 0xffff0000) | 0x8000 | (dpl << 13) | (type << 8);
 254    p = ptr;
 255    p[0] = tswap32(e1);
 256    p[1] = tswap32(e2);
 257    p[2] = tswap32(addr >> 32);
 258    p[3] = 0;
 259}
 260/* only dpl matters as we do only user space emulation */
 261static void set_idt(int n, unsigned int dpl)
 262{
 263    set_gate64(idt_table + n * 2, 0, dpl, 0, 0);
 264}
 265#else
 266static void set_gate(void *ptr, unsigned int type, unsigned int dpl,
 267                     uint32_t addr, unsigned int sel)
 268{
 269    uint32_t *p, e1, e2;
 270    e1 = (addr & 0xffff) | (sel << 16);
 271    e2 = (addr & 0xffff0000) | 0x8000 | (dpl << 13) | (type << 8);
 272    p = ptr;
 273    p[0] = tswap32(e1);
 274    p[1] = tswap32(e2);
 275}
 276
 277/* only dpl matters as we do only user space emulation */
 278static void set_idt(int n, unsigned int dpl)
 279{
 280    set_gate(idt_table + n, 0, dpl, 0, 0);
 281}
 282#endif
 283
 284void cpu_loop(CPUX86State *env)
 285{
 286    CPUState *cs = CPU(x86_env_get_cpu(env));
 287    int trapnr;
 288    abi_ulong pc;
 289    target_siginfo_t info;
 290
 291    for(;;) {
 292        cpu_exec_start(cs);
 293        trapnr = cpu_x86_exec(cs);
 294        cpu_exec_end(cs);
 295        switch(trapnr) {
 296        case 0x80:
 297            /* linux syscall from int $0x80 */
 298            env->regs[R_EAX] = do_syscall(env,
 299                                          env->regs[R_EAX],
 300                                          env->regs[R_EBX],
 301                                          env->regs[R_ECX],
 302                                          env->regs[R_EDX],
 303                                          env->regs[R_ESI],
 304                                          env->regs[R_EDI],
 305                                          env->regs[R_EBP],
 306                                          0, 0);
 307            break;
 308#ifndef TARGET_ABI32
 309        case EXCP_SYSCALL:
 310            /* linux syscall from syscall instruction */
 311            env->regs[R_EAX] = do_syscall(env,
 312                                          env->regs[R_EAX],
 313                                          env->regs[R_EDI],
 314                                          env->regs[R_ESI],
 315                                          env->regs[R_EDX],
 316                                          env->regs[10],
 317                                          env->regs[8],
 318                                          env->regs[9],
 319                                          0, 0);
 320            break;
 321#endif
 322        case EXCP0B_NOSEG:
 323        case EXCP0C_STACK:
 324            info.si_signo = TARGET_SIGBUS;
 325            info.si_errno = 0;
 326            info.si_code = TARGET_SI_KERNEL;
 327            info._sifields._sigfault._addr = 0;
 328            queue_signal(env, info.si_signo, &info);
 329            break;
 330        case EXCP0D_GPF:
 331            /* XXX: potential problem if ABI32 */
 332#ifndef TARGET_X86_64
 333            if (env->eflags & VM_MASK) {
 334                handle_vm86_fault(env);
 335            } else
 336#endif
 337            {
 338                info.si_signo = TARGET_SIGSEGV;
 339                info.si_errno = 0;
 340                info.si_code = TARGET_SI_KERNEL;
 341                info._sifields._sigfault._addr = 0;
 342                queue_signal(env, info.si_signo, &info);
 343            }
 344            break;
 345        case EXCP0E_PAGE:
 346            info.si_signo = TARGET_SIGSEGV;
 347            info.si_errno = 0;
 348            if (!(env->error_code & 1))
 349                info.si_code = TARGET_SEGV_MAPERR;
 350            else
 351                info.si_code = TARGET_SEGV_ACCERR;
 352            info._sifields._sigfault._addr = env->cr[2];
 353            queue_signal(env, info.si_signo, &info);
 354            break;
 355        case EXCP00_DIVZ:
 356#ifndef TARGET_X86_64
 357            if (env->eflags & VM_MASK) {
 358                handle_vm86_trap(env, trapnr);
 359            } else
 360#endif
 361            {
 362                /* division by zero */
 363                info.si_signo = TARGET_SIGFPE;
 364                info.si_errno = 0;
 365                info.si_code = TARGET_FPE_INTDIV;
 366                info._sifields._sigfault._addr = env->eip;
 367                queue_signal(env, info.si_signo, &info);
 368            }
 369            break;
 370        case EXCP01_DB:
 371        case EXCP03_INT3:
 372#ifndef TARGET_X86_64
 373            if (env->eflags & VM_MASK) {
 374                handle_vm86_trap(env, trapnr);
 375            } else
 376#endif
 377            {
 378                info.si_signo = TARGET_SIGTRAP;
 379                info.si_errno = 0;
 380                if (trapnr == EXCP01_DB) {
 381                    info.si_code = TARGET_TRAP_BRKPT;
 382                    info._sifields._sigfault._addr = env->eip;
 383                } else {
 384                    info.si_code = TARGET_SI_KERNEL;
 385                    info._sifields._sigfault._addr = 0;
 386                }
 387                queue_signal(env, info.si_signo, &info);
 388            }
 389            break;
 390        case EXCP04_INTO:
 391        case EXCP05_BOUND:
 392#ifndef TARGET_X86_64
 393            if (env->eflags & VM_MASK) {
 394                handle_vm86_trap(env, trapnr);
 395            } else
 396#endif
 397            {
 398                info.si_signo = TARGET_SIGSEGV;
 399                info.si_errno = 0;
 400                info.si_code = TARGET_SI_KERNEL;
 401                info._sifields._sigfault._addr = 0;
 402                queue_signal(env, info.si_signo, &info);
 403            }
 404            break;
 405        case EXCP06_ILLOP:
 406            info.si_signo = TARGET_SIGILL;
 407            info.si_errno = 0;
 408            info.si_code = TARGET_ILL_ILLOPN;
 409            info._sifields._sigfault._addr = env->eip;
 410            queue_signal(env, info.si_signo, &info);
 411            break;
 412        case EXCP_INTERRUPT:
 413            /* just indicate that signals should be handled asap */
 414            break;
 415        case EXCP_DEBUG:
 416            {
 417                int sig;
 418
 419                sig = gdb_handlesig(cs, TARGET_SIGTRAP);
 420                if (sig)
 421                  {
 422                    info.si_signo = sig;
 423                    info.si_errno = 0;
 424                    info.si_code = TARGET_TRAP_BRKPT;
 425                    queue_signal(env, info.si_signo, &info);
 426                  }
 427            }
 428            break;
 429        default:
 430            pc = env->segs[R_CS].base + env->eip;
 431            EXCP_DUMP(env, "qemu: 0x%08lx: unhandled CPU exception 0x%x - aborting\n",
 432                      (long)pc, trapnr);
 433            abort();
 434        }
 435        process_pending_signals(env);
 436    }
 437}
 438#endif
 439
 440#ifdef TARGET_ARM
 441
 442#define get_user_code_u32(x, gaddr, env)                \
 443    ({ abi_long __r = get_user_u32((x), (gaddr));       \
 444        if (!__r && bswap_code(arm_sctlr_b(env))) {     \
 445            (x) = bswap32(x);                           \
 446        }                                               \
 447        __r;                                            \
 448    })
 449
 450#define get_user_code_u16(x, gaddr, env)                \
 451    ({ abi_long __r = get_user_u16((x), (gaddr));       \
 452        if (!__r && bswap_code(arm_sctlr_b(env))) {     \
 453            (x) = bswap16(x);                           \
 454        }                                               \
 455        __r;                                            \
 456    })
 457
 458#define get_user_data_u32(x, gaddr, env)                \
 459    ({ abi_long __r = get_user_u32((x), (gaddr));       \
 460        if (!__r && arm_cpu_bswap_data(env)) {          \
 461            (x) = bswap32(x);                           \
 462        }                                               \
 463        __r;                                            \
 464    })
 465
 466#define get_user_data_u16(x, gaddr, env)                \
 467    ({ abi_long __r = get_user_u16((x), (gaddr));       \
 468        if (!__r && arm_cpu_bswap_data(env)) {          \
 469            (x) = bswap16(x);                           \
 470        }                                               \
 471        __r;                                            \
 472    })
 473
 474#define put_user_data_u32(x, gaddr, env)                \
 475    ({ typeof(x) __x = (x);                             \
 476        if (arm_cpu_bswap_data(env)) {                  \
 477            __x = bswap32(__x);                         \
 478        }                                               \
 479        put_user_u32(__x, (gaddr));                     \
 480    })
 481
 482#define put_user_data_u16(x, gaddr, env)                \
 483    ({ typeof(x) __x = (x);                             \
 484        if (arm_cpu_bswap_data(env)) {                  \
 485            __x = bswap16(__x);                         \
 486        }                                               \
 487        put_user_u16(__x, (gaddr));                     \
 488    })
 489
 490#ifdef TARGET_ABI32
 491/* Commpage handling -- there is no commpage for AArch64 */
 492
 493/*
 494 * See the Linux kernel's Documentation/arm/kernel_user_helpers.txt
 495 * Input:
 496 * r0 = pointer to oldval
 497 * r1 = pointer to newval
 498 * r2 = pointer to target value
 499 *
 500 * Output:
 501 * r0 = 0 if *ptr was changed, non-0 if no exchange happened
 502 * C set if *ptr was changed, clear if no exchange happened
 503 *
 504 * Note segv's in kernel helpers are a bit tricky, we can set the
 505 * data address sensibly but the PC address is just the entry point.
 506 */
 507static void arm_kernel_cmpxchg64_helper(CPUARMState *env)
 508{
 509    uint64_t oldval, newval, val;
 510    uint32_t addr, cpsr;
 511    target_siginfo_t info;
 512
 513    /* Based on the 32 bit code in do_kernel_trap */
 514
 515    /* XXX: This only works between threads, not between processes.
 516       It's probably possible to implement this with native host
 517       operations. However things like ldrex/strex are much harder so
 518       there's not much point trying.  */
 519    start_exclusive();
 520    cpsr = cpsr_read(env);
 521    addr = env->regs[2];
 522
 523    if (get_user_u64(oldval, env->regs[0])) {
 524        env->exception.vaddress = env->regs[0];
 525        goto segv;
 526    };
 527
 528    if (get_user_u64(newval, env->regs[1])) {
 529        env->exception.vaddress = env->regs[1];
 530        goto segv;
 531    };
 532
 533    if (get_user_u64(val, addr)) {
 534        env->exception.vaddress = addr;
 535        goto segv;
 536    }
 537
 538    if (val == oldval) {
 539        val = newval;
 540
 541        if (put_user_u64(val, addr)) {
 542            env->exception.vaddress = addr;
 543            goto segv;
 544        };
 545
 546        env->regs[0] = 0;
 547        cpsr |= CPSR_C;
 548    } else {
 549        env->regs[0] = -1;
 550        cpsr &= ~CPSR_C;
 551    }
 552    cpsr_write(env, cpsr, CPSR_C, CPSRWriteByInstr);
 553    end_exclusive();
 554    return;
 555
 556segv:
 557    end_exclusive();
 558    /* We get the PC of the entry address - which is as good as anything,
 559       on a real kernel what you get depends on which mode it uses. */
 560    info.si_signo = TARGET_SIGSEGV;
 561    info.si_errno = 0;
 562    /* XXX: check env->error_code */
 563    info.si_code = TARGET_SEGV_MAPERR;
 564    info._sifields._sigfault._addr = env->exception.vaddress;
 565    queue_signal(env, info.si_signo, &info);
 566}
 567
 568/* Handle a jump to the kernel code page.  */
 569static int
 570do_kernel_trap(CPUARMState *env)
 571{
 572    uint32_t addr;
 573    uint32_t cpsr;
 574    uint32_t val;
 575
 576    switch (env->regs[15]) {
 577    case 0xffff0fa0: /* __kernel_memory_barrier */
 578        /* ??? No-op. Will need to do better for SMP.  */
 579        break;
 580    case 0xffff0fc0: /* __kernel_cmpxchg */
 581         /* XXX: This only works between threads, not between processes.
 582            It's probably possible to implement this with native host
 583            operations. However things like ldrex/strex are much harder so
 584            there's not much point trying.  */
 585        start_exclusive();
 586        cpsr = cpsr_read(env);
 587        addr = env->regs[2];
 588        /* FIXME: This should SEGV if the access fails.  */
 589        if (get_user_u32(val, addr))
 590            val = ~env->regs[0];
 591        if (val == env->regs[0]) {
 592            val = env->regs[1];
 593            /* FIXME: Check for segfaults.  */
 594            put_user_u32(val, addr);
 595            env->regs[0] = 0;
 596            cpsr |= CPSR_C;
 597        } else {
 598            env->regs[0] = -1;
 599            cpsr &= ~CPSR_C;
 600        }
 601        cpsr_write(env, cpsr, CPSR_C, CPSRWriteByInstr);
 602        end_exclusive();
 603        break;
 604    case 0xffff0fe0: /* __kernel_get_tls */
 605        env->regs[0] = cpu_get_tls(env);
 606        break;
 607    case 0xffff0f60: /* __kernel_cmpxchg64 */
 608        arm_kernel_cmpxchg64_helper(env);
 609        break;
 610
 611    default:
 612        return 1;
 613    }
 614    /* Jump back to the caller.  */
 615    addr = env->regs[14];
 616    if (addr & 1) {
 617        env->thumb = 1;
 618        addr &= ~1;
 619    }
 620    env->regs[15] = addr;
 621
 622    return 0;
 623}
 624
 625/* Store exclusive handling for AArch32 */
 626static int do_strex(CPUARMState *env)
 627{
 628    uint64_t val;
 629    int size;
 630    int rc = 1;
 631    int segv = 0;
 632    uint32_t addr;
 633    start_exclusive();
 634    if (env->exclusive_addr != env->exclusive_test) {
 635        goto fail;
 636    }
 637    /* We know we're always AArch32 so the address is in uint32_t range
 638     * unless it was the -1 exclusive-monitor-lost value (which won't
 639     * match exclusive_test above).
 640     */
 641    assert(extract64(env->exclusive_addr, 32, 32) == 0);
 642    addr = env->exclusive_addr;
 643    size = env->exclusive_info & 0xf;
 644    switch (size) {
 645    case 0:
 646        segv = get_user_u8(val, addr);
 647        break;
 648    case 1:
 649        segv = get_user_data_u16(val, addr, env);
 650        break;
 651    case 2:
 652    case 3:
 653        segv = get_user_data_u32(val, addr, env);
 654        break;
 655    default:
 656        abort();
 657    }
 658    if (segv) {
 659        env->exception.vaddress = addr;
 660        goto done;
 661    }
 662    if (size == 3) {
 663        uint32_t valhi;
 664        segv = get_user_data_u32(valhi, addr + 4, env);
 665        if (segv) {
 666            env->exception.vaddress = addr + 4;
 667            goto done;
 668        }
 669        if (arm_cpu_bswap_data(env)) {
 670            val = deposit64((uint64_t)valhi, 32, 32, val);
 671        } else {
 672            val = deposit64(val, 32, 32, valhi);
 673        }
 674    }
 675    if (val != env->exclusive_val) {
 676        goto fail;
 677    }
 678
 679    val = env->regs[(env->exclusive_info >> 8) & 0xf];
 680    switch (size) {
 681    case 0:
 682        segv = put_user_u8(val, addr);
 683        break;
 684    case 1:
 685        segv = put_user_data_u16(val, addr, env);
 686        break;
 687    case 2:
 688    case 3:
 689        segv = put_user_data_u32(val, addr, env);
 690        break;
 691    }
 692    if (segv) {
 693        env->exception.vaddress = addr;
 694        goto done;
 695    }
 696    if (size == 3) {
 697        val = env->regs[(env->exclusive_info >> 12) & 0xf];
 698        segv = put_user_data_u32(val, addr + 4, env);
 699        if (segv) {
 700            env->exception.vaddress = addr + 4;
 701            goto done;
 702        }
 703    }
 704    rc = 0;
 705fail:
 706    env->regs[15] += 4;
 707    env->regs[(env->exclusive_info >> 4) & 0xf] = rc;
 708done:
 709    end_exclusive();
 710    return segv;
 711}
 712
 713void cpu_loop(CPUARMState *env)
 714{
 715    CPUState *cs = CPU(arm_env_get_cpu(env));
 716    int trapnr;
 717    unsigned int n, insn;
 718    target_siginfo_t info;
 719    uint32_t addr;
 720
 721    for(;;) {
 722        cpu_exec_start(cs);
 723        trapnr = cpu_arm_exec(cs);
 724        cpu_exec_end(cs);
 725        switch(trapnr) {
 726        case EXCP_UDEF:
 727            {
 728                TaskState *ts = cs->opaque;
 729                uint32_t opcode;
 730                int rc;
 731
 732                /* we handle the FPU emulation here, as Linux */
 733                /* we get the opcode */
 734                /* FIXME - what to do if get_user() fails? */
 735                get_user_code_u32(opcode, env->regs[15], env);
 736
 737                rc = EmulateAll(opcode, &ts->fpa, env);
 738                if (rc == 0) { /* illegal instruction */
 739                    info.si_signo = TARGET_SIGILL;
 740                    info.si_errno = 0;
 741                    info.si_code = TARGET_ILL_ILLOPN;
 742                    info._sifields._sigfault._addr = env->regs[15];
 743                    queue_signal(env, info.si_signo, &info);
 744                } else if (rc < 0) { /* FP exception */
 745                    int arm_fpe=0;
 746
 747                    /* translate softfloat flags to FPSR flags */
 748                    if (-rc & float_flag_invalid)
 749                      arm_fpe |= BIT_IOC;
 750                    if (-rc & float_flag_divbyzero)
 751                      arm_fpe |= BIT_DZC;
 752                    if (-rc & float_flag_overflow)
 753                      arm_fpe |= BIT_OFC;
 754                    if (-rc & float_flag_underflow)
 755                      arm_fpe |= BIT_UFC;
 756                    if (-rc & float_flag_inexact)
 757                      arm_fpe |= BIT_IXC;
 758
 759                    FPSR fpsr = ts->fpa.fpsr;
 760                    //printf("fpsr 0x%x, arm_fpe 0x%x\n",fpsr,arm_fpe);
 761
 762                    if (fpsr & (arm_fpe << 16)) { /* exception enabled? */
 763                      info.si_signo = TARGET_SIGFPE;
 764                      info.si_errno = 0;
 765
 766                      /* ordered by priority, least first */
 767                      if (arm_fpe & BIT_IXC) info.si_code = TARGET_FPE_FLTRES;
 768                      if (arm_fpe & BIT_UFC) info.si_code = TARGET_FPE_FLTUND;
 769                      if (arm_fpe & BIT_OFC) info.si_code = TARGET_FPE_FLTOVF;
 770                      if (arm_fpe & BIT_DZC) info.si_code = TARGET_FPE_FLTDIV;
 771                      if (arm_fpe & BIT_IOC) info.si_code = TARGET_FPE_FLTINV;
 772
 773                      info._sifields._sigfault._addr = env->regs[15];
 774                      queue_signal(env, info.si_signo, &info);
 775                    } else {
 776                      env->regs[15] += 4;
 777                    }
 778
 779                    /* accumulate unenabled exceptions */
 780                    if ((!(fpsr & BIT_IXE)) && (arm_fpe & BIT_IXC))
 781                      fpsr |= BIT_IXC;
 782                    if ((!(fpsr & BIT_UFE)) && (arm_fpe & BIT_UFC))
 783                      fpsr |= BIT_UFC;
 784                    if ((!(fpsr & BIT_OFE)) && (arm_fpe & BIT_OFC))
 785                      fpsr |= BIT_OFC;
 786                    if ((!(fpsr & BIT_DZE)) && (arm_fpe & BIT_DZC))
 787                      fpsr |= BIT_DZC;
 788                    if ((!(fpsr & BIT_IOE)) && (arm_fpe & BIT_IOC))
 789                      fpsr |= BIT_IOC;
 790                    ts->fpa.fpsr=fpsr;
 791                } else { /* everything OK */
 792                    /* increment PC */
 793                    env->regs[15] += 4;
 794                }
 795            }
 796            break;
 797        case EXCP_SWI:
 798        case EXCP_BKPT:
 799            {
 800                env->eabi = 1;
 801                /* system call */
 802                if (trapnr == EXCP_BKPT) {
 803                    if (env->thumb) {
 804                        /* FIXME - what to do if get_user() fails? */
 805                        get_user_code_u16(insn, env->regs[15], env);
 806                        n = insn & 0xff;
 807                        env->regs[15] += 2;
 808                    } else {
 809                        /* FIXME - what to do if get_user() fails? */
 810                        get_user_code_u32(insn, env->regs[15], env);
 811                        n = (insn & 0xf) | ((insn >> 4) & 0xff0);
 812                        env->regs[15] += 4;
 813                    }
 814                } else {
 815                    if (env->thumb) {
 816                        /* FIXME - what to do if get_user() fails? */
 817                        get_user_code_u16(insn, env->regs[15] - 2, env);
 818                        n = insn & 0xff;
 819                    } else {
 820                        /* FIXME - what to do if get_user() fails? */
 821                        get_user_code_u32(insn, env->regs[15] - 4, env);
 822                        n = insn & 0xffffff;
 823                    }
 824                }
 825
 826                if (n == ARM_NR_cacheflush) {
 827                    /* nop */
 828                } else if (n == ARM_NR_semihosting
 829                           || n == ARM_NR_thumb_semihosting) {
 830                    env->regs[0] = do_arm_semihosting (env);
 831                } else if (n == 0 || n >= ARM_SYSCALL_BASE || env->thumb) {
 832                    /* linux syscall */
 833                    if (env->thumb || n == 0) {
 834                        n = env->regs[7];
 835                    } else {
 836                        n -= ARM_SYSCALL_BASE;
 837                        env->eabi = 0;
 838                    }
 839                    if ( n > ARM_NR_BASE) {
 840                        switch (n) {
 841                        case ARM_NR_cacheflush:
 842                            /* nop */
 843                            break;
 844                        case ARM_NR_set_tls:
 845                            cpu_set_tls(env, env->regs[0]);
 846                            env->regs[0] = 0;
 847                            break;
 848                        case ARM_NR_breakpoint:
 849                            env->regs[15] -= env->thumb ? 2 : 4;
 850                            goto excp_debug;
 851                        default:
 852                            gemu_log("qemu: Unsupported ARM syscall: 0x%x\n",
 853                                     n);
 854                            env->regs[0] = -TARGET_ENOSYS;
 855                            break;
 856                        }
 857                    } else {
 858                        env->regs[0] = do_syscall(env,
 859                                                  n,
 860                                                  env->regs[0],
 861                                                  env->regs[1],
 862                                                  env->regs[2],
 863                                                  env->regs[3],
 864                                                  env->regs[4],
 865                                                  env->regs[5],
 866                                                  0, 0);
 867                    }
 868                } else {
 869                    goto error;
 870                }
 871            }
 872            break;
 873        case EXCP_INTERRUPT:
 874            /* just indicate that signals should be handled asap */
 875            break;
 876        case EXCP_STREX:
 877            if (!do_strex(env)) {
 878                break;
 879            }
 880            /* fall through for segv */
 881        case EXCP_PREFETCH_ABORT:
 882        case EXCP_DATA_ABORT:
 883            addr = env->exception.vaddress;
 884            {
 885                info.si_signo = TARGET_SIGSEGV;
 886                info.si_errno = 0;
 887                /* XXX: check env->error_code */
 888                info.si_code = TARGET_SEGV_MAPERR;
 889                info._sifields._sigfault._addr = addr;
 890                queue_signal(env, info.si_signo, &info);
 891            }
 892            break;
 893        case EXCP_DEBUG:
 894        excp_debug:
 895            {
 896                int sig;
 897
 898                sig = gdb_handlesig(cs, TARGET_SIGTRAP);
 899                if (sig)
 900                  {
 901                    info.si_signo = sig;
 902                    info.si_errno = 0;
 903                    info.si_code = TARGET_TRAP_BRKPT;
 904                    queue_signal(env, info.si_signo, &info);
 905                  }
 906            }
 907            break;
 908        case EXCP_KERNEL_TRAP:
 909            if (do_kernel_trap(env))
 910              goto error;
 911            break;
 912        case EXCP_YIELD:
 913            /* nothing to do here for user-mode, just resume guest code */
 914            break;
 915        default:
 916        error:
 917            EXCP_DUMP(env, "qemu: unhandled CPU exception 0x%x - aborting\n", trapnr);
 918            abort();
 919        }
 920        process_pending_signals(env);
 921    }
 922}
 923
 924#else
 925
 926/*
 927 * Handle AArch64 store-release exclusive
 928 *
 929 * rs = gets the status result of store exclusive
 930 * rt = is the register that is stored
 931 * rt2 = is the second register store (in STP)
 932 *
 933 */
 934static int do_strex_a64(CPUARMState *env)
 935{
 936    uint64_t val;
 937    int size;
 938    bool is_pair;
 939    int rc = 1;
 940    int segv = 0;
 941    uint64_t addr;
 942    int rs, rt, rt2;
 943
 944    start_exclusive();
 945    /* size | is_pair << 2 | (rs << 4) | (rt << 9) | (rt2 << 14)); */
 946    size = extract32(env->exclusive_info, 0, 2);
 947    is_pair = extract32(env->exclusive_info, 2, 1);
 948    rs = extract32(env->exclusive_info, 4, 5);
 949    rt = extract32(env->exclusive_info, 9, 5);
 950    rt2 = extract32(env->exclusive_info, 14, 5);
 951
 952    addr = env->exclusive_addr;
 953
 954    if (addr != env->exclusive_test) {
 955        goto finish;
 956    }
 957
 958    switch (size) {
 959    case 0:
 960        segv = get_user_u8(val, addr);
 961        break;
 962    case 1:
 963        segv = get_user_u16(val, addr);
 964        break;
 965    case 2:
 966        segv = get_user_u32(val, addr);
 967        break;
 968    case 3:
 969        segv = get_user_u64(val, addr);
 970        break;
 971    default:
 972        abort();
 973    }
 974    if (segv) {
 975        env->exception.vaddress = addr;
 976        goto error;
 977    }
 978    if (val != env->exclusive_val) {
 979        goto finish;
 980    }
 981    if (is_pair) {
 982        if (size == 2) {
 983            segv = get_user_u32(val, addr + 4);
 984        } else {
 985            segv = get_user_u64(val, addr + 8);
 986        }
 987        if (segv) {
 988            env->exception.vaddress = addr + (size == 2 ? 4 : 8);
 989            goto error;
 990        }
 991        if (val != env->exclusive_high) {
 992            goto finish;
 993        }
 994    }
 995    /* handle the zero register */
 996    val = rt == 31 ? 0 : env->xregs[rt];
 997    switch (size) {
 998    case 0:
 999        segv = put_user_u8(val, addr);
1000        break;
1001    case 1:
1002        segv = put_user_u16(val, addr);
1003        break;
1004    case 2:
1005        segv = put_user_u32(val, addr);
1006        break;
1007    case 3:
1008        segv = put_user_u64(val, addr);
1009        break;
1010    }
1011    if (segv) {
1012        goto error;
1013    }
1014    if (is_pair) {
1015        /* handle the zero register */
1016        val = rt2 == 31 ? 0 : env->xregs[rt2];
1017        if (size == 2) {
1018            segv = put_user_u32(val, addr + 4);
1019        } else {
1020            segv = put_user_u64(val, addr + 8);
1021        }
1022        if (segv) {
1023            env->exception.vaddress = addr + (size == 2 ? 4 : 8);
1024            goto error;
1025        }
1026    }
1027    rc = 0;
1028finish:
1029    env->pc += 4;
1030    /* rs == 31 encodes a write to the ZR, thus throwing away
1031     * the status return. This is rather silly but valid.
1032     */
1033    if (rs < 31) {
1034        env->xregs[rs] = rc;
1035    }
1036error:
1037    /* instruction faulted, PC does not advance */
1038    /* either way a strex releases any exclusive lock we have */
1039    env->exclusive_addr = -1;
1040    end_exclusive();
1041    return segv;
1042}
1043
1044/* AArch64 main loop */
1045void cpu_loop(CPUARMState *env)
1046{
1047    CPUState *cs = CPU(arm_env_get_cpu(env));
1048    int trapnr, sig;
1049    target_siginfo_t info;
1050
1051    for (;;) {
1052        cpu_exec_start(cs);
1053        trapnr = cpu_arm_exec(cs);
1054        cpu_exec_end(cs);
1055
1056        switch (trapnr) {
1057        case EXCP_SWI:
1058            env->xregs[0] = do_syscall(env,
1059                                       env->xregs[8],
1060                                       env->xregs[0],
1061                                       env->xregs[1],
1062                                       env->xregs[2],
1063                                       env->xregs[3],
1064                                       env->xregs[4],
1065                                       env->xregs[5],
1066                                       0, 0);
1067            break;
1068        case EXCP_INTERRUPT:
1069            /* just indicate that signals should be handled asap */
1070            break;
1071        case EXCP_UDEF:
1072            info.si_signo = TARGET_SIGILL;
1073            info.si_errno = 0;
1074            info.si_code = TARGET_ILL_ILLOPN;
1075            info._sifields._sigfault._addr = env->pc;
1076            queue_signal(env, info.si_signo, &info);
1077            break;
1078        case EXCP_STREX:
1079            if (!do_strex_a64(env)) {
1080                break;
1081            }
1082            /* fall through for segv */
1083        case EXCP_PREFETCH_ABORT:
1084        case EXCP_DATA_ABORT:
1085            info.si_signo = TARGET_SIGSEGV;
1086            info.si_errno = 0;
1087            /* XXX: check env->error_code */
1088            info.si_code = TARGET_SEGV_MAPERR;
1089            info._sifields._sigfault._addr = env->exception.vaddress;
1090            queue_signal(env, info.si_signo, &info);
1091            break;
1092        case EXCP_DEBUG:
1093        case EXCP_BKPT:
1094            sig = gdb_handlesig(cs, TARGET_SIGTRAP);
1095            if (sig) {
1096                info.si_signo = sig;
1097                info.si_errno = 0;
1098                info.si_code = TARGET_TRAP_BRKPT;
1099                queue_signal(env, info.si_signo, &info);
1100            }
1101            break;
1102        case EXCP_SEMIHOST:
1103            env->xregs[0] = do_arm_semihosting(env);
1104            break;
1105        case EXCP_YIELD:
1106            /* nothing to do here for user-mode, just resume guest code */
1107            break;
1108        default:
1109            EXCP_DUMP(env, "qemu: unhandled CPU exception 0x%x - aborting\n", trapnr);
1110            abort();
1111        }
1112        process_pending_signals(env);
1113        /* Exception return on AArch64 always clears the exclusive monitor,
1114         * so any return to running guest code implies this.
1115         * A strex (successful or otherwise) also clears the monitor, so
1116         * we don't need to specialcase EXCP_STREX.
1117         */
1118        env->exclusive_addr = -1;
1119    }
1120}
1121#endif /* ndef TARGET_ABI32 */
1122
1123#endif
1124
1125#ifdef TARGET_UNICORE32
1126
1127void cpu_loop(CPUUniCore32State *env)
1128{
1129    CPUState *cs = CPU(uc32_env_get_cpu(env));
1130    int trapnr;
1131    unsigned int n, insn;
1132    target_siginfo_t info;
1133
1134    for (;;) {
1135        cpu_exec_start(cs);
1136        trapnr = uc32_cpu_exec(cs);
1137        cpu_exec_end(cs);
1138        switch (trapnr) {
1139        case UC32_EXCP_PRIV:
1140            {
1141                /* system call */
1142                get_user_u32(insn, env->regs[31] - 4);
1143                n = insn & 0xffffff;
1144
1145                if (n >= UC32_SYSCALL_BASE) {
1146                    /* linux syscall */
1147                    n -= UC32_SYSCALL_BASE;
1148                    if (n == UC32_SYSCALL_NR_set_tls) {
1149                            cpu_set_tls(env, env->regs[0]);
1150                            env->regs[0] = 0;
1151                    } else {
1152                        env->regs[0] = do_syscall(env,
1153                                                  n,
1154                                                  env->regs[0],
1155                                                  env->regs[1],
1156                                                  env->regs[2],
1157                                                  env->regs[3],
1158                                                  env->regs[4],
1159                                                  env->regs[5],
1160                                                  0, 0);
1161                    }
1162                } else {
1163                    goto error;
1164                }
1165            }
1166            break;
1167        case UC32_EXCP_DTRAP:
1168        case UC32_EXCP_ITRAP:
1169            info.si_signo = TARGET_SIGSEGV;
1170            info.si_errno = 0;
1171            /* XXX: check env->error_code */
1172            info.si_code = TARGET_SEGV_MAPERR;
1173            info._sifields._sigfault._addr = env->cp0.c4_faultaddr;
1174            queue_signal(env, info.si_signo, &info);
1175            break;
1176        case EXCP_INTERRUPT:
1177            /* just indicate that signals should be handled asap */
1178            break;
1179        case EXCP_DEBUG:
1180            {
1181                int sig;
1182
1183                sig = gdb_handlesig(cs, TARGET_SIGTRAP);
1184                if (sig) {
1185                    info.si_signo = sig;
1186                    info.si_errno = 0;
1187                    info.si_code = TARGET_TRAP_BRKPT;
1188                    queue_signal(env, info.si_signo, &info);
1189                }
1190            }
1191            break;
1192        default:
1193            goto error;
1194        }
1195        process_pending_signals(env);
1196    }
1197
1198error:
1199    EXCP_DUMP(env, "qemu: unhandled CPU exception 0x%x - aborting\n", trapnr);
1200    abort();
1201}
1202#endif
1203
1204#ifdef TARGET_SPARC
1205#define SPARC64_STACK_BIAS 2047
1206
1207//#define DEBUG_WIN
1208
1209/* WARNING: dealing with register windows _is_ complicated. More info
1210   can be found at http://www.sics.se/~psm/sparcstack.html */
1211static inline int get_reg_index(CPUSPARCState *env, int cwp, int index)
1212{
1213    index = (index + cwp * 16) % (16 * env->nwindows);
1214    /* wrap handling : if cwp is on the last window, then we use the
1215       registers 'after' the end */
1216    if (index < 8 && env->cwp == env->nwindows - 1)
1217        index += 16 * env->nwindows;
1218    return index;
1219}
1220
1221/* save the register window 'cwp1' */
1222static inline void save_window_offset(CPUSPARCState *env, int cwp1)
1223{
1224    unsigned int i;
1225    abi_ulong sp_ptr;
1226
1227    sp_ptr = env->regbase[get_reg_index(env, cwp1, 6)];
1228#ifdef TARGET_SPARC64
1229    if (sp_ptr & 3)
1230        sp_ptr += SPARC64_STACK_BIAS;
1231#endif
1232#if defined(DEBUG_WIN)
1233    printf("win_overflow: sp_ptr=0x" TARGET_ABI_FMT_lx " save_cwp=%d\n",
1234           sp_ptr, cwp1);
1235#endif
1236    for(i = 0; i < 16; i++) {
1237        /* FIXME - what to do if put_user() fails? */
1238        put_user_ual(env->regbase[get_reg_index(env, cwp1, 8 + i)], sp_ptr);
1239        sp_ptr += sizeof(abi_ulong);
1240    }
1241}
1242
1243static void save_window(CPUSPARCState *env)
1244{
1245#ifndef TARGET_SPARC64
1246    unsigned int new_wim;
1247    new_wim = ((env->wim >> 1) | (env->wim << (env->nwindows - 1))) &
1248        ((1LL << env->nwindows) - 1);
1249    save_window_offset(env, cpu_cwp_dec(env, env->cwp - 2));
1250    env->wim = new_wim;
1251#else
1252    save_window_offset(env, cpu_cwp_dec(env, env->cwp - 2));
1253    env->cansave++;
1254    env->canrestore--;
1255#endif
1256}
1257
1258static void restore_window(CPUSPARCState *env)
1259{
1260#ifndef TARGET_SPARC64
1261    unsigned int new_wim;
1262#endif
1263    unsigned int i, cwp1;
1264    abi_ulong sp_ptr;
1265
1266#ifndef TARGET_SPARC64
1267    new_wim = ((env->wim << 1) | (env->wim >> (env->nwindows - 1))) &
1268        ((1LL << env->nwindows) - 1);
1269#endif
1270
1271    /* restore the invalid window */
1272    cwp1 = cpu_cwp_inc(env, env->cwp + 1);
1273    sp_ptr = env->regbase[get_reg_index(env, cwp1, 6)];
1274#ifdef TARGET_SPARC64
1275    if (sp_ptr & 3)
1276        sp_ptr += SPARC64_STACK_BIAS;
1277#endif
1278#if defined(DEBUG_WIN)
1279    printf("win_underflow: sp_ptr=0x" TARGET_ABI_FMT_lx " load_cwp=%d\n",
1280           sp_ptr, cwp1);
1281#endif
1282    for(i = 0; i < 16; i++) {
1283        /* FIXME - what to do if get_user() fails? */
1284        get_user_ual(env->regbase[get_reg_index(env, cwp1, 8 + i)], sp_ptr);
1285        sp_ptr += sizeof(abi_ulong);
1286    }
1287#ifdef TARGET_SPARC64
1288    env->canrestore++;
1289    if (env->cleanwin < env->nwindows - 1)
1290        env->cleanwin++;
1291    env->cansave--;
1292#else
1293    env->wim = new_wim;
1294#endif
1295}
1296
1297static void flush_windows(CPUSPARCState *env)
1298{
1299    int offset, cwp1;
1300
1301    offset = 1;
1302    for(;;) {
1303        /* if restore would invoke restore_window(), then we can stop */
1304        cwp1 = cpu_cwp_inc(env, env->cwp + offset);
1305#ifndef TARGET_SPARC64
1306        if (env->wim & (1 << cwp1))
1307            break;
1308#else
1309        if (env->canrestore == 0)
1310            break;
1311        env->cansave++;
1312        env->canrestore--;
1313#endif
1314        save_window_offset(env, cwp1);
1315        offset++;
1316    }
1317    cwp1 = cpu_cwp_inc(env, env->cwp + 1);
1318#ifndef TARGET_SPARC64
1319    /* set wim so that restore will reload the registers */
1320    env->wim = 1 << cwp1;
1321#endif
1322#if defined(DEBUG_WIN)
1323    printf("flush_windows: nb=%d\n", offset - 1);
1324#endif
1325}
1326
1327void cpu_loop (CPUSPARCState *env)
1328{
1329    CPUState *cs = CPU(sparc_env_get_cpu(env));
1330    int trapnr;
1331    abi_long ret;
1332    target_siginfo_t info;
1333
1334    while (1) {
1335        cpu_exec_start(cs);
1336        trapnr = cpu_sparc_exec(cs);
1337        cpu_exec_end(cs);
1338
1339        /* Compute PSR before exposing state.  */
1340        if (env->cc_op != CC_OP_FLAGS) {
1341            cpu_get_psr(env);
1342        }
1343
1344        switch (trapnr) {
1345#ifndef TARGET_SPARC64
1346        case 0x88:
1347        case 0x90:
1348#else
1349        case 0x110:
1350        case 0x16d:
1351#endif
1352            ret = do_syscall (env, env->gregs[1],
1353                              env->regwptr[0], env->regwptr[1],
1354                              env->regwptr[2], env->regwptr[3],
1355                              env->regwptr[4], env->regwptr[5],
1356                              0, 0);
1357            if ((abi_ulong)ret >= (abi_ulong)(-515)) {
1358#if defined(TARGET_SPARC64) && !defined(TARGET_ABI32)
1359                env->xcc |= PSR_CARRY;
1360#else
1361                env->psr |= PSR_CARRY;
1362#endif
1363                ret = -ret;
1364            } else {
1365#if defined(TARGET_SPARC64) && !defined(TARGET_ABI32)
1366                env->xcc &= ~PSR_CARRY;
1367#else
1368                env->psr &= ~PSR_CARRY;
1369#endif
1370            }
1371            env->regwptr[0] = ret;
1372            /* next instruction */
1373            env->pc = env->npc;
1374            env->npc = env->npc + 4;
1375            break;
1376        case 0x83: /* flush windows */
1377#ifdef TARGET_ABI32
1378        case 0x103:
1379#endif
1380            flush_windows(env);
1381            /* next instruction */
1382            env->pc = env->npc;
1383            env->npc = env->npc + 4;
1384            break;
1385#ifndef TARGET_SPARC64
1386        case TT_WIN_OVF: /* window overflow */
1387            save_window(env);
1388            break;
1389        case TT_WIN_UNF: /* window underflow */
1390            restore_window(env);
1391            break;
1392        case TT_TFAULT:
1393        case TT_DFAULT:
1394            {
1395                info.si_signo = TARGET_SIGSEGV;
1396                info.si_errno = 0;
1397                /* XXX: check env->error_code */
1398                info.si_code = TARGET_SEGV_MAPERR;
1399                info._sifields._sigfault._addr = env->mmuregs[4];
1400                queue_signal(env, info.si_signo, &info);
1401            }
1402            break;
1403#else
1404        case TT_SPILL: /* window overflow */
1405            save_window(env);
1406            break;
1407        case TT_FILL: /* window underflow */
1408            restore_window(env);
1409            break;
1410        case TT_TFAULT:
1411        case TT_DFAULT:
1412            {
1413                info.si_signo = TARGET_SIGSEGV;
1414                info.si_errno = 0;
1415                /* XXX: check env->error_code */
1416                info.si_code = TARGET_SEGV_MAPERR;
1417                if (trapnr == TT_DFAULT)
1418                    info._sifields._sigfault._addr = env->dmmuregs[4];
1419                else
1420                    info._sifields._sigfault._addr = cpu_tsptr(env)->tpc;
1421                queue_signal(env, info.si_signo, &info);
1422            }
1423            break;
1424#ifndef TARGET_ABI32
1425        case 0x16e:
1426            flush_windows(env);
1427            sparc64_get_context(env);
1428            break;
1429        case 0x16f:
1430            flush_windows(env);
1431            sparc64_set_context(env);
1432            break;
1433#endif
1434#endif
1435        case EXCP_INTERRUPT:
1436            /* just indicate that signals should be handled asap */
1437            break;
1438        case TT_ILL_INSN:
1439            {
1440                info.si_signo = TARGET_SIGILL;
1441                info.si_errno = 0;
1442                info.si_code = TARGET_ILL_ILLOPC;
1443                info._sifields._sigfault._addr = env->pc;
1444                queue_signal(env, info.si_signo, &info);
1445            }
1446            break;
1447        case EXCP_DEBUG:
1448            {
1449                int sig;
1450
1451                sig = gdb_handlesig(cs, TARGET_SIGTRAP);
1452                if (sig)
1453                  {
1454                    info.si_signo = sig;
1455                    info.si_errno = 0;
1456                    info.si_code = TARGET_TRAP_BRKPT;
1457                    queue_signal(env, info.si_signo, &info);
1458                  }
1459            }
1460            break;
1461        default:
1462            printf ("Unhandled trap: 0x%x\n", trapnr);
1463            cpu_dump_state(cs, stderr, fprintf, 0);
1464            exit(EXIT_FAILURE);
1465        }
1466        process_pending_signals (env);
1467    }
1468}
1469
1470#endif
1471
1472#ifdef TARGET_PPC
1473static inline uint64_t cpu_ppc_get_tb(CPUPPCState *env)
1474{
1475    return cpu_get_host_ticks();
1476}
1477
1478uint64_t cpu_ppc_load_tbl(CPUPPCState *env)
1479{
1480    return cpu_ppc_get_tb(env);
1481}
1482
1483uint32_t cpu_ppc_load_tbu(CPUPPCState *env)
1484{
1485    return cpu_ppc_get_tb(env) >> 32;
1486}
1487
1488uint64_t cpu_ppc_load_atbl(CPUPPCState *env)
1489{
1490    return cpu_ppc_get_tb(env);
1491}
1492
1493uint32_t cpu_ppc_load_atbu(CPUPPCState *env)
1494{
1495    return cpu_ppc_get_tb(env) >> 32;
1496}
1497
1498uint32_t cpu_ppc601_load_rtcu(CPUPPCState *env)
1499__attribute__ (( alias ("cpu_ppc_load_tbu") ));
1500
1501uint32_t cpu_ppc601_load_rtcl(CPUPPCState *env)
1502{
1503    return cpu_ppc_load_tbl(env) & 0x3FFFFF80;
1504}
1505
1506/* XXX: to be fixed */
1507int ppc_dcr_read (ppc_dcr_t *dcr_env, int dcrn, uint32_t *valp)
1508{
1509    return -1;
1510}
1511
1512int ppc_dcr_write (ppc_dcr_t *dcr_env, int dcrn, uint32_t val)
1513{
1514    return -1;
1515}
1516
1517static int do_store_exclusive(CPUPPCState *env)
1518{
1519    target_ulong addr;
1520    target_ulong page_addr;
1521    target_ulong val, val2 __attribute__((unused)) = 0;
1522    int flags;
1523    int segv = 0;
1524
1525    addr = env->reserve_ea;
1526    page_addr = addr & TARGET_PAGE_MASK;
1527    start_exclusive();
1528    mmap_lock();
1529    flags = page_get_flags(page_addr);
1530    if ((flags & PAGE_READ) == 0) {
1531        segv = 1;
1532    } else {
1533        int reg = env->reserve_info & 0x1f;
1534        int size = env->reserve_info >> 5;
1535        int stored = 0;
1536
1537        if (addr == env->reserve_addr) {
1538            switch (size) {
1539            case 1: segv = get_user_u8(val, addr); break;
1540            case 2: segv = get_user_u16(val, addr); break;
1541            case 4: segv = get_user_u32(val, addr); break;
1542#if defined(TARGET_PPC64)
1543            case 8: segv = get_user_u64(val, addr); break;
1544            case 16: {
1545                segv = get_user_u64(val, addr);
1546                if (!segv) {
1547                    segv = get_user_u64(val2, addr + 8);
1548                }
1549                break;
1550            }
1551#endif
1552            default: abort();
1553            }
1554            if (!segv && val == env->reserve_val) {
1555                val = env->gpr[reg];
1556                switch (size) {
1557                case 1: segv = put_user_u8(val, addr); break;
1558                case 2: segv = put_user_u16(val, addr); break;
1559                case 4: segv = put_user_u32(val, addr); break;
1560#if defined(TARGET_PPC64)
1561                case 8: segv = put_user_u64(val, addr); break;
1562                case 16: {
1563                    if (val2 == env->reserve_val2) {
1564                        if (msr_le) {
1565                            val2 = val;
1566                            val = env->gpr[reg+1];
1567                        } else {
1568                            val2 = env->gpr[reg+1];
1569                        }
1570                        segv = put_user_u64(val, addr);
1571                        if (!segv) {
1572                            segv = put_user_u64(val2, addr + 8);
1573                        }
1574                    }
1575                    break;
1576                }
1577#endif
1578                default: abort();
1579                }
1580                if (!segv) {
1581                    stored = 1;
1582                }
1583            }
1584        }
1585        env->crf[0] = (stored << 1) | xer_so;
1586        env->reserve_addr = (target_ulong)-1;
1587    }
1588    if (!segv) {
1589        env->nip += 4;
1590    }
1591    mmap_unlock();
1592    end_exclusive();
1593    return segv;
1594}
1595
1596void cpu_loop(CPUPPCState *env)
1597{
1598    CPUState *cs = CPU(ppc_env_get_cpu(env));
1599    target_siginfo_t info;
1600    int trapnr;
1601    target_ulong ret;
1602
1603    for(;;) {
1604        cpu_exec_start(cs);
1605        trapnr = cpu_ppc_exec(cs);
1606        cpu_exec_end(cs);
1607        switch(trapnr) {
1608        case POWERPC_EXCP_NONE:
1609            /* Just go on */
1610            break;
1611        case POWERPC_EXCP_CRITICAL: /* Critical input                        */
1612            cpu_abort(cs, "Critical interrupt while in user mode. "
1613                      "Aborting\n");
1614            break;
1615        case POWERPC_EXCP_MCHECK:   /* Machine check exception               */
1616            cpu_abort(cs, "Machine check exception while in user mode. "
1617                      "Aborting\n");
1618            break;
1619        case POWERPC_EXCP_DSI:      /* Data storage exception                */
1620            EXCP_DUMP(env, "Invalid data memory access: 0x" TARGET_FMT_lx "\n",
1621                      env->spr[SPR_DAR]);
1622            /* XXX: check this. Seems bugged */
1623            switch (env->error_code & 0xFF000000) {
1624            case 0x40000000:
1625                info.si_signo = TARGET_SIGSEGV;
1626                info.si_errno = 0;
1627                info.si_code = TARGET_SEGV_MAPERR;
1628                break;
1629            case 0x04000000:
1630                info.si_signo = TARGET_SIGILL;
1631                info.si_errno = 0;
1632                info.si_code = TARGET_ILL_ILLADR;
1633                break;
1634            case 0x08000000:
1635                info.si_signo = TARGET_SIGSEGV;
1636                info.si_errno = 0;
1637                info.si_code = TARGET_SEGV_ACCERR;
1638                break;
1639            default:
1640                /* Let's send a regular segfault... */
1641                EXCP_DUMP(env, "Invalid segfault errno (%02x)\n",
1642                          env->error_code);
1643                info.si_signo = TARGET_SIGSEGV;
1644                info.si_errno = 0;
1645                info.si_code = TARGET_SEGV_MAPERR;
1646                break;
1647            }
1648            info._sifields._sigfault._addr = env->nip;
1649            queue_signal(env, info.si_signo, &info);
1650            break;
1651        case POWERPC_EXCP_ISI:      /* Instruction storage exception         */
1652            EXCP_DUMP(env, "Invalid instruction fetch: 0x\n" TARGET_FMT_lx
1653                      "\n", env->spr[SPR_SRR0]);
1654            /* XXX: check this */
1655            switch (env->error_code & 0xFF000000) {
1656            case 0x40000000:
1657                info.si_signo = TARGET_SIGSEGV;
1658            info.si_errno = 0;
1659                info.si_code = TARGET_SEGV_MAPERR;
1660                break;
1661            case 0x10000000:
1662            case 0x08000000:
1663                info.si_signo = TARGET_SIGSEGV;
1664                info.si_errno = 0;
1665                info.si_code = TARGET_SEGV_ACCERR;
1666                break;
1667            default:
1668                /* Let's send a regular segfault... */
1669                EXCP_DUMP(env, "Invalid segfault errno (%02x)\n",
1670                          env->error_code);
1671                info.si_signo = TARGET_SIGSEGV;
1672                info.si_errno = 0;
1673                info.si_code = TARGET_SEGV_MAPERR;
1674                break;
1675            }
1676            info._sifields._sigfault._addr = env->nip - 4;
1677            queue_signal(env, info.si_signo, &info);
1678            break;
1679        case POWERPC_EXCP_EXTERNAL: /* External input                        */
1680            cpu_abort(cs, "External interrupt while in user mode. "
1681                      "Aborting\n");
1682            break;
1683        case POWERPC_EXCP_ALIGN:    /* Alignment exception                   */
1684            EXCP_DUMP(env, "Unaligned memory access\n");
1685            /* XXX: check this */
1686            info.si_signo = TARGET_SIGBUS;
1687            info.si_errno = 0;
1688            info.si_code = TARGET_BUS_ADRALN;
1689            info._sifields._sigfault._addr = env->nip;
1690            queue_signal(env, info.si_signo, &info);
1691            break;
1692        case POWERPC_EXCP_PROGRAM:  /* Program exception                     */
1693            /* XXX: check this */
1694            switch (env->error_code & ~0xF) {
1695            case POWERPC_EXCP_FP:
1696                EXCP_DUMP(env, "Floating point program exception\n");
1697                info.si_signo = TARGET_SIGFPE;
1698                info.si_errno = 0;
1699                switch (env->error_code & 0xF) {
1700                case POWERPC_EXCP_FP_OX:
1701                    info.si_code = TARGET_FPE_FLTOVF;
1702                    break;
1703                case POWERPC_EXCP_FP_UX:
1704                    info.si_code = TARGET_FPE_FLTUND;
1705                    break;
1706                case POWERPC_EXCP_FP_ZX:
1707                case POWERPC_EXCP_FP_VXZDZ:
1708                    info.si_code = TARGET_FPE_FLTDIV;
1709                    break;
1710                case POWERPC_EXCP_FP_XX:
1711                    info.si_code = TARGET_FPE_FLTRES;
1712                    break;
1713                case POWERPC_EXCP_FP_VXSOFT:
1714                    info.si_code = TARGET_FPE_FLTINV;
1715                    break;
1716                case POWERPC_EXCP_FP_VXSNAN:
1717                case POWERPC_EXCP_FP_VXISI:
1718                case POWERPC_EXCP_FP_VXIDI:
1719                case POWERPC_EXCP_FP_VXIMZ:
1720                case POWERPC_EXCP_FP_VXVC:
1721                case POWERPC_EXCP_FP_VXSQRT:
1722                case POWERPC_EXCP_FP_VXCVI:
1723                    info.si_code = TARGET_FPE_FLTSUB;
1724                    break;
1725                default:
1726                    EXCP_DUMP(env, "Unknown floating point exception (%02x)\n",
1727                              env->error_code);
1728                    break;
1729                }
1730                break;
1731            case POWERPC_EXCP_INVAL:
1732                EXCP_DUMP(env, "Invalid instruction\n");
1733                info.si_signo = TARGET_SIGILL;
1734                info.si_errno = 0;
1735                switch (env->error_code & 0xF) {
1736                case POWERPC_EXCP_INVAL_INVAL:
1737                    info.si_code = TARGET_ILL_ILLOPC;
1738                    break;
1739                case POWERPC_EXCP_INVAL_LSWX:
1740                    info.si_code = TARGET_ILL_ILLOPN;
1741                    break;
1742                case POWERPC_EXCP_INVAL_SPR:
1743                    info.si_code = TARGET_ILL_PRVREG;
1744                    break;
1745                case POWERPC_EXCP_INVAL_FP:
1746                    info.si_code = TARGET_ILL_COPROC;
1747                    break;
1748                default:
1749                    EXCP_DUMP(env, "Unknown invalid operation (%02x)\n",
1750                              env->error_code & 0xF);
1751                    info.si_code = TARGET_ILL_ILLADR;
1752                    break;
1753                }
1754                break;
1755            case POWERPC_EXCP_PRIV:
1756                EXCP_DUMP(env, "Privilege violation\n");
1757                info.si_signo = TARGET_SIGILL;
1758                info.si_errno = 0;
1759                switch (env->error_code & 0xF) {
1760                case POWERPC_EXCP_PRIV_OPC:
1761                    info.si_code = TARGET_ILL_PRVOPC;
1762                    break;
1763                case POWERPC_EXCP_PRIV_REG:
1764                    info.si_code = TARGET_ILL_PRVREG;
1765                    break;
1766                default:
1767                    EXCP_DUMP(env, "Unknown privilege violation (%02x)\n",
1768                              env->error_code & 0xF);
1769                    info.si_code = TARGET_ILL_PRVOPC;
1770                    break;
1771                }
1772                break;
1773            case POWERPC_EXCP_TRAP:
1774                cpu_abort(cs, "Tried to call a TRAP\n");
1775                break;
1776            default:
1777                /* Should not happen ! */
1778                cpu_abort(cs, "Unknown program exception (%02x)\n",
1779                          env->error_code);
1780                break;
1781            }
1782            info._sifields._sigfault._addr = env->nip - 4;
1783            queue_signal(env, info.si_signo, &info);
1784            break;
1785        case POWERPC_EXCP_FPU:      /* Floating-point unavailable exception  */
1786            EXCP_DUMP(env, "No floating point allowed\n");
1787            info.si_signo = TARGET_SIGILL;
1788            info.si_errno = 0;
1789            info.si_code = TARGET_ILL_COPROC;
1790            info._sifields._sigfault._addr = env->nip - 4;
1791            queue_signal(env, info.si_signo, &info);
1792            break;
1793        case POWERPC_EXCP_SYSCALL:  /* System call exception                 */
1794            cpu_abort(cs, "Syscall exception while in user mode. "
1795                      "Aborting\n");
1796            break;
1797        case POWERPC_EXCP_APU:      /* Auxiliary processor unavailable       */
1798            EXCP_DUMP(env, "No APU instruction allowed\n");
1799            info.si_signo = TARGET_SIGILL;
1800            info.si_errno = 0;
1801            info.si_code = TARGET_ILL_COPROC;
1802            info._sifields._sigfault._addr = env->nip - 4;
1803            queue_signal(env, info.si_signo, &info);
1804            break;
1805        case POWERPC_EXCP_DECR:     /* Decrementer exception                 */
1806            cpu_abort(cs, "Decrementer interrupt while in user mode. "
1807                      "Aborting\n");
1808            break;
1809        case POWERPC_EXCP_FIT:      /* Fixed-interval timer interrupt        */
1810            cpu_abort(cs, "Fix interval timer interrupt while in user mode. "
1811                      "Aborting\n");
1812            break;
1813        case POWERPC_EXCP_WDT:      /* Watchdog timer interrupt              */
1814            cpu_abort(cs, "Watchdog timer interrupt while in user mode. "
1815                      "Aborting\n");
1816            break;
1817        case POWERPC_EXCP_DTLB:     /* Data TLB error                        */
1818            cpu_abort(cs, "Data TLB exception while in user mode. "
1819                      "Aborting\n");
1820            break;
1821        case POWERPC_EXCP_ITLB:     /* Instruction TLB error                 */
1822            cpu_abort(cs, "Instruction TLB exception while in user mode. "
1823                      "Aborting\n");
1824            break;
1825        case POWERPC_EXCP_SPEU:     /* SPE/embedded floating-point unavail.  */
1826            EXCP_DUMP(env, "No SPE/floating-point instruction allowed\n");
1827            info.si_signo = TARGET_SIGILL;
1828            info.si_errno = 0;
1829            info.si_code = TARGET_ILL_COPROC;
1830            info._sifields._sigfault._addr = env->nip - 4;
1831            queue_signal(env, info.si_signo, &info);
1832            break;
1833        case POWERPC_EXCP_EFPDI:    /* Embedded floating-point data IRQ      */
1834            cpu_abort(cs, "Embedded floating-point data IRQ not handled\n");
1835            break;
1836        case POWERPC_EXCP_EFPRI:    /* Embedded floating-point round IRQ     */
1837            cpu_abort(cs, "Embedded floating-point round IRQ not handled\n");
1838            break;
1839        case POWERPC_EXCP_EPERFM:   /* Embedded performance monitor IRQ      */
1840            cpu_abort(cs, "Performance monitor exception not handled\n");
1841            break;
1842        case POWERPC_EXCP_DOORI:    /* Embedded doorbell interrupt           */
1843            cpu_abort(cs, "Doorbell interrupt while in user mode. "
1844                       "Aborting\n");
1845            break;
1846        case POWERPC_EXCP_DOORCI:   /* Embedded doorbell critical interrupt  */
1847            cpu_abort(cs, "Doorbell critical interrupt while in user mode. "
1848                      "Aborting\n");
1849            break;
1850        case POWERPC_EXCP_RESET:    /* System reset exception                */
1851            cpu_abort(cs, "Reset interrupt while in user mode. "
1852                      "Aborting\n");
1853            break;
1854        case POWERPC_EXCP_DSEG:     /* Data segment exception                */
1855            cpu_abort(cs, "Data segment exception while in user mode. "
1856                      "Aborting\n");
1857            break;
1858        case POWERPC_EXCP_ISEG:     /* Instruction segment exception         */
1859            cpu_abort(cs, "Instruction segment exception "
1860                      "while in user mode. Aborting\n");
1861            break;
1862        /* PowerPC 64 with hypervisor mode support */
1863        case POWERPC_EXCP_HDECR:    /* Hypervisor decrementer exception      */
1864            cpu_abort(cs, "Hypervisor decrementer interrupt "
1865                      "while in user mode. Aborting\n");
1866            break;
1867        case POWERPC_EXCP_TRACE:    /* Trace exception                       */
1868            /* Nothing to do:
1869             * we use this exception to emulate step-by-step execution mode.
1870             */
1871            break;
1872        /* PowerPC 64 with hypervisor mode support */
1873        case POWERPC_EXCP_HDSI:     /* Hypervisor data storage exception     */
1874            cpu_abort(cs, "Hypervisor data storage exception "
1875                      "while in user mode. Aborting\n");
1876            break;
1877        case POWERPC_EXCP_HISI:     /* Hypervisor instruction storage excp   */
1878            cpu_abort(cs, "Hypervisor instruction storage exception "
1879                      "while in user mode. Aborting\n");
1880            break;
1881        case POWERPC_EXCP_HDSEG:    /* Hypervisor data segment exception     */
1882            cpu_abort(cs, "Hypervisor data segment exception "
1883                      "while in user mode. Aborting\n");
1884            break;
1885        case POWERPC_EXCP_HISEG:    /* Hypervisor instruction segment excp   */
1886            cpu_abort(cs, "Hypervisor instruction segment exception "
1887                      "while in user mode. Aborting\n");
1888            break;
1889        case POWERPC_EXCP_VPU:      /* Vector unavailable exception          */
1890            EXCP_DUMP(env, "No Altivec instructions allowed\n");
1891            info.si_signo = TARGET_SIGILL;
1892            info.si_errno = 0;
1893            info.si_code = TARGET_ILL_COPROC;
1894            info._sifields._sigfault._addr = env->nip - 4;
1895            queue_signal(env, info.si_signo, &info);
1896            break;
1897        case POWERPC_EXCP_PIT:      /* Programmable interval timer IRQ       */
1898            cpu_abort(cs, "Programmable interval timer interrupt "
1899                      "while in user mode. Aborting\n");
1900            break;
1901        case POWERPC_EXCP_IO:       /* IO error exception                    */
1902            cpu_abort(cs, "IO error exception while in user mode. "
1903                      "Aborting\n");
1904            break;
1905        case POWERPC_EXCP_RUNM:     /* Run mode exception                    */
1906            cpu_abort(cs, "Run mode exception while in user mode. "
1907                      "Aborting\n");
1908            break;
1909        case POWERPC_EXCP_EMUL:     /* Emulation trap exception              */
1910            cpu_abort(cs, "Emulation trap exception not handled\n");
1911            break;
1912        case POWERPC_EXCP_IFTLB:    /* Instruction fetch TLB error           */
1913            cpu_abort(cs, "Instruction fetch TLB exception "
1914                      "while in user-mode. Aborting");
1915            break;
1916        case POWERPC_EXCP_DLTLB:    /* Data load TLB miss                    */
1917            cpu_abort(cs, "Data load TLB exception while in user-mode. "
1918                      "Aborting");
1919            break;
1920        case POWERPC_EXCP_DSTLB:    /* Data store TLB miss                   */
1921            cpu_abort(cs, "Data store TLB exception while in user-mode. "
1922                      "Aborting");
1923            break;
1924        case POWERPC_EXCP_FPA:      /* Floating-point assist exception       */
1925            cpu_abort(cs, "Floating-point assist exception not handled\n");
1926            break;
1927        case POWERPC_EXCP_IABR:     /* Instruction address breakpoint        */
1928            cpu_abort(cs, "Instruction address breakpoint exception "
1929                      "not handled\n");
1930            break;
1931        case POWERPC_EXCP_SMI:      /* System management interrupt           */
1932            cpu_abort(cs, "System management interrupt while in user mode. "
1933                      "Aborting\n");
1934            break;
1935        case POWERPC_EXCP_THERM:    /* Thermal interrupt                     */
1936            cpu_abort(cs, "Thermal interrupt interrupt while in user mode. "
1937                      "Aborting\n");
1938            break;
1939        case POWERPC_EXCP_PERFM:   /* Embedded performance monitor IRQ      */
1940            cpu_abort(cs, "Performance monitor exception not handled\n");
1941            break;
1942        case POWERPC_EXCP_VPUA:     /* Vector assist exception               */
1943            cpu_abort(cs, "Vector assist exception not handled\n");
1944            break;
1945        case POWERPC_EXCP_SOFTP:    /* Soft patch exception                  */
1946            cpu_abort(cs, "Soft patch exception not handled\n");
1947            break;
1948        case POWERPC_EXCP_MAINT:    /* Maintenance exception                 */
1949            cpu_abort(cs, "Maintenance exception while in user mode. "
1950                      "Aborting\n");
1951            break;
1952        case POWERPC_EXCP_STOP:     /* stop translation                      */
1953            /* We did invalidate the instruction cache. Go on */
1954            break;
1955        case POWERPC_EXCP_BRANCH:   /* branch instruction:                   */
1956            /* We just stopped because of a branch. Go on */
1957            break;
1958        case POWERPC_EXCP_SYSCALL_USER:
1959            /* system call in user-mode emulation */
1960            /* WARNING:
1961             * PPC ABI uses overflow flag in cr0 to signal an error
1962             * in syscalls.
1963             */
1964            env->crf[0] &= ~0x1;
1965            ret = do_syscall(env, env->gpr[0], env->gpr[3], env->gpr[4],
1966                             env->gpr[5], env->gpr[6], env->gpr[7],
1967                             env->gpr[8], 0, 0);
1968            if (ret == (target_ulong)(-TARGET_QEMU_ESIGRETURN)) {
1969                /* Returning from a successful sigreturn syscall.
1970                   Avoid corrupting register state.  */
1971                break;
1972            }
1973            if (ret > (target_ulong)(-515)) {
1974                env->crf[0] |= 0x1;
1975                ret = -ret;
1976            }
1977            env->gpr[3] = ret;
1978            break;
1979        case POWERPC_EXCP_STCX:
1980            if (do_store_exclusive(env)) {
1981                info.si_signo = TARGET_SIGSEGV;
1982                info.si_errno = 0;
1983                info.si_code = TARGET_SEGV_MAPERR;
1984                info._sifields._sigfault._addr = env->nip;
1985                queue_signal(env, info.si_signo, &info);
1986            }
1987            break;
1988        case EXCP_DEBUG:
1989            {
1990                int sig;
1991
1992                sig = gdb_handlesig(cs, TARGET_SIGTRAP);
1993                if (sig) {
1994                    info.si_signo = sig;
1995                    info.si_errno = 0;
1996                    info.si_code = TARGET_TRAP_BRKPT;
1997                    queue_signal(env, info.si_signo, &info);
1998                  }
1999            }
2000            break;
2001        case EXCP_INTERRUPT:
2002            /* just indicate that signals should be handled asap */
2003            break;
2004        default:
2005            cpu_abort(cs, "Unknown exception 0x%d. Aborting\n", trapnr);
2006            break;
2007        }
2008        process_pending_signals(env);
2009    }
2010}
2011#endif
2012
2013#ifdef TARGET_MIPS
2014
2015# ifdef TARGET_ABI_MIPSO32
2016#  define MIPS_SYS(name, args) args,
2017static const uint8_t mips_syscall_args[] = {
2018        MIPS_SYS(sys_syscall    , 8)    /* 4000 */
2019        MIPS_SYS(sys_exit       , 1)
2020        MIPS_SYS(sys_fork       , 0)
2021        MIPS_SYS(sys_read       , 3)
2022        MIPS_SYS(sys_write      , 3)
2023        MIPS_SYS(sys_open       , 3)    /* 4005 */
2024        MIPS_SYS(sys_close      , 1)
2025        MIPS_SYS(sys_waitpid    , 3)
2026        MIPS_SYS(sys_creat      , 2)
2027        MIPS_SYS(sys_link       , 2)
2028        MIPS_SYS(sys_unlink     , 1)    /* 4010 */
2029        MIPS_SYS(sys_execve     , 0)
2030        MIPS_SYS(sys_chdir      , 1)
2031        MIPS_SYS(sys_time       , 1)
2032        MIPS_SYS(sys_mknod      , 3)
2033        MIPS_SYS(sys_chmod      , 2)    /* 4015 */
2034        MIPS_SYS(sys_lchown     , 3)
2035        MIPS_SYS(sys_ni_syscall , 0)
2036        MIPS_SYS(sys_ni_syscall , 0)    /* was sys_stat */
2037        MIPS_SYS(sys_lseek      , 3)
2038        MIPS_SYS(sys_getpid     , 0)    /* 4020 */
2039        MIPS_SYS(sys_mount      , 5)
2040        MIPS_SYS(sys_umount     , 1)
2041        MIPS_SYS(sys_setuid     , 1)
2042        MIPS_SYS(sys_getuid     , 0)
2043        MIPS_SYS(sys_stime      , 1)    /* 4025 */
2044        MIPS_SYS(sys_ptrace     , 4)
2045        MIPS_SYS(sys_alarm      , 1)
2046        MIPS_SYS(sys_ni_syscall , 0)    /* was sys_fstat */
2047        MIPS_SYS(sys_pause      , 0)
2048        MIPS_SYS(sys_utime      , 2)    /* 4030 */
2049        MIPS_SYS(sys_ni_syscall , 0)
2050        MIPS_SYS(sys_ni_syscall , 0)
2051        MIPS_SYS(sys_access     , 2)
2052        MIPS_SYS(sys_nice       , 1)
2053        MIPS_SYS(sys_ni_syscall , 0)    /* 4035 */
2054        MIPS_SYS(sys_sync       , 0)
2055        MIPS_SYS(sys_kill       , 2)
2056        MIPS_SYS(sys_rename     , 2)
2057        MIPS_SYS(sys_mkdir      , 2)
2058        MIPS_SYS(sys_rmdir      , 1)    /* 4040 */
2059        MIPS_SYS(sys_dup                , 1)
2060        MIPS_SYS(sys_pipe       , 0)
2061        MIPS_SYS(sys_times      , 1)
2062        MIPS_SYS(sys_ni_syscall , 0)
2063        MIPS_SYS(sys_brk                , 1)    /* 4045 */
2064        MIPS_SYS(sys_setgid     , 1)
2065        MIPS_SYS(sys_getgid     , 0)
2066        MIPS_SYS(sys_ni_syscall , 0)    /* was signal(2) */
2067        MIPS_SYS(sys_geteuid    , 0)
2068        MIPS_SYS(sys_getegid    , 0)    /* 4050 */
2069        MIPS_SYS(sys_acct       , 0)
2070        MIPS_SYS(sys_umount2    , 2)
2071        MIPS_SYS(sys_ni_syscall , 0)
2072        MIPS_SYS(sys_ioctl      , 3)
2073        MIPS_SYS(sys_fcntl      , 3)    /* 4055 */
2074        MIPS_SYS(sys_ni_syscall , 2)
2075        MIPS_SYS(sys_setpgid    , 2)
2076        MIPS_SYS(sys_ni_syscall , 0)
2077        MIPS_SYS(sys_olduname   , 1)
2078        MIPS_SYS(sys_umask      , 1)    /* 4060 */
2079        MIPS_SYS(sys_chroot     , 1)
2080        MIPS_SYS(sys_ustat      , 2)
2081        MIPS_SYS(sys_dup2       , 2)
2082        MIPS_SYS(sys_getppid    , 0)
2083        MIPS_SYS(sys_getpgrp    , 0)    /* 4065 */
2084        MIPS_SYS(sys_setsid     , 0)
2085        MIPS_SYS(sys_sigaction  , 3)
2086        MIPS_SYS(sys_sgetmask   , 0)
2087        MIPS_SYS(sys_ssetmask   , 1)
2088        MIPS_SYS(sys_setreuid   , 2)    /* 4070 */
2089        MIPS_SYS(sys_setregid   , 2)
2090        MIPS_SYS(sys_sigsuspend , 0)
2091        MIPS_SYS(sys_sigpending , 1)
2092        MIPS_SYS(sys_sethostname        , 2)
2093        MIPS_SYS(sys_setrlimit  , 2)    /* 4075 */
2094        MIPS_SYS(sys_getrlimit  , 2)
2095        MIPS_SYS(sys_getrusage  , 2)
2096        MIPS_SYS(sys_gettimeofday, 2)
2097        MIPS_SYS(sys_settimeofday, 2)
2098        MIPS_SYS(sys_getgroups  , 2)    /* 4080 */
2099        MIPS_SYS(sys_setgroups  , 2)
2100        MIPS_SYS(sys_ni_syscall , 0)    /* old_select */
2101        MIPS_SYS(sys_symlink    , 2)
2102        MIPS_SYS(sys_ni_syscall , 0)    /* was sys_lstat */
2103        MIPS_SYS(sys_readlink   , 3)    /* 4085 */
2104        MIPS_SYS(sys_uselib     , 1)
2105        MIPS_SYS(sys_swapon     , 2)
2106        MIPS_SYS(sys_reboot     , 3)
2107        MIPS_SYS(old_readdir    , 3)
2108        MIPS_SYS(old_mmap       , 6)    /* 4090 */
2109        MIPS_SYS(sys_munmap     , 2)
2110        MIPS_SYS(sys_truncate   , 2)
2111        MIPS_SYS(sys_ftruncate  , 2)
2112        MIPS_SYS(sys_fchmod     , 2)
2113        MIPS_SYS(sys_fchown     , 3)    /* 4095 */
2114        MIPS_SYS(sys_getpriority        , 2)
2115        MIPS_SYS(sys_setpriority        , 3)
2116        MIPS_SYS(sys_ni_syscall , 0)
2117        MIPS_SYS(sys_statfs     , 2)
2118        MIPS_SYS(sys_fstatfs    , 2)    /* 4100 */
2119        MIPS_SYS(sys_ni_syscall , 0)    /* was ioperm(2) */
2120        MIPS_SYS(sys_socketcall , 2)
2121        MIPS_SYS(sys_syslog     , 3)
2122        MIPS_SYS(sys_setitimer  , 3)
2123        MIPS_SYS(sys_getitimer  , 2)    /* 4105 */
2124        MIPS_SYS(sys_newstat    , 2)
2125        MIPS_SYS(sys_newlstat   , 2)
2126        MIPS_SYS(sys_newfstat   , 2)
2127        MIPS_SYS(sys_uname      , 1)
2128        MIPS_SYS(sys_ni_syscall , 0)    /* 4110 was iopl(2) */
2129        MIPS_SYS(sys_vhangup    , 0)
2130        MIPS_SYS(sys_ni_syscall , 0)    /* was sys_idle() */
2131        MIPS_SYS(sys_ni_syscall , 0)    /* was sys_vm86 */
2132        MIPS_SYS(sys_wait4      , 4)
2133        MIPS_SYS(sys_swapoff    , 1)    /* 4115 */
2134        MIPS_SYS(sys_sysinfo    , 1)
2135        MIPS_SYS(sys_ipc                , 6)
2136        MIPS_SYS(sys_fsync      , 1)
2137        MIPS_SYS(sys_sigreturn  , 0)
2138        MIPS_SYS(sys_clone      , 6)    /* 4120 */
2139        MIPS_SYS(sys_setdomainname, 2)
2140        MIPS_SYS(sys_newuname   , 1)
2141        MIPS_SYS(sys_ni_syscall , 0)    /* sys_modify_ldt */
2142        MIPS_SYS(sys_adjtimex   , 1)
2143        MIPS_SYS(sys_mprotect   , 3)    /* 4125 */
2144        MIPS_SYS(sys_sigprocmask        , 3)
2145        MIPS_SYS(sys_ni_syscall , 0)    /* was create_module */
2146        MIPS_SYS(sys_init_module        , 5)
2147        MIPS_SYS(sys_delete_module, 1)
2148        MIPS_SYS(sys_ni_syscall , 0)    /* 4130 was get_kernel_syms */
2149        MIPS_SYS(sys_quotactl   , 0)
2150        MIPS_SYS(sys_getpgid    , 1)
2151        MIPS_SYS(sys_fchdir     , 1)
2152        MIPS_SYS(sys_bdflush    , 2)
2153        MIPS_SYS(sys_sysfs      , 3)    /* 4135 */
2154        MIPS_SYS(sys_personality        , 1)
2155        MIPS_SYS(sys_ni_syscall , 0)    /* for afs_syscall */
2156        MIPS_SYS(sys_setfsuid   , 1)
2157        MIPS_SYS(sys_setfsgid   , 1)
2158        MIPS_SYS(sys_llseek     , 5)    /* 4140 */
2159        MIPS_SYS(sys_getdents   , 3)
2160        MIPS_SYS(sys_select     , 5)
2161        MIPS_SYS(sys_flock      , 2)
2162        MIPS_SYS(sys_msync      , 3)
2163        MIPS_SYS(sys_readv      , 3)    /* 4145 */
2164        MIPS_SYS(sys_writev     , 3)
2165        MIPS_SYS(sys_cacheflush , 3)
2166        MIPS_SYS(sys_cachectl   , 3)
2167        MIPS_SYS(sys_sysmips    , 4)
2168        MIPS_SYS(sys_ni_syscall , 0)    /* 4150 */
2169        MIPS_SYS(sys_getsid     , 1)
2170        MIPS_SYS(sys_fdatasync  , 0)
2171        MIPS_SYS(sys_sysctl     , 1)
2172        MIPS_SYS(sys_mlock      , 2)
2173        MIPS_SYS(sys_munlock    , 2)    /* 4155 */
2174        MIPS_SYS(sys_mlockall   , 1)
2175        MIPS_SYS(sys_munlockall , 0)
2176        MIPS_SYS(sys_sched_setparam, 2)
2177        MIPS_SYS(sys_sched_getparam, 2)
2178        MIPS_SYS(sys_sched_setscheduler, 3)     /* 4160 */
2179        MIPS_SYS(sys_sched_getscheduler, 1)
2180        MIPS_SYS(sys_sched_yield        , 0)
2181        MIPS_SYS(sys_sched_get_priority_max, 1)
2182        MIPS_SYS(sys_sched_get_priority_min, 1)
2183        MIPS_SYS(sys_sched_rr_get_interval, 2)  /* 4165 */
2184        MIPS_SYS(sys_nanosleep, 2)
2185        MIPS_SYS(sys_mremap     , 5)
2186        MIPS_SYS(sys_accept     , 3)
2187        MIPS_SYS(sys_bind       , 3)
2188        MIPS_SYS(sys_connect    , 3)    /* 4170 */
2189        MIPS_SYS(sys_getpeername        , 3)
2190        MIPS_SYS(sys_getsockname        , 3)
2191        MIPS_SYS(sys_getsockopt , 5)
2192        MIPS_SYS(sys_listen     , 2)
2193        MIPS_SYS(sys_recv       , 4)    /* 4175 */
2194        MIPS_SYS(sys_recvfrom   , 6)
2195        MIPS_SYS(sys_recvmsg    , 3)
2196        MIPS_SYS(sys_send       , 4)
2197        MIPS_SYS(sys_sendmsg    , 3)
2198        MIPS_SYS(sys_sendto     , 6)    /* 4180 */
2199        MIPS_SYS(sys_setsockopt , 5)
2200        MIPS_SYS(sys_shutdown   , 2)
2201        MIPS_SYS(sys_socket     , 3)
2202        MIPS_SYS(sys_socketpair , 4)
2203        MIPS_SYS(sys_setresuid  , 3)    /* 4185 */
2204        MIPS_SYS(sys_getresuid  , 3)
2205        MIPS_SYS(sys_ni_syscall , 0)    /* was sys_query_module */
2206        MIPS_SYS(sys_poll       , 3)
2207        MIPS_SYS(sys_nfsservctl , 3)
2208        MIPS_SYS(sys_setresgid  , 3)    /* 4190 */
2209        MIPS_SYS(sys_getresgid  , 3)
2210        MIPS_SYS(sys_prctl      , 5)
2211        MIPS_SYS(sys_rt_sigreturn, 0)
2212        MIPS_SYS(sys_rt_sigaction, 4)
2213        MIPS_SYS(sys_rt_sigprocmask, 4) /* 4195 */
2214        MIPS_SYS(sys_rt_sigpending, 2)
2215        MIPS_SYS(sys_rt_sigtimedwait, 4)
2216        MIPS_SYS(sys_rt_sigqueueinfo, 3)
2217        MIPS_SYS(sys_rt_sigsuspend, 0)
2218        MIPS_SYS(sys_pread64    , 6)    /* 4200 */
2219        MIPS_SYS(sys_pwrite64   , 6)
2220        MIPS_SYS(sys_chown      , 3)
2221        MIPS_SYS(sys_getcwd     , 2)
2222        MIPS_SYS(sys_capget     , 2)
2223        MIPS_SYS(sys_capset     , 2)    /* 4205 */
2224        MIPS_SYS(sys_sigaltstack        , 2)
2225        MIPS_SYS(sys_sendfile   , 4)
2226        MIPS_SYS(sys_ni_syscall , 0)
2227        MIPS_SYS(sys_ni_syscall , 0)
2228        MIPS_SYS(sys_mmap2      , 6)    /* 4210 */
2229        MIPS_SYS(sys_truncate64 , 4)
2230        MIPS_SYS(sys_ftruncate64        , 4)
2231        MIPS_SYS(sys_stat64     , 2)
2232        MIPS_SYS(sys_lstat64    , 2)
2233        MIPS_SYS(sys_fstat64    , 2)    /* 4215 */
2234        MIPS_SYS(sys_pivot_root , 2)
2235        MIPS_SYS(sys_mincore    , 3)
2236        MIPS_SYS(sys_madvise    , 3)
2237        MIPS_SYS(sys_getdents64 , 3)
2238        MIPS_SYS(sys_fcntl64    , 3)    /* 4220 */
2239        MIPS_SYS(sys_ni_syscall , 0)
2240        MIPS_SYS(sys_gettid     , 0)
2241        MIPS_SYS(sys_readahead  , 5)
2242        MIPS_SYS(sys_setxattr   , 5)
2243        MIPS_SYS(sys_lsetxattr  , 5)    /* 4225 */
2244        MIPS_SYS(sys_fsetxattr  , 5)
2245        MIPS_SYS(sys_getxattr   , 4)
2246        MIPS_SYS(sys_lgetxattr  , 4)
2247        MIPS_SYS(sys_fgetxattr  , 4)
2248        MIPS_SYS(sys_listxattr  , 3)    /* 4230 */
2249        MIPS_SYS(sys_llistxattr , 3)
2250        MIPS_SYS(sys_flistxattr , 3)
2251        MIPS_SYS(sys_removexattr        , 2)
2252        MIPS_SYS(sys_lremovexattr, 2)
2253        MIPS_SYS(sys_fremovexattr, 2)   /* 4235 */
2254        MIPS_SYS(sys_tkill      , 2)
2255        MIPS_SYS(sys_sendfile64 , 5)
2256        MIPS_SYS(sys_futex      , 6)
2257        MIPS_SYS(sys_sched_setaffinity, 3)
2258        MIPS_SYS(sys_sched_getaffinity, 3)      /* 4240 */
2259        MIPS_SYS(sys_io_setup   , 2)
2260        MIPS_SYS(sys_io_destroy , 1)
2261        MIPS_SYS(sys_io_getevents, 5)
2262        MIPS_SYS(sys_io_submit  , 3)
2263        MIPS_SYS(sys_io_cancel  , 3)    /* 4245 */
2264        MIPS_SYS(sys_exit_group , 1)
2265        MIPS_SYS(sys_lookup_dcookie, 3)
2266        MIPS_SYS(sys_epoll_create, 1)
2267        MIPS_SYS(sys_epoll_ctl  , 4)
2268        MIPS_SYS(sys_epoll_wait , 3)    /* 4250 */
2269        MIPS_SYS(sys_remap_file_pages, 5)
2270        MIPS_SYS(sys_set_tid_address, 1)
2271        MIPS_SYS(sys_restart_syscall, 0)
2272        MIPS_SYS(sys_fadvise64_64, 7)
2273        MIPS_SYS(sys_statfs64   , 3)    /* 4255 */
2274        MIPS_SYS(sys_fstatfs64  , 2)
2275        MIPS_SYS(sys_timer_create, 3)
2276        MIPS_SYS(sys_timer_settime, 4)
2277        MIPS_SYS(sys_timer_gettime, 2)
2278        MIPS_SYS(sys_timer_getoverrun, 1)       /* 4260 */
2279        MIPS_SYS(sys_timer_delete, 1)
2280        MIPS_SYS(sys_clock_settime, 2)
2281        MIPS_SYS(sys_clock_gettime, 2)
2282        MIPS_SYS(sys_clock_getres, 2)
2283        MIPS_SYS(sys_clock_nanosleep, 4)        /* 4265 */
2284        MIPS_SYS(sys_tgkill     , 3)
2285        MIPS_SYS(sys_utimes     , 2)
2286        MIPS_SYS(sys_mbind      , 4)
2287        MIPS_SYS(sys_ni_syscall , 0)    /* sys_get_mempolicy */
2288        MIPS_SYS(sys_ni_syscall , 0)    /* 4270 sys_set_mempolicy */
2289        MIPS_SYS(sys_mq_open    , 4)
2290        MIPS_SYS(sys_mq_unlink  , 1)
2291        MIPS_SYS(sys_mq_timedsend, 5)
2292        MIPS_SYS(sys_mq_timedreceive, 5)
2293        MIPS_SYS(sys_mq_notify  , 2)    /* 4275 */
2294        MIPS_SYS(sys_mq_getsetattr, 3)
2295        MIPS_SYS(sys_ni_syscall , 0)    /* sys_vserver */
2296        MIPS_SYS(sys_waitid     , 4)
2297        MIPS_SYS(sys_ni_syscall , 0)    /* available, was setaltroot */
2298        MIPS_SYS(sys_add_key    , 5)
2299        MIPS_SYS(sys_request_key, 4)
2300        MIPS_SYS(sys_keyctl     , 5)
2301        MIPS_SYS(sys_set_thread_area, 1)
2302        MIPS_SYS(sys_inotify_init, 0)
2303        MIPS_SYS(sys_inotify_add_watch, 3) /* 4285 */
2304        MIPS_SYS(sys_inotify_rm_watch, 2)
2305        MIPS_SYS(sys_migrate_pages, 4)
2306        MIPS_SYS(sys_openat, 4)
2307        MIPS_SYS(sys_mkdirat, 3)
2308        MIPS_SYS(sys_mknodat, 4)        /* 4290 */
2309        MIPS_SYS(sys_fchownat, 5)
2310        MIPS_SYS(sys_futimesat, 3)
2311        MIPS_SYS(sys_fstatat64, 4)
2312        MIPS_SYS(sys_unlinkat, 3)
2313        MIPS_SYS(sys_renameat, 4)       /* 4295 */
2314        MIPS_SYS(sys_linkat, 5)
2315        MIPS_SYS(sys_symlinkat, 3)
2316        MIPS_SYS(sys_readlinkat, 4)
2317        MIPS_SYS(sys_fchmodat, 3)
2318        MIPS_SYS(sys_faccessat, 3)      /* 4300 */
2319        MIPS_SYS(sys_pselect6, 6)
2320        MIPS_SYS(sys_ppoll, 5)
2321        MIPS_SYS(sys_unshare, 1)
2322        MIPS_SYS(sys_splice, 6)
2323        MIPS_SYS(sys_sync_file_range, 7) /* 4305 */
2324        MIPS_SYS(sys_tee, 4)
2325        MIPS_SYS(sys_vmsplice, 4)
2326        MIPS_SYS(sys_move_pages, 6)
2327        MIPS_SYS(sys_set_robust_list, 2)
2328        MIPS_SYS(sys_get_robust_list, 3) /* 4310 */
2329        MIPS_SYS(sys_kexec_load, 4)
2330        MIPS_SYS(sys_getcpu, 3)
2331        MIPS_SYS(sys_epoll_pwait, 6)
2332        MIPS_SYS(sys_ioprio_set, 3)
2333        MIPS_SYS(sys_ioprio_get, 2)
2334        MIPS_SYS(sys_utimensat, 4)
2335        MIPS_SYS(sys_signalfd, 3)
2336        MIPS_SYS(sys_ni_syscall, 0)     /* was timerfd */
2337        MIPS_SYS(sys_eventfd, 1)
2338        MIPS_SYS(sys_fallocate, 6)      /* 4320 */
2339        MIPS_SYS(sys_timerfd_create, 2)
2340        MIPS_SYS(sys_timerfd_gettime, 2)
2341        MIPS_SYS(sys_timerfd_settime, 4)
2342        MIPS_SYS(sys_signalfd4, 4)
2343        MIPS_SYS(sys_eventfd2, 2)       /* 4325 */
2344        MIPS_SYS(sys_epoll_create1, 1)
2345        MIPS_SYS(sys_dup3, 3)
2346        MIPS_SYS(sys_pipe2, 2)
2347        MIPS_SYS(sys_inotify_init1, 1)
2348        MIPS_SYS(sys_preadv, 6)         /* 4330 */
2349        MIPS_SYS(sys_pwritev, 6)
2350        MIPS_SYS(sys_rt_tgsigqueueinfo, 4)
2351        MIPS_SYS(sys_perf_event_open, 5)
2352        MIPS_SYS(sys_accept4, 4)
2353        MIPS_SYS(sys_recvmmsg, 5)       /* 4335 */
2354        MIPS_SYS(sys_fanotify_init, 2)
2355        MIPS_SYS(sys_fanotify_mark, 6)
2356        MIPS_SYS(sys_prlimit64, 4)
2357        MIPS_SYS(sys_name_to_handle_at, 5)
2358        MIPS_SYS(sys_open_by_handle_at, 3) /* 4340 */
2359        MIPS_SYS(sys_clock_adjtime, 2)
2360        MIPS_SYS(sys_syncfs, 1)
2361};
2362#  undef MIPS_SYS
2363# endif /* O32 */
2364
2365static int do_store_exclusive(CPUMIPSState *env)
2366{
2367    target_ulong addr;
2368    target_ulong page_addr;
2369    target_ulong val;
2370    int flags;
2371    int segv = 0;
2372    int reg;
2373    int d;
2374
2375    addr = env->lladdr;
2376    page_addr = addr & TARGET_PAGE_MASK;
2377    start_exclusive();
2378    mmap_lock();
2379    flags = page_get_flags(page_addr);
2380    if ((flags & PAGE_READ) == 0) {
2381        segv = 1;
2382    } else {
2383        reg = env->llreg & 0x1f;
2384        d = (env->llreg & 0x20) != 0;
2385        if (d) {
2386            segv = get_user_s64(val, addr);
2387        } else {
2388            segv = get_user_s32(val, addr);
2389        }
2390        if (!segv) {
2391            if (val != env->llval) {
2392                env->active_tc.gpr[reg] = 0;
2393            } else {
2394                if (d) {
2395                    segv = put_user_u64(env->llnewval, addr);
2396                } else {
2397                    segv = put_user_u32(env->llnewval, addr);
2398                }
2399                if (!segv) {
2400                    env->active_tc.gpr[reg] = 1;
2401                }
2402            }
2403        }
2404    }
2405    env->lladdr = -1;
2406    if (!segv) {
2407        env->active_tc.PC += 4;
2408    }
2409    mmap_unlock();
2410    end_exclusive();
2411    return segv;
2412}
2413
2414/* Break codes */
2415enum {
2416    BRK_OVERFLOW = 6,
2417    BRK_DIVZERO = 7
2418};
2419
2420static int do_break(CPUMIPSState *env, target_siginfo_t *info,
2421                    unsigned int code)
2422{
2423    int ret = -1;
2424
2425    switch (code) {
2426    case BRK_OVERFLOW:
2427    case BRK_DIVZERO:
2428        info->si_signo = TARGET_SIGFPE;
2429        info->si_errno = 0;
2430        info->si_code = (code == BRK_OVERFLOW) ? FPE_INTOVF : FPE_INTDIV;
2431        queue_signal(env, info->si_signo, &*info);
2432        ret = 0;
2433        break;
2434    default:
2435        info->si_signo = TARGET_SIGTRAP;
2436        info->si_errno = 0;
2437        queue_signal(env, info->si_signo, &*info);
2438        ret = 0;
2439        break;
2440    }
2441
2442    return ret;
2443}
2444
2445void cpu_loop(CPUMIPSState *env)
2446{
2447    CPUState *cs = CPU(mips_env_get_cpu(env));
2448    target_siginfo_t info;
2449    int trapnr;
2450    abi_long ret;
2451# ifdef TARGET_ABI_MIPSO32
2452    unsigned int syscall_num;
2453# endif
2454
2455    for(;;) {
2456        cpu_exec_start(cs);
2457        trapnr = cpu_mips_exec(cs);
2458        cpu_exec_end(cs);
2459        switch(trapnr) {
2460        case EXCP_SYSCALL:
2461            env->active_tc.PC += 4;
2462# ifdef TARGET_ABI_MIPSO32
2463            syscall_num = env->active_tc.gpr[2] - 4000;
2464            if (syscall_num >= sizeof(mips_syscall_args)) {
2465                ret = -TARGET_ENOSYS;
2466            } else {
2467                int nb_args;
2468                abi_ulong sp_reg;
2469                abi_ulong arg5 = 0, arg6 = 0, arg7 = 0, arg8 = 0;
2470
2471                nb_args = mips_syscall_args[syscall_num];
2472                sp_reg = env->active_tc.gpr[29];
2473                switch (nb_args) {
2474                /* these arguments are taken from the stack */
2475                case 8:
2476                    if ((ret = get_user_ual(arg8, sp_reg + 28)) != 0) {
2477                        goto done_syscall;
2478                    }
2479                case 7:
2480                    if ((ret = get_user_ual(arg7, sp_reg + 24)) != 0) {
2481                        goto done_syscall;
2482                    }
2483                case 6:
2484                    if ((ret = get_user_ual(arg6, sp_reg + 20)) != 0) {
2485                        goto done_syscall;
2486                    }
2487                case 5:
2488                    if ((ret = get_user_ual(arg5, sp_reg + 16)) != 0) {
2489                        goto done_syscall;
2490                    }
2491                default:
2492                    break;
2493                }
2494                ret = do_syscall(env, env->active_tc.gpr[2],
2495                                 env->active_tc.gpr[4],
2496                                 env->active_tc.gpr[5],
2497                                 env->active_tc.gpr[6],
2498                                 env->active_tc.gpr[7],
2499                                 arg5, arg6, arg7, arg8);
2500            }
2501done_syscall:
2502# else
2503            ret = do_syscall(env, env->active_tc.gpr[2],
2504                             env->active_tc.gpr[4], env->active_tc.gpr[5],
2505                             env->active_tc.gpr[6], env->active_tc.gpr[7],
2506                             env->active_tc.gpr[8], env->active_tc.gpr[9],
2507                             env->active_tc.gpr[10], env->active_tc.gpr[11]);
2508# endif /* O32 */
2509            if (ret == -TARGET_QEMU_ESIGRETURN) {
2510                /* Returning from a successful sigreturn syscall.
2511                   Avoid clobbering register state.  */
2512                break;
2513            }
2514            if ((abi_ulong)ret >= (abi_ulong)-1133) {
2515                env->active_tc.gpr[7] = 1; /* error flag */
2516                ret = -ret;
2517            } else {
2518                env->active_tc.gpr[7] = 0; /* error flag */
2519            }
2520            env->active_tc.gpr[2] = ret;
2521            break;
2522        case EXCP_TLBL:
2523        case EXCP_TLBS:
2524        case EXCP_AdEL:
2525        case EXCP_AdES:
2526            info.si_signo = TARGET_SIGSEGV;
2527            info.si_errno = 0;
2528            /* XXX: check env->error_code */
2529            info.si_code = TARGET_SEGV_MAPERR;
2530            info._sifields._sigfault._addr = env->CP0_BadVAddr;
2531            queue_signal(env, info.si_signo, &info);
2532            break;
2533        case EXCP_CpU:
2534        case EXCP_RI:
2535            info.si_signo = TARGET_SIGILL;
2536            info.si_errno = 0;
2537            info.si_code = 0;
2538            queue_signal(env, info.si_signo, &info);
2539            break;
2540        case EXCP_INTERRUPT:
2541            /* just indicate that signals should be handled asap */
2542            break;
2543        case EXCP_DEBUG:
2544            {
2545                int sig;
2546
2547                sig = gdb_handlesig(cs, TARGET_SIGTRAP);
2548                if (sig)
2549                  {
2550                    info.si_signo = sig;
2551                    info.si_errno = 0;
2552                    info.si_code = TARGET_TRAP_BRKPT;
2553                    queue_signal(env, info.si_signo, &info);
2554                  }
2555            }
2556            break;
2557        case EXCP_SC:
2558            if (do_store_exclusive(env)) {
2559                info.si_signo = TARGET_SIGSEGV;
2560                info.si_errno = 0;
2561                info.si_code = TARGET_SEGV_MAPERR;
2562                info._sifields._sigfault._addr = env->active_tc.PC;
2563                queue_signal(env, info.si_signo, &info);
2564            }
2565            break;
2566        case EXCP_DSPDIS:
2567            info.si_signo = TARGET_SIGILL;
2568            info.si_errno = 0;
2569            info.si_code = TARGET_ILL_ILLOPC;
2570            queue_signal(env, info.si_signo, &info);
2571            break;
2572        /* The code below was inspired by the MIPS Linux kernel trap
2573         * handling code in arch/mips/kernel/traps.c.
2574         */
2575        case EXCP_BREAK:
2576            {
2577                abi_ulong trap_instr;
2578                unsigned int code;
2579
2580                if (env->hflags & MIPS_HFLAG_M16) {
2581                    if (env->insn_flags & ASE_MICROMIPS) {
2582                        /* microMIPS mode */
2583                        ret = get_user_u16(trap_instr, env->active_tc.PC);
2584                        if (ret != 0) {
2585                            goto error;
2586                        }
2587
2588                        if ((trap_instr >> 10) == 0x11) {
2589                            /* 16-bit instruction */
2590                            code = trap_instr & 0xf;
2591                        } else {
2592                            /* 32-bit instruction */
2593                            abi_ulong instr_lo;
2594
2595                            ret = get_user_u16(instr_lo,
2596                                               env->active_tc.PC + 2);
2597                            if (ret != 0) {
2598                                goto error;
2599                            }
2600                            trap_instr = (trap_instr << 16) | instr_lo;
2601                            code = ((trap_instr >> 6) & ((1 << 20) - 1));
2602                            /* Unfortunately, microMIPS also suffers from
2603                               the old assembler bug...  */
2604                            if (code >= (1 << 10)) {
2605                                code >>= 10;
2606                            }
2607                        }
2608                    } else {
2609                        /* MIPS16e mode */
2610                        ret = get_user_u16(trap_instr, env->active_tc.PC);
2611                        if (ret != 0) {
2612                            goto error;
2613                        }
2614                        code = (trap_instr >> 6) & 0x3f;
2615                    }
2616                } else {
2617                    ret = get_user_u32(trap_instr, env->active_tc.PC);
2618                    if (ret != 0) {
2619                        goto error;
2620                    }
2621
2622                    /* As described in the original Linux kernel code, the
2623                     * below checks on 'code' are to work around an old
2624                     * assembly bug.
2625                     */
2626                    code = ((trap_instr >> 6) & ((1 << 20) - 1));
2627                    if (code >= (1 << 10)) {
2628                        code >>= 10;
2629                    }
2630                }
2631
2632                if (do_break(env, &info, code) != 0) {
2633                    goto error;
2634                }
2635            }
2636            break;
2637        case EXCP_TRAP:
2638            {
2639                abi_ulong trap_instr;
2640                unsigned int code = 0;
2641
2642                if (env->hflags & MIPS_HFLAG_M16) {
2643                    /* microMIPS mode */
2644                    abi_ulong instr[2];
2645
2646                    ret = get_user_u16(instr[0], env->active_tc.PC) ||
2647                          get_user_u16(instr[1], env->active_tc.PC + 2);
2648
2649                    trap_instr = (instr[0] << 16) | instr[1];
2650                } else {
2651                    ret = get_user_u32(trap_instr, env->active_tc.PC);
2652                }
2653
2654                if (ret != 0) {
2655                    goto error;
2656                }
2657
2658                /* The immediate versions don't provide a code.  */
2659                if (!(trap_instr & 0xFC000000)) {
2660                    if (env->hflags & MIPS_HFLAG_M16) {
2661                        /* microMIPS mode */
2662                        code = ((trap_instr >> 12) & ((1 << 4) - 1));
2663                    } else {
2664                        code = ((trap_instr >> 6) & ((1 << 10) - 1));
2665                    }
2666                }
2667
2668                if (do_break(env, &info, code) != 0) {
2669                    goto error;
2670                }
2671            }
2672            break;
2673        default:
2674error:
2675            EXCP_DUMP(env, "qemu: unhandled CPU exception 0x%x - aborting\n", trapnr);
2676            abort();
2677        }
2678        process_pending_signals(env);
2679    }
2680}
2681#endif
2682
2683#ifdef TARGET_OPENRISC
2684
2685void cpu_loop(CPUOpenRISCState *env)
2686{
2687    CPUState *cs = CPU(openrisc_env_get_cpu(env));
2688    int trapnr, gdbsig;
2689
2690    for (;;) {
2691        cpu_exec_start(cs);
2692        trapnr = cpu_openrisc_exec(cs);
2693        cpu_exec_end(cs);
2694        gdbsig = 0;
2695
2696        switch (trapnr) {
2697        case EXCP_RESET:
2698            qemu_log_mask(CPU_LOG_INT, "\nReset request, exit, pc is %#x\n", env->pc);
2699            exit(EXIT_FAILURE);
2700            break;
2701        case EXCP_BUSERR:
2702            qemu_log_mask(CPU_LOG_INT, "\nBus error, exit, pc is %#x\n", env->pc);
2703            gdbsig = TARGET_SIGBUS;
2704            break;
2705        case EXCP_DPF:
2706        case EXCP_IPF:
2707            cpu_dump_state(cs, stderr, fprintf, 0);
2708            gdbsig = TARGET_SIGSEGV;
2709            break;
2710        case EXCP_TICK:
2711            qemu_log_mask(CPU_LOG_INT, "\nTick time interrupt pc is %#x\n", env->pc);
2712            break;
2713        case EXCP_ALIGN:
2714            qemu_log_mask(CPU_LOG_INT, "\nAlignment pc is %#x\n", env->pc);
2715            gdbsig = TARGET_SIGBUS;
2716            break;
2717        case EXCP_ILLEGAL:
2718            qemu_log_mask(CPU_LOG_INT, "\nIllegal instructionpc is %#x\n", env->pc);
2719            gdbsig = TARGET_SIGILL;
2720            break;
2721        case EXCP_INT:
2722            qemu_log_mask(CPU_LOG_INT, "\nExternal interruptpc is %#x\n", env->pc);
2723            break;
2724        case EXCP_DTLBMISS:
2725        case EXCP_ITLBMISS:
2726            qemu_log_mask(CPU_LOG_INT, "\nTLB miss\n");
2727            break;
2728        case EXCP_RANGE:
2729            qemu_log_mask(CPU_LOG_INT, "\nRange\n");
2730            gdbsig = TARGET_SIGSEGV;
2731            break;
2732        case EXCP_SYSCALL:
2733            env->pc += 4;   /* 0xc00; */
2734            env->gpr[11] = do_syscall(env,
2735                                      env->gpr[11], /* return value       */
2736                                      env->gpr[3],  /* r3 - r7 are params */
2737                                      env->gpr[4],
2738                                      env->gpr[5],
2739                                      env->gpr[6],
2740                                      env->gpr[7],
2741                                      env->gpr[8], 0, 0);
2742            break;
2743        case EXCP_FPE:
2744            qemu_log_mask(CPU_LOG_INT, "\nFloating point error\n");
2745            break;
2746        case EXCP_TRAP:
2747            qemu_log_mask(CPU_LOG_INT, "\nTrap\n");
2748            gdbsig = TARGET_SIGTRAP;
2749            break;
2750        case EXCP_NR:
2751            qemu_log_mask(CPU_LOG_INT, "\nNR\n");
2752            break;
2753        default:
2754            EXCP_DUMP(env, "\nqemu: unhandled CPU exception %#x - aborting\n",
2755                     trapnr);
2756            gdbsig = TARGET_SIGILL;
2757            break;
2758        }
2759        if (gdbsig) {
2760            gdb_handlesig(cs, gdbsig);
2761            if (gdbsig != TARGET_SIGTRAP) {
2762                exit(EXIT_FAILURE);
2763            }
2764        }
2765
2766        process_pending_signals(env);
2767    }
2768}
2769
2770#endif /* TARGET_OPENRISC */
2771
2772#ifdef TARGET_SH4
2773void cpu_loop(CPUSH4State *env)
2774{
2775    CPUState *cs = CPU(sh_env_get_cpu(env));
2776    int trapnr, ret;
2777    target_siginfo_t info;
2778
2779    while (1) {
2780        cpu_exec_start(cs);
2781        trapnr = cpu_sh4_exec(cs);
2782        cpu_exec_end(cs);
2783
2784        switch (trapnr) {
2785        case 0x160:
2786            env->pc += 2;
2787            ret = do_syscall(env,
2788                             env->gregs[3],
2789                             env->gregs[4],
2790                             env->gregs[5],
2791                             env->gregs[6],
2792                             env->gregs[7],
2793                             env->gregs[0],
2794                             env->gregs[1],
2795                             0, 0);
2796            env->gregs[0] = ret;
2797            break;
2798        case EXCP_INTERRUPT:
2799            /* just indicate that signals should be handled asap */
2800            break;
2801        case EXCP_DEBUG:
2802            {
2803                int sig;
2804
2805                sig = gdb_handlesig(cs, TARGET_SIGTRAP);
2806                if (sig)
2807                  {
2808                    info.si_signo = sig;
2809                    info.si_errno = 0;
2810                    info.si_code = TARGET_TRAP_BRKPT;
2811                    queue_signal(env, info.si_signo, &info);
2812                  }
2813            }
2814            break;
2815        case 0xa0:
2816        case 0xc0:
2817            info.si_signo = TARGET_SIGSEGV;
2818            info.si_errno = 0;
2819            info.si_code = TARGET_SEGV_MAPERR;
2820            info._sifields._sigfault._addr = env->tea;
2821            queue_signal(env, info.si_signo, &info);
2822            break;
2823
2824        default:
2825            printf ("Unhandled trap: 0x%x\n", trapnr);
2826            cpu_dump_state(cs, stderr, fprintf, 0);
2827            exit(EXIT_FAILURE);
2828        }
2829        process_pending_signals (env);
2830    }
2831}
2832#endif
2833
2834#ifdef TARGET_CRIS
2835void cpu_loop(CPUCRISState *env)
2836{
2837    CPUState *cs = CPU(cris_env_get_cpu(env));
2838    int trapnr, ret;
2839    target_siginfo_t info;
2840    
2841    while (1) {
2842        cpu_exec_start(cs);
2843        trapnr = cpu_cris_exec(cs);
2844        cpu_exec_end(cs);
2845        switch (trapnr) {
2846        case 0xaa:
2847            {
2848                info.si_signo = TARGET_SIGSEGV;
2849                info.si_errno = 0;
2850                /* XXX: check env->error_code */
2851                info.si_code = TARGET_SEGV_MAPERR;
2852                info._sifields._sigfault._addr = env->pregs[PR_EDA];
2853                queue_signal(env, info.si_signo, &info);
2854            }
2855            break;
2856        case EXCP_INTERRUPT:
2857          /* just indicate that signals should be handled asap */
2858          break;
2859        case EXCP_BREAK:
2860            ret = do_syscall(env, 
2861                             env->regs[9], 
2862                             env->regs[10], 
2863                             env->regs[11], 
2864                             env->regs[12], 
2865                             env->regs[13], 
2866                             env->pregs[7], 
2867                             env->pregs[11],
2868                             0, 0);
2869            env->regs[10] = ret;
2870            break;
2871        case EXCP_DEBUG:
2872            {
2873                int sig;
2874
2875                sig = gdb_handlesig(cs, TARGET_SIGTRAP);
2876                if (sig)
2877                  {
2878                    info.si_signo = sig;
2879                    info.si_errno = 0;
2880                    info.si_code = TARGET_TRAP_BRKPT;
2881                    queue_signal(env, info.si_signo, &info);
2882                  }
2883            }
2884            break;
2885        default:
2886            printf ("Unhandled trap: 0x%x\n", trapnr);
2887            cpu_dump_state(cs, stderr, fprintf, 0);
2888            exit(EXIT_FAILURE);
2889        }
2890        process_pending_signals (env);
2891    }
2892}
2893#endif
2894
2895#ifdef TARGET_MICROBLAZE
2896void cpu_loop(CPUMBState *env)
2897{
2898    CPUState *cs = CPU(mb_env_get_cpu(env));
2899    int trapnr, ret;
2900    target_siginfo_t info;
2901    
2902    while (1) {
2903        cpu_exec_start(cs);
2904        trapnr = cpu_mb_exec(cs);
2905        cpu_exec_end(cs);
2906        switch (trapnr) {
2907        case 0xaa:
2908            {
2909                info.si_signo = TARGET_SIGSEGV;
2910                info.si_errno = 0;
2911                /* XXX: check env->error_code */
2912                info.si_code = TARGET_SEGV_MAPERR;
2913                info._sifields._sigfault._addr = 0;
2914                queue_signal(env, info.si_signo, &info);
2915            }
2916            break;
2917        case EXCP_INTERRUPT:
2918          /* just indicate that signals should be handled asap */
2919          break;
2920        case EXCP_BREAK:
2921            /* Return address is 4 bytes after the call.  */
2922            env->regs[14] += 4;
2923            env->sregs[SR_PC] = env->regs[14];
2924            ret = do_syscall(env, 
2925                             env->regs[12], 
2926                             env->regs[5], 
2927                             env->regs[6], 
2928                             env->regs[7], 
2929                             env->regs[8], 
2930                             env->regs[9], 
2931                             env->regs[10],
2932                             0, 0);
2933            env->regs[3] = ret;
2934            break;
2935        case EXCP_HW_EXCP:
2936            env->regs[17] = env->sregs[SR_PC] + 4;
2937            if (env->iflags & D_FLAG) {
2938                env->sregs[SR_ESR] |= 1 << 12;
2939                env->sregs[SR_PC] -= 4;
2940                /* FIXME: if branch was immed, replay the imm as well.  */
2941            }
2942
2943            env->iflags &= ~(IMM_FLAG | D_FLAG);
2944
2945            switch (env->sregs[SR_ESR] & 31) {
2946                case ESR_EC_DIVZERO:
2947                    info.si_signo = TARGET_SIGFPE;
2948                    info.si_errno = 0;
2949                    info.si_code = TARGET_FPE_FLTDIV;
2950                    info._sifields._sigfault._addr = 0;
2951                    queue_signal(env, info.si_signo, &info);
2952                    break;
2953                case ESR_EC_FPU:
2954                    info.si_signo = TARGET_SIGFPE;
2955                    info.si_errno = 0;
2956                    if (env->sregs[SR_FSR] & FSR_IO) {
2957                        info.si_code = TARGET_FPE_FLTINV;
2958                    }
2959                    if (env->sregs[SR_FSR] & FSR_DZ) {
2960                        info.si_code = TARGET_FPE_FLTDIV;
2961                    }
2962                    info._sifields._sigfault._addr = 0;
2963                    queue_signal(env, info.si_signo, &info);
2964                    break;
2965                default:
2966                    printf ("Unhandled hw-exception: 0x%x\n",
2967                            env->sregs[SR_ESR] & ESR_EC_MASK);
2968                    cpu_dump_state(cs, stderr, fprintf, 0);
2969                    exit(EXIT_FAILURE);
2970                    break;
2971            }
2972            break;
2973        case EXCP_DEBUG:
2974            {
2975                int sig;
2976
2977                sig = gdb_handlesig(cs, TARGET_SIGTRAP);
2978                if (sig)
2979                  {
2980                    info.si_signo = sig;
2981                    info.si_errno = 0;
2982                    info.si_code = TARGET_TRAP_BRKPT;
2983                    queue_signal(env, info.si_signo, &info);
2984                  }
2985            }
2986            break;
2987        default:
2988            printf ("Unhandled trap: 0x%x\n", trapnr);
2989            cpu_dump_state(cs, stderr, fprintf, 0);
2990            exit(EXIT_FAILURE);
2991        }
2992        process_pending_signals (env);
2993    }
2994}
2995#endif
2996
2997#ifdef TARGET_M68K
2998
2999void cpu_loop(CPUM68KState *env)
3000{
3001    CPUState *cs = CPU(m68k_env_get_cpu(env));
3002    int trapnr;
3003    unsigned int n;
3004    target_siginfo_t info;
3005    TaskState *ts = cs->opaque;
3006
3007    for(;;) {
3008        cpu_exec_start(cs);
3009        trapnr = cpu_m68k_exec(cs);
3010        cpu_exec_end(cs);
3011        switch(trapnr) {
3012        case EXCP_ILLEGAL:
3013            {
3014                if (ts->sim_syscalls) {
3015                    uint16_t nr;
3016                    get_user_u16(nr, env->pc + 2);
3017                    env->pc += 4;
3018                    do_m68k_simcall(env, nr);
3019                } else {
3020                    goto do_sigill;
3021                }
3022            }
3023            break;
3024        case EXCP_HALT_INSN:
3025            /* Semihosing syscall.  */
3026            env->pc += 4;
3027            do_m68k_semihosting(env, env->dregs[0]);
3028            break;
3029        case EXCP_LINEA:
3030        case EXCP_LINEF:
3031        case EXCP_UNSUPPORTED:
3032        do_sigill:
3033            info.si_signo = TARGET_SIGILL;
3034            info.si_errno = 0;
3035            info.si_code = TARGET_ILL_ILLOPN;
3036            info._sifields._sigfault._addr = env->pc;
3037            queue_signal(env, info.si_signo, &info);
3038            break;
3039        case EXCP_TRAP0:
3040            {
3041                ts->sim_syscalls = 0;
3042                n = env->dregs[0];
3043                env->pc += 2;
3044                env->dregs[0] = do_syscall(env,
3045                                          n,
3046                                          env->dregs[1],
3047                                          env->dregs[2],
3048                                          env->dregs[3],
3049                                          env->dregs[4],
3050                                          env->dregs[5],
3051                                          env->aregs[0],
3052                                          0, 0);
3053            }
3054            break;
3055        case EXCP_INTERRUPT:
3056            /* just indicate that signals should be handled asap */
3057            break;
3058        case EXCP_ACCESS:
3059            {
3060                info.si_signo = TARGET_SIGSEGV;
3061                info.si_errno = 0;
3062                /* XXX: check env->error_code */
3063                info.si_code = TARGET_SEGV_MAPERR;
3064                info._sifields._sigfault._addr = env->mmu.ar;
3065                queue_signal(env, info.si_signo, &info);
3066            }
3067            break;
3068        case EXCP_DEBUG:
3069            {
3070                int sig;
3071
3072                sig = gdb_handlesig(cs, TARGET_SIGTRAP);
3073                if (sig)
3074                  {
3075                    info.si_signo = sig;
3076                    info.si_errno = 0;
3077                    info.si_code = TARGET_TRAP_BRKPT;
3078                    queue_signal(env, info.si_signo, &info);
3079                  }
3080            }
3081            break;
3082        default:
3083            EXCP_DUMP(env, "qemu: unhandled CPU exception 0x%x - aborting\n", trapnr);
3084            abort();
3085        }
3086        process_pending_signals(env);
3087    }
3088}
3089#endif /* TARGET_M68K */
3090
3091#ifdef TARGET_ALPHA
3092static void do_store_exclusive(CPUAlphaState *env, int reg, int quad)
3093{
3094    target_ulong addr, val, tmp;
3095    target_siginfo_t info;
3096    int ret = 0;
3097
3098    addr = env->lock_addr;
3099    tmp = env->lock_st_addr;
3100    env->lock_addr = -1;
3101    env->lock_st_addr = 0;
3102
3103    start_exclusive();
3104    mmap_lock();
3105
3106    if (addr == tmp) {
3107        if (quad ? get_user_s64(val, addr) : get_user_s32(val, addr)) {
3108            goto do_sigsegv;
3109        }
3110
3111        if (val == env->lock_value) {
3112            tmp = env->ir[reg];
3113            if (quad ? put_user_u64(tmp, addr) : put_user_u32(tmp, addr)) {
3114                goto do_sigsegv;
3115            }
3116            ret = 1;
3117        }
3118    }
3119    env->ir[reg] = ret;
3120    env->pc += 4;
3121
3122    mmap_unlock();
3123    end_exclusive();
3124    return;
3125
3126 do_sigsegv:
3127    mmap_unlock();
3128    end_exclusive();
3129
3130    info.si_signo = TARGET_SIGSEGV;
3131    info.si_errno = 0;
3132    info.si_code = TARGET_SEGV_MAPERR;
3133    info._sifields._sigfault._addr = addr;
3134    queue_signal(env, TARGET_SIGSEGV, &info);
3135}
3136
3137void cpu_loop(CPUAlphaState *env)
3138{
3139    CPUState *cs = CPU(alpha_env_get_cpu(env));
3140    int trapnr;
3141    target_siginfo_t info;
3142    abi_long sysret;
3143
3144    while (1) {
3145        cpu_exec_start(cs);
3146        trapnr = cpu_alpha_exec(cs);
3147        cpu_exec_end(cs);
3148
3149        /* All of the traps imply a transition through PALcode, which
3150           implies an REI instruction has been executed.  Which means
3151           that the intr_flag should be cleared.  */
3152        env->intr_flag = 0;
3153
3154        switch (trapnr) {
3155        case EXCP_RESET:
3156            fprintf(stderr, "Reset requested. Exit\n");
3157            exit(EXIT_FAILURE);
3158            break;
3159        case EXCP_MCHK:
3160            fprintf(stderr, "Machine check exception. Exit\n");
3161            exit(EXIT_FAILURE);
3162            break;
3163        case EXCP_SMP_INTERRUPT:
3164        case EXCP_CLK_INTERRUPT:
3165        case EXCP_DEV_INTERRUPT:
3166            fprintf(stderr, "External interrupt. Exit\n");
3167            exit(EXIT_FAILURE);
3168            break;
3169        case EXCP_MMFAULT:
3170            env->lock_addr = -1;
3171            info.si_signo = TARGET_SIGSEGV;
3172            info.si_errno = 0;
3173            info.si_code = (page_get_flags(env->trap_arg0) & PAGE_VALID
3174                            ? TARGET_SEGV_ACCERR : TARGET_SEGV_MAPERR);
3175            info._sifields._sigfault._addr = env->trap_arg0;
3176            queue_signal(env, info.si_signo, &info);
3177            break;
3178        case EXCP_UNALIGN:
3179            env->lock_addr = -1;
3180            info.si_signo = TARGET_SIGBUS;
3181            info.si_errno = 0;
3182            info.si_code = TARGET_BUS_ADRALN;
3183            info._sifields._sigfault._addr = env->trap_arg0;
3184            queue_signal(env, info.si_signo, &info);
3185            break;
3186        case EXCP_OPCDEC:
3187        do_sigill:
3188            env->lock_addr = -1;
3189            info.si_signo = TARGET_SIGILL;
3190            info.si_errno = 0;
3191            info.si_code = TARGET_ILL_ILLOPC;
3192            info._sifields._sigfault._addr = env->pc;
3193            queue_signal(env, info.si_signo, &info);
3194            break;
3195        case EXCP_ARITH:
3196            env->lock_addr = -1;
3197            info.si_signo = TARGET_SIGFPE;
3198            info.si_errno = 0;
3199            info.si_code = TARGET_FPE_FLTINV;
3200            info._sifields._sigfault._addr = env->pc;
3201            queue_signal(env, info.si_signo, &info);
3202            break;
3203        case EXCP_FEN:
3204            /* No-op.  Linux simply re-enables the FPU.  */
3205            break;
3206        case EXCP_CALL_PAL:
3207            env->lock_addr = -1;
3208            switch (env->error_code) {
3209            case 0x80:
3210                /* BPT */
3211                info.si_signo = TARGET_SIGTRAP;
3212                info.si_errno = 0;
3213                info.si_code = TARGET_TRAP_BRKPT;
3214                info._sifields._sigfault._addr = env->pc;
3215                queue_signal(env, info.si_signo, &info);
3216                break;
3217            case 0x81:
3218                /* BUGCHK */
3219                info.si_signo = TARGET_SIGTRAP;
3220                info.si_errno = 0;
3221                info.si_code = 0;
3222                info._sifields._sigfault._addr = env->pc;
3223                queue_signal(env, info.si_signo, &info);
3224                break;
3225            case 0x83:
3226                /* CALLSYS */
3227                trapnr = env->ir[IR_V0];
3228                sysret = do_syscall(env, trapnr,
3229                                    env->ir[IR_A0], env->ir[IR_A1],
3230                                    env->ir[IR_A2], env->ir[IR_A3],
3231                                    env->ir[IR_A4], env->ir[IR_A5],
3232                                    0, 0);
3233                if (trapnr == TARGET_NR_sigreturn
3234                    || trapnr == TARGET_NR_rt_sigreturn) {
3235                    break;
3236                }
3237                /* Syscall writes 0 to V0 to bypass error check, similar
3238                   to how this is handled internal to Linux kernel.
3239                   (Ab)use trapnr temporarily as boolean indicating error.  */
3240                trapnr = (env->ir[IR_V0] != 0 && sysret < 0);
3241                env->ir[IR_V0] = (trapnr ? -sysret : sysret);
3242                env->ir[IR_A3] = trapnr;
3243                break;
3244            case 0x86:
3245                /* IMB */
3246                /* ??? We can probably elide the code using page_unprotect
3247                   that is checking for self-modifying code.  Instead we
3248                   could simply call tb_flush here.  Until we work out the
3249                   changes required to turn off the extra write protection,
3250                   this can be a no-op.  */
3251                break;
3252            case 0x9E:
3253                /* RDUNIQUE */
3254                /* Handled in the translator for usermode.  */
3255                abort();
3256            case 0x9F:
3257                /* WRUNIQUE */
3258                /* Handled in the translator for usermode.  */
3259                abort();
3260            case 0xAA:
3261                /* GENTRAP */
3262                info.si_signo = TARGET_SIGFPE;
3263                switch (env->ir[IR_A0]) {
3264                case TARGET_GEN_INTOVF:
3265                    info.si_code = TARGET_FPE_INTOVF;
3266                    break;
3267                case TARGET_GEN_INTDIV:
3268                    info.si_code = TARGET_FPE_INTDIV;
3269                    break;
3270                case TARGET_GEN_FLTOVF:
3271                    info.si_code = TARGET_FPE_FLTOVF;
3272                    break;
3273                case TARGET_GEN_FLTUND:
3274                    info.si_code = TARGET_FPE_FLTUND;
3275                    break;
3276                case TARGET_GEN_FLTINV:
3277                    info.si_code = TARGET_FPE_FLTINV;
3278                    break;
3279                case TARGET_GEN_FLTINE:
3280                    info.si_code = TARGET_FPE_FLTRES;
3281                    break;
3282                case TARGET_GEN_ROPRAND:
3283                    info.si_code = 0;
3284                    break;
3285                default:
3286                    info.si_signo = TARGET_SIGTRAP;
3287                    info.si_code = 0;
3288                    break;
3289                }
3290                info.si_errno = 0;
3291                info._sifields._sigfault._addr = env->pc;
3292                queue_signal(env, info.si_signo, &info);
3293                break;
3294            default:
3295                goto do_sigill;
3296            }
3297            break;
3298        case EXCP_DEBUG:
3299            info.si_signo = gdb_handlesig(cs, TARGET_SIGTRAP);
3300            if (info.si_signo) {
3301                env->lock_addr = -1;
3302                info.si_errno = 0;
3303                info.si_code = TARGET_TRAP_BRKPT;
3304                queue_signal(env, info.si_signo, &info);
3305            }
3306            break;
3307        case EXCP_STL_C:
3308        case EXCP_STQ_C:
3309            do_store_exclusive(env, env->error_code, trapnr - EXCP_STL_C);
3310            break;
3311        case EXCP_INTERRUPT:
3312            /* Just indicate that signals should be handled asap.  */
3313            break;
3314        default:
3315            printf ("Unhandled trap: 0x%x\n", trapnr);
3316            cpu_dump_state(cs, stderr, fprintf, 0);
3317            exit(EXIT_FAILURE);
3318        }
3319        process_pending_signals (env);
3320    }
3321}
3322#endif /* TARGET_ALPHA */
3323
3324#ifdef TARGET_S390X
3325void cpu_loop(CPUS390XState *env)
3326{
3327    CPUState *cs = CPU(s390_env_get_cpu(env));
3328    int trapnr, n, sig;
3329    target_siginfo_t info;
3330    target_ulong addr;
3331
3332    while (1) {
3333        cpu_exec_start(cs);
3334        trapnr = cpu_s390x_exec(cs);
3335        cpu_exec_end(cs);
3336        switch (trapnr) {
3337        case EXCP_INTERRUPT:
3338            /* Just indicate that signals should be handled asap.  */
3339            break;
3340
3341        case EXCP_SVC:
3342            n = env->int_svc_code;
3343            if (!n) {
3344                /* syscalls > 255 */
3345                n = env->regs[1];
3346            }
3347            env->psw.addr += env->int_svc_ilen;
3348            env->regs[2] = do_syscall(env, n, env->regs[2], env->regs[3],
3349                                      env->regs[4], env->regs[5],
3350                                      env->regs[6], env->regs[7], 0, 0);
3351            break;
3352
3353        case EXCP_DEBUG:
3354            sig = gdb_handlesig(cs, TARGET_SIGTRAP);
3355            if (sig) {
3356                n = TARGET_TRAP_BRKPT;
3357                goto do_signal_pc;
3358            }
3359            break;
3360        case EXCP_PGM:
3361            n = env->int_pgm_code;
3362            switch (n) {
3363            case PGM_OPERATION:
3364            case PGM_PRIVILEGED:
3365                sig = TARGET_SIGILL;
3366                n = TARGET_ILL_ILLOPC;
3367                goto do_signal_pc;
3368            case PGM_PROTECTION:
3369            case PGM_ADDRESSING:
3370                sig = TARGET_SIGSEGV;
3371                /* XXX: check env->error_code */
3372                n = TARGET_SEGV_MAPERR;
3373                addr = env->__excp_addr;
3374                goto do_signal;
3375            case PGM_EXECUTE:
3376            case PGM_SPECIFICATION:
3377            case PGM_SPECIAL_OP:
3378            case PGM_OPERAND:
3379            do_sigill_opn:
3380                sig = TARGET_SIGILL;
3381                n = TARGET_ILL_ILLOPN;
3382                goto do_signal_pc;
3383
3384            case PGM_FIXPT_OVERFLOW:
3385                sig = TARGET_SIGFPE;
3386                n = TARGET_FPE_INTOVF;
3387                goto do_signal_pc;
3388            case PGM_FIXPT_DIVIDE:
3389                sig = TARGET_SIGFPE;
3390                n = TARGET_FPE_INTDIV;
3391                goto do_signal_pc;
3392
3393            case PGM_DATA:
3394                n = (env->fpc >> 8) & 0xff;
3395                if (n == 0xff) {
3396                    /* compare-and-trap */
3397                    goto do_sigill_opn;
3398                } else {
3399                    /* An IEEE exception, simulated or otherwise.  */
3400                    if (n & 0x80) {
3401                        n = TARGET_FPE_FLTINV;
3402                    } else if (n & 0x40) {
3403                        n = TARGET_FPE_FLTDIV;
3404                    } else if (n & 0x20) {
3405                        n = TARGET_FPE_FLTOVF;
3406                    } else if (n & 0x10) {
3407                        n = TARGET_FPE_FLTUND;
3408                    } else if (n & 0x08) {
3409                        n = TARGET_FPE_FLTRES;
3410                    } else {
3411                        /* ??? Quantum exception; BFP, DFP error.  */
3412                        goto do_sigill_opn;
3413                    }
3414                    sig = TARGET_SIGFPE;
3415                    goto do_signal_pc;
3416                }
3417
3418            default:
3419                fprintf(stderr, "Unhandled program exception: %#x\n", n);
3420                cpu_dump_state(cs, stderr, fprintf, 0);
3421                exit(EXIT_FAILURE);
3422            }
3423            break;
3424
3425        do_signal_pc:
3426            addr = env->psw.addr;
3427        do_signal:
3428            info.si_signo = sig;
3429            info.si_errno = 0;
3430            info.si_code = n;
3431            info._sifields._sigfault._addr = addr;
3432            queue_signal(env, info.si_signo, &info);
3433            break;
3434
3435        default:
3436            fprintf(stderr, "Unhandled trap: 0x%x\n", trapnr);
3437            cpu_dump_state(cs, stderr, fprintf, 0);
3438            exit(EXIT_FAILURE);
3439        }
3440        process_pending_signals (env);
3441    }
3442}
3443
3444#endif /* TARGET_S390X */
3445
3446#ifdef TARGET_TILEGX
3447
3448static void gen_sigill_reg(CPUTLGState *env)
3449{
3450    target_siginfo_t info;
3451
3452    info.si_signo = TARGET_SIGILL;
3453    info.si_errno = 0;
3454    info.si_code = TARGET_ILL_PRVREG;
3455    info._sifields._sigfault._addr = env->pc;
3456    queue_signal(env, info.si_signo, &info);
3457}
3458
3459static void do_signal(CPUTLGState *env, int signo, int sigcode)
3460{
3461    target_siginfo_t info;
3462
3463    info.si_signo = signo;
3464    info.si_errno = 0;
3465    info._sifields._sigfault._addr = env->pc;
3466
3467    if (signo == TARGET_SIGSEGV) {
3468        /* The passed in sigcode is a dummy; check for a page mapping
3469           and pass either MAPERR or ACCERR.  */
3470        target_ulong addr = env->excaddr;
3471        info._sifields._sigfault._addr = addr;
3472        if (page_check_range(addr, 1, PAGE_VALID) < 0) {
3473            sigcode = TARGET_SEGV_MAPERR;
3474        } else {
3475            sigcode = TARGET_SEGV_ACCERR;
3476        }
3477    }
3478    info.si_code = sigcode;
3479
3480    queue_signal(env, info.si_signo, &info);
3481}
3482
3483static void gen_sigsegv_maperr(CPUTLGState *env, target_ulong addr)
3484{
3485    env->excaddr = addr;
3486    do_signal(env, TARGET_SIGSEGV, 0);
3487}
3488
3489static void set_regval(CPUTLGState *env, uint8_t reg, uint64_t val)
3490{
3491    if (unlikely(reg >= TILEGX_R_COUNT)) {
3492        switch (reg) {
3493        case TILEGX_R_SN:
3494        case TILEGX_R_ZERO:
3495            return;
3496        case TILEGX_R_IDN0:
3497        case TILEGX_R_IDN1:
3498        case TILEGX_R_UDN0:
3499        case TILEGX_R_UDN1:
3500        case TILEGX_R_UDN2:
3501        case TILEGX_R_UDN3:
3502            gen_sigill_reg(env);
3503            return;
3504        default:
3505            g_assert_not_reached();
3506        }
3507    }
3508    env->regs[reg] = val;
3509}
3510
3511/*
3512 * Compare the 8-byte contents of the CmpValue SPR with the 8-byte value in
3513 * memory at the address held in the first source register. If the values are
3514 * not equal, then no memory operation is performed. If the values are equal,
3515 * the 8-byte quantity from the second source register is written into memory
3516 * at the address held in the first source register. In either case, the result
3517 * of the instruction is the value read from memory. The compare and write to
3518 * memory are atomic and thus can be used for synchronization purposes. This
3519 * instruction only operates for addresses aligned to a 8-byte boundary.
3520 * Unaligned memory access causes an Unaligned Data Reference interrupt.
3521 *
3522 * Functional Description (64-bit)
3523 *       uint64_t memVal = memoryReadDoubleWord (rf[SrcA]);
3524 *       rf[Dest] = memVal;
3525 *       if (memVal == SPR[CmpValueSPR])
3526 *           memoryWriteDoubleWord (rf[SrcA], rf[SrcB]);
3527 *
3528 * Functional Description (32-bit)
3529 *       uint64_t memVal = signExtend32 (memoryReadWord (rf[SrcA]));
3530 *       rf[Dest] = memVal;
3531 *       if (memVal == signExtend32 (SPR[CmpValueSPR]))
3532 *           memoryWriteWord (rf[SrcA], rf[SrcB]);
3533 *
3534 *
3535 * This function also processes exch and exch4 which need not process SPR.
3536 */
3537static void do_exch(CPUTLGState *env, bool quad, bool cmp)
3538{
3539    target_ulong addr;
3540    target_long val, sprval;
3541
3542    start_exclusive();
3543
3544    addr = env->atomic_srca;
3545    if (quad ? get_user_s64(val, addr) : get_user_s32(val, addr)) {
3546        goto sigsegv_maperr;
3547    }
3548
3549    if (cmp) {
3550        if (quad) {
3551            sprval = env->spregs[TILEGX_SPR_CMPEXCH];
3552        } else {
3553            sprval = sextract64(env->spregs[TILEGX_SPR_CMPEXCH], 0, 32);
3554        }
3555    }
3556
3557    if (!cmp || val == sprval) {
3558        target_long valb = env->atomic_srcb;
3559        if (quad ? put_user_u64(valb, addr) : put_user_u32(valb, addr)) {
3560            goto sigsegv_maperr;
3561        }
3562    }
3563
3564    set_regval(env, env->atomic_dstr, val);
3565    end_exclusive();
3566    return;
3567
3568 sigsegv_maperr:
3569    end_exclusive();
3570    gen_sigsegv_maperr(env, addr);
3571}
3572
3573static void do_fetch(CPUTLGState *env, int trapnr, bool quad)
3574{
3575    int8_t write = 1;
3576    target_ulong addr;
3577    target_long val, valb;
3578
3579    start_exclusive();
3580
3581    addr = env->atomic_srca;
3582    valb = env->atomic_srcb;
3583    if (quad ? get_user_s64(val, addr) : get_user_s32(val, addr)) {
3584        goto sigsegv_maperr;
3585    }
3586
3587    switch (trapnr) {
3588    case TILEGX_EXCP_OPCODE_FETCHADD:
3589    case TILEGX_EXCP_OPCODE_FETCHADD4:
3590        valb += val;
3591        break;
3592    case TILEGX_EXCP_OPCODE_FETCHADDGEZ:
3593        valb += val;
3594        if (valb < 0) {
3595            write = 0;
3596        }
3597        break;
3598    case TILEGX_EXCP_OPCODE_FETCHADDGEZ4:
3599        valb += val;
3600        if ((int32_t)valb < 0) {
3601            write = 0;
3602        }
3603        break;
3604    case TILEGX_EXCP_OPCODE_FETCHAND:
3605    case TILEGX_EXCP_OPCODE_FETCHAND4:
3606        valb &= val;
3607        break;
3608    case TILEGX_EXCP_OPCODE_FETCHOR:
3609    case TILEGX_EXCP_OPCODE_FETCHOR4:
3610        valb |= val;
3611        break;
3612    default:
3613        g_assert_not_reached();
3614    }
3615
3616    if (write) {
3617        if (quad ? put_user_u64(valb, addr) : put_user_u32(valb, addr)) {
3618            goto sigsegv_maperr;
3619        }
3620    }
3621
3622    set_regval(env, env->atomic_dstr, val);
3623    end_exclusive();
3624    return;
3625
3626 sigsegv_maperr:
3627    end_exclusive();
3628    gen_sigsegv_maperr(env, addr);
3629}
3630
3631void cpu_loop(CPUTLGState *env)
3632{
3633    CPUState *cs = CPU(tilegx_env_get_cpu(env));
3634    int trapnr;
3635
3636    while (1) {
3637        cpu_exec_start(cs);
3638        trapnr = cpu_tilegx_exec(cs);
3639        cpu_exec_end(cs);
3640        switch (trapnr) {
3641        case TILEGX_EXCP_SYSCALL:
3642            env->regs[TILEGX_R_RE] = do_syscall(env, env->regs[TILEGX_R_NR],
3643                                                env->regs[0], env->regs[1],
3644                                                env->regs[2], env->regs[3],
3645                                                env->regs[4], env->regs[5],
3646                                                env->regs[6], env->regs[7]);
3647            env->regs[TILEGX_R_ERR] = TILEGX_IS_ERRNO(env->regs[TILEGX_R_RE])
3648                                                      ? - env->regs[TILEGX_R_RE]
3649                                                      : 0;
3650            break;
3651        case TILEGX_EXCP_OPCODE_EXCH:
3652            do_exch(env, true, false);
3653            break;
3654        case TILEGX_EXCP_OPCODE_EXCH4:
3655            do_exch(env, false, false);
3656            break;
3657        case TILEGX_EXCP_OPCODE_CMPEXCH:
3658            do_exch(env, true, true);
3659            break;
3660        case TILEGX_EXCP_OPCODE_CMPEXCH4:
3661            do_exch(env, false, true);
3662            break;
3663        case TILEGX_EXCP_OPCODE_FETCHADD:
3664        case TILEGX_EXCP_OPCODE_FETCHADDGEZ:
3665        case TILEGX_EXCP_OPCODE_FETCHAND:
3666        case TILEGX_EXCP_OPCODE_FETCHOR:
3667            do_fetch(env, trapnr, true);
3668            break;
3669        case TILEGX_EXCP_OPCODE_FETCHADD4:
3670        case TILEGX_EXCP_OPCODE_FETCHADDGEZ4:
3671        case TILEGX_EXCP_OPCODE_FETCHAND4:
3672        case TILEGX_EXCP_OPCODE_FETCHOR4:
3673            do_fetch(env, trapnr, false);
3674            break;
3675        case TILEGX_EXCP_SIGNAL:
3676            do_signal(env, env->signo, env->sigcode);
3677            break;
3678        case TILEGX_EXCP_REG_IDN_ACCESS:
3679        case TILEGX_EXCP_REG_UDN_ACCESS:
3680            gen_sigill_reg(env);
3681            break;
3682        default:
3683            fprintf(stderr, "trapnr is %d[0x%x].\n", trapnr, trapnr);
3684            g_assert_not_reached();
3685        }
3686        process_pending_signals(env);
3687    }
3688}
3689
3690#endif
3691
3692THREAD CPUState *thread_cpu;
3693
3694void task_settid(TaskState *ts)
3695{
3696    if (ts->ts_tid == 0) {
3697        ts->ts_tid = (pid_t)syscall(SYS_gettid);
3698    }
3699}
3700
3701void stop_all_tasks(void)
3702{
3703    /*
3704     * We trust that when using NPTL, start_exclusive()
3705     * handles thread stopping correctly.
3706     */
3707    start_exclusive();
3708}
3709
3710/* Assumes contents are already zeroed.  */
3711void init_task_state(TaskState *ts)
3712{
3713    int i;
3714 
3715    ts->used = 1;
3716    ts->first_free = ts->sigqueue_table;
3717    for (i = 0; i < MAX_SIGQUEUE_SIZE - 1; i++) {
3718        ts->sigqueue_table[i].next = &ts->sigqueue_table[i + 1];
3719    }
3720    ts->sigqueue_table[i].next = NULL;
3721}
3722
3723CPUArchState *cpu_copy(CPUArchState *env)
3724{
3725    CPUState *cpu = ENV_GET_CPU(env);
3726    CPUState *new_cpu = cpu_init(cpu_model);
3727    CPUArchState *new_env = new_cpu->env_ptr;
3728    CPUBreakpoint *bp;
3729    CPUWatchpoint *wp;
3730
3731    /* Reset non arch specific state */
3732    cpu_reset(new_cpu);
3733
3734    memcpy(new_env, env, sizeof(CPUArchState));
3735
3736    /* Clone all break/watchpoints.
3737       Note: Once we support ptrace with hw-debug register access, make sure
3738       BP_CPU break/watchpoints are handled correctly on clone. */
3739    QTAILQ_INIT(&new_cpu->breakpoints);
3740    QTAILQ_INIT(&new_cpu->watchpoints);
3741    QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
3742        cpu_breakpoint_insert(new_cpu, bp->pc, bp->flags, NULL);
3743    }
3744    QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
3745        cpu_watchpoint_insert(new_cpu, wp->vaddr, wp->len, wp->flags, NULL);
3746    }
3747
3748    return new_env;
3749}
3750
3751static void handle_arg_help(const char *arg)
3752{
3753    usage(EXIT_SUCCESS);
3754}
3755
3756static void handle_arg_log(const char *arg)
3757{
3758    int mask;
3759
3760    mask = qemu_str_to_log_mask(arg);
3761    if (!mask) {
3762        qemu_print_log_usage(stdout);
3763        exit(EXIT_FAILURE);
3764    }
3765    qemu_set_log(mask);
3766}
3767
3768static void handle_arg_log_filename(const char *arg)
3769{
3770    qemu_set_log_filename(arg);
3771}
3772
3773static void handle_arg_set_env(const char *arg)
3774{
3775    char *r, *p, *token;
3776    r = p = strdup(arg);
3777    while ((token = strsep(&p, ",")) != NULL) {
3778        if (envlist_setenv(envlist, token) != 0) {
3779            usage(EXIT_FAILURE);
3780        }
3781    }
3782    free(r);
3783}
3784
3785static void handle_arg_unset_env(const char *arg)
3786{
3787    char *r, *p, *token;
3788    r = p = strdup(arg);
3789    while ((token = strsep(&p, ",")) != NULL) {
3790        if (envlist_unsetenv(envlist, token) != 0) {
3791            usage(EXIT_FAILURE);
3792        }
3793    }
3794    free(r);
3795}
3796
3797static void handle_arg_argv0(const char *arg)
3798{
3799    argv0 = strdup(arg);
3800}
3801
3802static void handle_arg_stack_size(const char *arg)
3803{
3804    char *p;
3805    guest_stack_size = strtoul(arg, &p, 0);
3806    if (guest_stack_size == 0) {
3807        usage(EXIT_FAILURE);
3808    }
3809
3810    if (*p == 'M') {
3811        guest_stack_size *= 1024 * 1024;
3812    } else if (*p == 'k' || *p == 'K') {
3813        guest_stack_size *= 1024;
3814    }
3815}
3816
3817static void handle_arg_ld_prefix(const char *arg)
3818{
3819    interp_prefix = strdup(arg);
3820}
3821
3822static void handle_arg_pagesize(const char *arg)
3823{
3824    qemu_host_page_size = atoi(arg);
3825    if (qemu_host_page_size == 0 ||
3826        (qemu_host_page_size & (qemu_host_page_size - 1)) != 0) {
3827        fprintf(stderr, "page size must be a power of two\n");
3828        exit(EXIT_FAILURE);
3829    }
3830}
3831
3832static void handle_arg_randseed(const char *arg)
3833{
3834    unsigned long long seed;
3835
3836    if (parse_uint_full(arg, &seed, 0) != 0 || seed > UINT_MAX) {
3837        fprintf(stderr, "Invalid seed number: %s\n", arg);
3838        exit(EXIT_FAILURE);
3839    }
3840    srand(seed);
3841}
3842
3843static void handle_arg_gdb(const char *arg)
3844{
3845    gdbstub_port = atoi(arg);
3846}
3847
3848static void handle_arg_uname(const char *arg)
3849{
3850    qemu_uname_release = strdup(arg);
3851}
3852
3853static void handle_arg_cpu(const char *arg)
3854{
3855    cpu_model = strdup(arg);
3856    if (cpu_model == NULL || is_help_option(cpu_model)) {
3857        /* XXX: implement xxx_cpu_list for targets that still miss it */
3858#if defined(cpu_list)
3859        cpu_list(stdout, &fprintf);
3860#endif
3861        exit(EXIT_FAILURE);
3862    }
3863}
3864
3865static void handle_arg_guest_base(const char *arg)
3866{
3867    guest_base = strtol(arg, NULL, 0);
3868    have_guest_base = 1;
3869}
3870
3871static void handle_arg_reserved_va(const char *arg)
3872{
3873    char *p;
3874    int shift = 0;
3875    reserved_va = strtoul(arg, &p, 0);
3876    switch (*p) {
3877    case 'k':
3878    case 'K':
3879        shift = 10;
3880        break;
3881    case 'M':
3882        shift = 20;
3883        break;
3884    case 'G':
3885        shift = 30;
3886        break;
3887    }
3888    if (shift) {
3889        unsigned long unshifted = reserved_va;
3890        p++;
3891        reserved_va <<= shift;
3892        if (((reserved_va >> shift) != unshifted)
3893#if HOST_LONG_BITS > TARGET_VIRT_ADDR_SPACE_BITS
3894            || (reserved_va > (1ul << TARGET_VIRT_ADDR_SPACE_BITS))
3895#endif
3896            ) {
3897            fprintf(stderr, "Reserved virtual address too big\n");
3898            exit(EXIT_FAILURE);
3899        }
3900    }
3901    if (*p) {
3902        fprintf(stderr, "Unrecognised -R size suffix '%s'\n", p);
3903        exit(EXIT_FAILURE);
3904    }
3905}
3906
3907static void handle_arg_no_tb_chain(const char *arg)
3908{
3909    tcg_tb_chain = false;
3910}
3911
3912static void handle_arg_singlestep(const char *arg)
3913{
3914    singlestep = 1;
3915}
3916
3917static void handle_arg_strace(const char *arg)
3918{
3919    do_strace = 1;
3920}
3921
3922static void handle_arg_version(const char *arg)
3923{
3924    printf("qemu-" TARGET_NAME " version " QEMU_VERSION QEMU_PKGVERSION
3925           ", Copyright (c) 2003-2008 Fabrice Bellard\n");
3926    exit(EXIT_SUCCESS);
3927}
3928
3929struct qemu_argument {
3930    const char *argv;
3931    const char *env;
3932    bool has_arg;
3933    void (*handle_opt)(const char *arg);
3934    const char *example;
3935    const char *help;
3936};
3937
3938static const struct qemu_argument arg_table[] = {
3939    {"h",          "",                 false, handle_arg_help,
3940     "",           "print this help"},
3941    {"help",       "",                 false, handle_arg_help,
3942     "",           ""},
3943    {"g",          "QEMU_GDB",         true,  handle_arg_gdb,
3944     "port",       "wait gdb connection to 'port'"},
3945    {"L",          "QEMU_LD_PREFIX",   true,  handle_arg_ld_prefix,
3946     "path",       "set the elf interpreter prefix to 'path'"},
3947    {"s",          "QEMU_STACK_SIZE",  true,  handle_arg_stack_size,
3948     "size",       "set the stack size to 'size' bytes"},
3949    {"cpu",        "QEMU_CPU",         true,  handle_arg_cpu,
3950     "model",      "select CPU (-cpu help for list)"},
3951    {"E",          "QEMU_SET_ENV",     true,  handle_arg_set_env,
3952     "var=value",  "sets targets environment variable (see below)"},
3953    {"U",          "QEMU_UNSET_ENV",   true,  handle_arg_unset_env,
3954     "var",        "unsets targets environment variable (see below)"},
3955    {"0",          "QEMU_ARGV0",       true,  handle_arg_argv0,
3956     "argv0",      "forces target process argv[0] to be 'argv0'"},
3957    {"r",          "QEMU_UNAME",       true,  handle_arg_uname,
3958     "uname",      "set qemu uname release string to 'uname'"},
3959    {"B",          "QEMU_GUEST_BASE",  true,  handle_arg_guest_base,
3960     "address",    "set guest_base address to 'address'"},
3961    {"R",          "QEMU_RESERVED_VA", true,  handle_arg_reserved_va,
3962     "size",       "reserve 'size' bytes for guest virtual address space"},
3963    {"d",          "QEMU_LOG",         true,  handle_arg_log,
3964     "item[,...]", "enable logging of specified items "
3965     "(use '-d help' for a list of items)"},
3966    {"D",          "QEMU_LOG_FILENAME", true, handle_arg_log_filename,
3967     "logfile",     "write logs to 'logfile' (default stderr)"},
3968    {"p",          "QEMU_PAGESIZE",    true,  handle_arg_pagesize,
3969     "pagesize",   "set the host page size to 'pagesize'"},
3970    {"no-tb-chain", "QEMU_NO_TB_CHAIN",  false, handle_arg_no_tb_chain,
3971     "",           "Disable TB chaining"},
3972    {"singlestep", "QEMU_SINGLESTEP",  false, handle_arg_singlestep,
3973     "",           "run in singlestep mode"},
3974    {"strace",     "QEMU_STRACE",      false, handle_arg_strace,
3975     "",           "log system calls"},
3976    {"seed",       "QEMU_RAND_SEED",   true,  handle_arg_randseed,
3977     "",           "Seed for pseudo-random number generator"},
3978    {"version",    "QEMU_VERSION",     false, handle_arg_version,
3979     "",           "display version information and exit"},
3980    {NULL, NULL, false, NULL, NULL, NULL}
3981};
3982
3983static void usage(int exitcode)
3984{
3985    const struct qemu_argument *arginfo;
3986    int maxarglen;
3987    int maxenvlen;
3988
3989    printf("usage: qemu-" TARGET_NAME " [options] program [arguments...]\n"
3990           "Linux CPU emulator (compiled for " TARGET_NAME " emulation)\n"
3991           "\n"
3992           "Options and associated environment variables:\n"
3993           "\n");
3994
3995    /* Calculate column widths. We must always have at least enough space
3996     * for the column header.
3997     */
3998    maxarglen = strlen("Argument");
3999    maxenvlen = strlen("Env-variable");
4000
4001    for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {
4002        int arglen = strlen(arginfo->argv);
4003        if (arginfo->has_arg) {
4004            arglen += strlen(arginfo->example) + 1;
4005        }
4006        if (strlen(arginfo->env) > maxenvlen) {
4007            maxenvlen = strlen(arginfo->env);
4008        }
4009        if (arglen > maxarglen) {
4010            maxarglen = arglen;
4011        }
4012    }
4013
4014    printf("%-*s %-*s Description\n", maxarglen+1, "Argument",
4015            maxenvlen, "Env-variable");
4016
4017    for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {
4018        if (arginfo->has_arg) {
4019            printf("-%s %-*s %-*s %s\n", arginfo->argv,
4020                   (int)(maxarglen - strlen(arginfo->argv) - 1),
4021                   arginfo->example, maxenvlen, arginfo->env, arginfo->help);
4022        } else {
4023            printf("-%-*s %-*s %s\n", maxarglen, arginfo->argv,
4024                    maxenvlen, arginfo->env,
4025                    arginfo->help);
4026        }
4027    }
4028
4029    printf("\n"
4030           "Defaults:\n"
4031           "QEMU_LD_PREFIX  = %s\n"
4032           "QEMU_STACK_SIZE = %ld byte\n",
4033           interp_prefix,
4034           guest_stack_size);
4035
4036    printf("\n"
4037           "You can use -E and -U options or the QEMU_SET_ENV and\n"
4038           "QEMU_UNSET_ENV environment variables to set and unset\n"
4039           "environment variables for the target process.\n"
4040           "It is possible to provide several variables by separating them\n"
4041           "by commas in getsubopt(3) style. Additionally it is possible to\n"
4042           "provide the -E and -U options multiple times.\n"
4043           "The following lines are equivalent:\n"
4044           "    -E var1=val2 -E var2=val2 -U LD_PRELOAD -U LD_DEBUG\n"
4045           "    -E var1=val2,var2=val2 -U LD_PRELOAD,LD_DEBUG\n"
4046           "    QEMU_SET_ENV=var1=val2,var2=val2 QEMU_UNSET_ENV=LD_PRELOAD,LD_DEBUG\n"
4047           "Note that if you provide several changes to a single variable\n"
4048           "the last change will stay in effect.\n");
4049
4050    exit(exitcode);
4051}
4052
4053static int parse_args(int argc, char **argv)
4054{
4055    const char *r;
4056    int optind;
4057    const struct qemu_argument *arginfo;
4058
4059    for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {
4060        if (arginfo->env == NULL) {
4061            continue;
4062        }
4063
4064        r = getenv(arginfo->env);
4065        if (r != NULL) {
4066            arginfo->handle_opt(r);
4067        }
4068    }
4069
4070    optind = 1;
4071    for (;;) {
4072        if (optind >= argc) {
4073            break;
4074        }
4075        r = argv[optind];
4076        if (r[0] != '-') {
4077            break;
4078        }
4079        optind++;
4080        r++;
4081        if (!strcmp(r, "-")) {
4082            break;
4083        }
4084        /* Treat --foo the same as -foo.  */
4085        if (r[0] == '-') {
4086            r++;
4087        }
4088
4089        for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {
4090            if (!strcmp(r, arginfo->argv)) {
4091                if (arginfo->has_arg) {
4092                    if (optind >= argc) {
4093                        (void) fprintf(stderr,
4094                            "qemu: missing argument for option '%s'\n", r);
4095                        exit(EXIT_FAILURE);
4096                    }
4097                    arginfo->handle_opt(argv[optind]);
4098                    optind++;
4099                } else {
4100                    arginfo->handle_opt(NULL);
4101                }
4102                break;
4103            }
4104        }
4105
4106        /* no option matched the current argv */
4107        if (arginfo->handle_opt == NULL) {
4108            (void) fprintf(stderr, "qemu: unknown option '%s'\n", r);
4109            exit(EXIT_FAILURE);
4110        }
4111    }
4112
4113    if (optind >= argc) {
4114        (void) fprintf(stderr, "qemu: no user program specified\n");
4115        exit(EXIT_FAILURE);
4116    }
4117
4118    filename = argv[optind];
4119    exec_path = argv[optind];
4120
4121    return optind;
4122}
4123
4124int main(int argc, char **argv, char **envp)
4125{
4126    struct target_pt_regs regs1, *regs = &regs1;
4127    struct image_info info1, *info = &info1;
4128    struct linux_binprm bprm;
4129    TaskState *ts;
4130    CPUArchState *env;
4131    CPUState *cpu;
4132    int optind;
4133    char **target_environ, **wrk;
4134    char **target_argv;
4135    int target_argc;
4136    int i;
4137    int ret;
4138    int execfd;
4139
4140    module_call_init(MODULE_INIT_QOM);
4141
4142    if ((envlist = envlist_create()) == NULL) {
4143        (void) fprintf(stderr, "Unable to allocate envlist\n");
4144        exit(EXIT_FAILURE);
4145    }
4146
4147    /* add current environment into the list */
4148    for (wrk = environ; *wrk != NULL; wrk++) {
4149        (void) envlist_setenv(envlist, *wrk);
4150    }
4151
4152    /* Read the stack limit from the kernel.  If it's "unlimited",
4153       then we can do little else besides use the default.  */
4154    {
4155        struct rlimit lim;
4156        if (getrlimit(RLIMIT_STACK, &lim) == 0
4157            && lim.rlim_cur != RLIM_INFINITY
4158            && lim.rlim_cur == (target_long)lim.rlim_cur) {
4159            guest_stack_size = lim.rlim_cur;
4160        }
4161    }
4162
4163    cpu_model = NULL;
4164
4165    srand(time(NULL));
4166
4167    optind = parse_args(argc, argv);
4168
4169    /* Zero out regs */
4170    memset(regs, 0, sizeof(struct target_pt_regs));
4171
4172    /* Zero out image_info */
4173    memset(info, 0, sizeof(struct image_info));
4174
4175    memset(&bprm, 0, sizeof (bprm));
4176
4177    /* Scan interp_prefix dir for replacement files. */
4178    init_paths(interp_prefix);
4179
4180    init_qemu_uname_release();
4181
4182    if (cpu_model == NULL) {
4183#if defined(TARGET_I386)
4184#ifdef TARGET_X86_64
4185        cpu_model = "qemu64";
4186#else
4187        cpu_model = "qemu32";
4188#endif
4189#elif defined(TARGET_ARM)
4190        cpu_model = "any";
4191#elif defined(TARGET_UNICORE32)
4192        cpu_model = "any";
4193#elif defined(TARGET_M68K)
4194        cpu_model = "any";
4195#elif defined(TARGET_SPARC)
4196#ifdef TARGET_SPARC64
4197        cpu_model = "TI UltraSparc II";
4198#else
4199        cpu_model = "Fujitsu MB86904";
4200#endif
4201#elif defined(TARGET_MIPS)
4202#if defined(TARGET_ABI_MIPSN32) || defined(TARGET_ABI_MIPSN64)
4203        cpu_model = "5KEf";
4204#else
4205        cpu_model = "24Kf";
4206#endif
4207#elif defined TARGET_OPENRISC
4208        cpu_model = "or1200";
4209#elif defined(TARGET_PPC)
4210# ifdef TARGET_PPC64
4211        cpu_model = "POWER8";
4212# else
4213        cpu_model = "750";
4214# endif
4215#elif defined TARGET_SH4
4216        cpu_model = TYPE_SH7785_CPU;
4217#else
4218        cpu_model = "any";
4219#endif
4220    }
4221    tcg_exec_init(0);
4222    /* NOTE: we need to init the CPU at this stage to get
4223       qemu_host_page_size */
4224    cpu = cpu_init(cpu_model);
4225    if (!cpu) {
4226        fprintf(stderr, "Unable to find CPU definition\n");
4227        exit(EXIT_FAILURE);
4228    }
4229    env = cpu->env_ptr;
4230    cpu_reset(cpu);
4231
4232    thread_cpu = cpu;
4233
4234    if (getenv("QEMU_STRACE")) {
4235        do_strace = 1;
4236    }
4237
4238    if (getenv("QEMU_RAND_SEED")) {
4239        handle_arg_randseed(getenv("QEMU_RAND_SEED"));
4240    }
4241
4242    target_environ = envlist_to_environ(envlist, NULL);
4243    envlist_free(envlist);
4244
4245    /*
4246     * Now that page sizes are configured in cpu_init() we can do
4247     * proper page alignment for guest_base.
4248     */
4249    guest_base = HOST_PAGE_ALIGN(guest_base);
4250
4251    if (reserved_va || have_guest_base) {
4252        guest_base = init_guest_space(guest_base, reserved_va, 0,
4253                                      have_guest_base);
4254        if (guest_base == (unsigned long)-1) {
4255            fprintf(stderr, "Unable to reserve 0x%lx bytes of virtual address "
4256                    "space for use as guest address space (check your virtual "
4257                    "memory ulimit setting or reserve less using -R option)\n",
4258                    reserved_va);
4259            exit(EXIT_FAILURE);
4260        }
4261
4262        if (reserved_va) {
4263            mmap_next_start = reserved_va;
4264        }
4265    }
4266
4267    /*
4268     * Read in mmap_min_addr kernel parameter.  This value is used
4269     * When loading the ELF image to determine whether guest_base
4270     * is needed.  It is also used in mmap_find_vma.
4271     */
4272    {
4273        FILE *fp;
4274
4275        if ((fp = fopen("/proc/sys/vm/mmap_min_addr", "r")) != NULL) {
4276            unsigned long tmp;
4277            if (fscanf(fp, "%lu", &tmp) == 1) {
4278                mmap_min_addr = tmp;
4279                qemu_log_mask(CPU_LOG_PAGE, "host mmap_min_addr=0x%lx\n", mmap_min_addr);
4280            }
4281            fclose(fp);
4282        }
4283    }
4284
4285    /*
4286     * Prepare copy of argv vector for target.
4287     */
4288    target_argc = argc - optind;
4289    target_argv = calloc(target_argc + 1, sizeof (char *));
4290    if (target_argv == NULL) {
4291        (void) fprintf(stderr, "Unable to allocate memory for target_argv\n");
4292        exit(EXIT_FAILURE);
4293    }
4294
4295    /*
4296     * If argv0 is specified (using '-0' switch) we replace
4297     * argv[0] pointer with the given one.
4298     */
4299    i = 0;
4300    if (argv0 != NULL) {
4301        target_argv[i++] = strdup(argv0);
4302    }
4303    for (; i < target_argc; i++) {
4304        target_argv[i] = strdup(argv[optind + i]);
4305    }
4306    target_argv[target_argc] = NULL;
4307
4308    ts = g_new0(TaskState, 1);
4309    init_task_state(ts);
4310    /* build Task State */
4311    ts->info = info;
4312    ts->bprm = &bprm;
4313    cpu->opaque = ts;
4314    task_settid(ts);
4315
4316    execfd = qemu_getauxval(AT_EXECFD);
4317    if (execfd == 0) {
4318        execfd = open(filename, O_RDONLY);
4319        if (execfd < 0) {
4320            printf("Error while loading %s: %s\n", filename, strerror(errno));
4321            _exit(EXIT_FAILURE);
4322        }
4323    }
4324
4325    ret = loader_exec(execfd, filename, target_argv, target_environ, regs,
4326        info, &bprm);
4327    if (ret != 0) {
4328        printf("Error while loading %s: %s\n", filename, strerror(-ret));
4329        _exit(EXIT_FAILURE);
4330    }
4331
4332    for (wrk = target_environ; *wrk; wrk++) {
4333        free(*wrk);
4334    }
4335
4336    free(target_environ);
4337
4338    if (qemu_loglevel_mask(CPU_LOG_PAGE)) {
4339        qemu_log("guest_base  0x%lx\n", guest_base);
4340        log_page_dump();
4341
4342        qemu_log("start_brk   0x" TARGET_ABI_FMT_lx "\n", info->start_brk);
4343        qemu_log("end_code    0x" TARGET_ABI_FMT_lx "\n", info->end_code);
4344        qemu_log("start_code  0x" TARGET_ABI_FMT_lx "\n",
4345                 info->start_code);
4346        qemu_log("start_data  0x" TARGET_ABI_FMT_lx "\n",
4347                 info->start_data);
4348        qemu_log("end_data    0x" TARGET_ABI_FMT_lx "\n", info->end_data);
4349        qemu_log("start_stack 0x" TARGET_ABI_FMT_lx "\n",
4350                 info->start_stack);
4351        qemu_log("brk         0x" TARGET_ABI_FMT_lx "\n", info->brk);
4352        qemu_log("entry       0x" TARGET_ABI_FMT_lx "\n", info->entry);
4353    }
4354
4355    target_set_brk(info->brk);
4356    syscall_init();
4357    signal_init();
4358
4359    /* Now that we've loaded the binary, GUEST_BASE is fixed.  Delay
4360       generating the prologue until now so that the prologue can take
4361       the real value of GUEST_BASE into account.  */
4362    tcg_prologue_init(&tcg_ctx);
4363
4364#if defined(TARGET_I386)
4365    env->cr[0] = CR0_PG_MASK | CR0_WP_MASK | CR0_PE_MASK;
4366    env->hflags |= HF_PE_MASK | HF_CPL_MASK;
4367    if (env->features[FEAT_1_EDX] & CPUID_SSE) {
4368        env->cr[4] |= CR4_OSFXSR_MASK;
4369        env->hflags |= HF_OSFXSR_MASK;
4370    }
4371#ifndef TARGET_ABI32
4372    /* enable 64 bit mode if possible */
4373    if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_LM)) {
4374        fprintf(stderr, "The selected x86 CPU does not support 64 bit mode\n");
4375        exit(EXIT_FAILURE);
4376    }
4377    env->cr[4] |= CR4_PAE_MASK;
4378    env->efer |= MSR_EFER_LMA | MSR_EFER_LME;
4379    env->hflags |= HF_LMA_MASK;
4380#endif
4381
4382    /* flags setup : we activate the IRQs by default as in user mode */
4383    env->eflags |= IF_MASK;
4384
4385    /* linux register setup */
4386#ifndef TARGET_ABI32
4387    env->regs[R_EAX] = regs->rax;
4388    env->regs[R_EBX] = regs->rbx;
4389    env->regs[R_ECX] = regs->rcx;
4390    env->regs[R_EDX] = regs->rdx;
4391    env->regs[R_ESI] = regs->rsi;
4392    env->regs[R_EDI] = regs->rdi;
4393    env->regs[R_EBP] = regs->rbp;
4394    env->regs[R_ESP] = regs->rsp;
4395    env->eip = regs->rip;
4396#else
4397    env->regs[R_EAX] = regs->eax;
4398    env->regs[R_EBX] = regs->ebx;
4399    env->regs[R_ECX] = regs->ecx;
4400    env->regs[R_EDX] = regs->edx;
4401    env->regs[R_ESI] = regs->esi;
4402    env->regs[R_EDI] = regs->edi;
4403    env->regs[R_EBP] = regs->ebp;
4404    env->regs[R_ESP] = regs->esp;
4405    env->eip = regs->eip;
4406#endif
4407
4408    /* linux interrupt setup */
4409#ifndef TARGET_ABI32
4410    env->idt.limit = 511;
4411#else
4412    env->idt.limit = 255;
4413#endif
4414    env->idt.base = target_mmap(0, sizeof(uint64_t) * (env->idt.limit + 1),
4415                                PROT_READ|PROT_WRITE,
4416                                MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
4417    idt_table = g2h(env->idt.base);
4418    set_idt(0, 0);
4419    set_idt(1, 0);
4420    set_idt(2, 0);
4421    set_idt(3, 3);
4422    set_idt(4, 3);
4423    set_idt(5, 0);
4424    set_idt(6, 0);
4425    set_idt(7, 0);
4426    set_idt(8, 0);
4427    set_idt(9, 0);
4428    set_idt(10, 0);
4429    set_idt(11, 0);
4430    set_idt(12, 0);
4431    set_idt(13, 0);
4432    set_idt(14, 0);
4433    set_idt(15, 0);
4434    set_idt(16, 0);
4435    set_idt(17, 0);
4436    set_idt(18, 0);
4437    set_idt(19, 0);
4438    set_idt(0x80, 3);
4439
4440    /* linux segment setup */
4441    {
4442        uint64_t *gdt_table;
4443        env->gdt.base = target_mmap(0, sizeof(uint64_t) * TARGET_GDT_ENTRIES,
4444                                    PROT_READ|PROT_WRITE,
4445                                    MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
4446        env->gdt.limit = sizeof(uint64_t) * TARGET_GDT_ENTRIES - 1;
4447        gdt_table = g2h(env->gdt.base);
4448#ifdef TARGET_ABI32
4449        write_dt(&gdt_table[__USER_CS >> 3], 0, 0xfffff,
4450                 DESC_G_MASK | DESC_B_MASK | DESC_P_MASK | DESC_S_MASK |
4451                 (3 << DESC_DPL_SHIFT) | (0xa << DESC_TYPE_SHIFT));
4452#else
4453        /* 64 bit code segment */
4454        write_dt(&gdt_table[__USER_CS >> 3], 0, 0xfffff,
4455                 DESC_G_MASK | DESC_B_MASK | DESC_P_MASK | DESC_S_MASK |
4456                 DESC_L_MASK |
4457                 (3 << DESC_DPL_SHIFT) | (0xa << DESC_TYPE_SHIFT));
4458#endif
4459        write_dt(&gdt_table[__USER_DS >> 3], 0, 0xfffff,
4460                 DESC_G_MASK | DESC_B_MASK | DESC_P_MASK | DESC_S_MASK |
4461                 (3 << DESC_DPL_SHIFT) | (0x2 << DESC_TYPE_SHIFT));
4462    }
4463    cpu_x86_load_seg(env, R_CS, __USER_CS);
4464    cpu_x86_load_seg(env, R_SS, __USER_DS);
4465#ifdef TARGET_ABI32
4466    cpu_x86_load_seg(env, R_DS, __USER_DS);
4467    cpu_x86_load_seg(env, R_ES, __USER_DS);
4468    cpu_x86_load_seg(env, R_FS, __USER_DS);
4469    cpu_x86_load_seg(env, R_GS, __USER_DS);
4470    /* This hack makes Wine work... */
4471    env->segs[R_FS].selector = 0;
4472#else
4473    cpu_x86_load_seg(env, R_DS, 0);
4474    cpu_x86_load_seg(env, R_ES, 0);
4475    cpu_x86_load_seg(env, R_FS, 0);
4476    cpu_x86_load_seg(env, R_GS, 0);
4477#endif
4478#elif defined(TARGET_AARCH64)
4479    {
4480        int i;
4481
4482        if (!(arm_feature(env, ARM_FEATURE_AARCH64))) {
4483            fprintf(stderr,
4484                    "The selected ARM CPU does not support 64 bit mode\n");
4485            exit(EXIT_FAILURE);
4486        }
4487
4488        for (i = 0; i < 31; i++) {
4489            env->xregs[i] = regs->regs[i];
4490        }
4491        env->pc = regs->pc;
4492        env->xregs[31] = regs->sp;
4493    }
4494#elif defined(TARGET_ARM)
4495    {
4496        int i;
4497        cpsr_write(env, regs->uregs[16], CPSR_USER | CPSR_EXEC,
4498                   CPSRWriteByInstr);
4499        for(i = 0; i < 16; i++) {
4500            env->regs[i] = regs->uregs[i];
4501        }
4502#ifdef TARGET_WORDS_BIGENDIAN
4503        /* Enable BE8.  */
4504        if (EF_ARM_EABI_VERSION(info->elf_flags) >= EF_ARM_EABI_VER4
4505            && (info->elf_flags & EF_ARM_BE8)) {
4506            env->uncached_cpsr |= CPSR_E;
4507            env->cp15.sctlr_el[1] |= SCTLR_E0E;
4508        } else {
4509            env->cp15.sctlr_el[1] |= SCTLR_B;
4510        }
4511#endif
4512    }
4513#elif defined(TARGET_UNICORE32)
4514    {
4515        int i;
4516        cpu_asr_write(env, regs->uregs[32], 0xffffffff);
4517        for (i = 0; i < 32; i++) {
4518            env->regs[i] = regs->uregs[i];
4519        }
4520    }
4521#elif defined(TARGET_SPARC)
4522    {
4523        int i;
4524        env->pc = regs->pc;
4525        env->npc = regs->npc;
4526        env->y = regs->y;
4527        for(i = 0; i < 8; i++)
4528            env->gregs[i] = regs->u_regs[i];
4529        for(i = 0; i < 8; i++)
4530            env->regwptr[i] = regs->u_regs[i + 8];
4531    }
4532#elif defined(TARGET_PPC)
4533    {
4534        int i;
4535
4536#if defined(TARGET_PPC64)
4537#if defined(TARGET_ABI32)
4538        env->msr &= ~((target_ulong)1 << MSR_SF);
4539#else
4540        env->msr |= (target_ulong)1 << MSR_SF;
4541#endif
4542#endif
4543        env->nip = regs->nip;
4544        for(i = 0; i < 32; i++) {
4545            env->gpr[i] = regs->gpr[i];
4546        }
4547    }
4548#elif defined(TARGET_M68K)
4549    {
4550        env->pc = regs->pc;
4551        env->dregs[0] = regs->d0;
4552        env->dregs[1] = regs->d1;
4553        env->dregs[2] = regs->d2;
4554        env->dregs[3] = regs->d3;
4555        env->dregs[4] = regs->d4;
4556        env->dregs[5] = regs->d5;
4557        env->dregs[6] = regs->d6;
4558        env->dregs[7] = regs->d7;
4559        env->aregs[0] = regs->a0;
4560        env->aregs[1] = regs->a1;
4561        env->aregs[2] = regs->a2;
4562        env->aregs[3] = regs->a3;
4563        env->aregs[4] = regs->a4;
4564        env->aregs[5] = regs->a5;
4565        env->aregs[6] = regs->a6;
4566        env->aregs[7] = regs->usp;
4567        env->sr = regs->sr;
4568        ts->sim_syscalls = 1;
4569    }
4570#elif defined(TARGET_MICROBLAZE)
4571    {
4572        env->regs[0] = regs->r0;
4573        env->regs[1] = regs->r1;
4574        env->regs[2] = regs->r2;
4575        env->regs[3] = regs->r3;
4576        env->regs[4] = regs->r4;
4577        env->regs[5] = regs->r5;
4578        env->regs[6] = regs->r6;
4579        env->regs[7] = regs->r7;
4580        env->regs[8] = regs->r8;
4581        env->regs[9] = regs->r9;
4582        env->regs[10] = regs->r10;
4583        env->regs[11] = regs->r11;
4584        env->regs[12] = regs->r12;
4585        env->regs[13] = regs->r13;
4586        env->regs[14] = regs->r14;
4587        env->regs[15] = regs->r15;          
4588        env->regs[16] = regs->r16;          
4589        env->regs[17] = regs->r17;          
4590        env->regs[18] = regs->r18;          
4591        env->regs[19] = regs->r19;          
4592        env->regs[20] = regs->r20;          
4593        env->regs[21] = regs->r21;          
4594        env->regs[22] = regs->r22;          
4595        env->regs[23] = regs->r23;          
4596        env->regs[24] = regs->r24;          
4597        env->regs[25] = regs->r25;          
4598        env->regs[26] = regs->r26;          
4599        env->regs[27] = regs->r27;          
4600        env->regs[28] = regs->r28;          
4601        env->regs[29] = regs->r29;          
4602        env->regs[30] = regs->r30;          
4603        env->regs[31] = regs->r31;          
4604        env->sregs[SR_PC] = regs->pc;
4605    }
4606#elif defined(TARGET_MIPS)
4607    {
4608        int i;
4609
4610        for(i = 0; i < 32; i++) {
4611            env->active_tc.gpr[i] = regs->regs[i];
4612        }
4613        env->active_tc.PC = regs->cp0_epc & ~(target_ulong)1;
4614        if (regs->cp0_epc & 1) {
4615            env->hflags |= MIPS_HFLAG_M16;
4616        }
4617    }
4618#elif defined(TARGET_OPENRISC)
4619    {
4620        int i;
4621
4622        for (i = 0; i < 32; i++) {
4623            env->gpr[i] = regs->gpr[i];
4624        }
4625
4626        env->sr = regs->sr;
4627        env->pc = regs->pc;
4628    }
4629#elif defined(TARGET_SH4)
4630    {
4631        int i;
4632
4633        for(i = 0; i < 16; i++) {
4634            env->gregs[i] = regs->regs[i];
4635        }
4636        env->pc = regs->pc;
4637    }
4638#elif defined(TARGET_ALPHA)
4639    {
4640        int i;
4641
4642        for(i = 0; i < 28; i++) {
4643            env->ir[i] = ((abi_ulong *)regs)[i];
4644        }
4645        env->ir[IR_SP] = regs->usp;
4646        env->pc = regs->pc;
4647    }
4648#elif defined(TARGET_CRIS)
4649    {
4650            env->regs[0] = regs->r0;
4651            env->regs[1] = regs->r1;
4652            env->regs[2] = regs->r2;
4653            env->regs[3] = regs->r3;
4654            env->regs[4] = regs->r4;
4655            env->regs[5] = regs->r5;
4656            env->regs[6] = regs->r6;
4657            env->regs[7] = regs->r7;
4658            env->regs[8] = regs->r8;
4659            env->regs[9] = regs->r9;
4660            env->regs[10] = regs->r10;
4661            env->regs[11] = regs->r11;
4662            env->regs[12] = regs->r12;
4663            env->regs[13] = regs->r13;
4664            env->regs[14] = info->start_stack;
4665            env->regs[15] = regs->acr;      
4666            env->pc = regs->erp;
4667    }
4668#elif defined(TARGET_S390X)
4669    {
4670            int i;
4671            for (i = 0; i < 16; i++) {
4672                env->regs[i] = regs->gprs[i];
4673            }
4674            env->psw.mask = regs->psw.mask;
4675            env->psw.addr = regs->psw.addr;
4676    }
4677#elif defined(TARGET_TILEGX)
4678    {
4679        int i;
4680        for (i = 0; i < TILEGX_R_COUNT; i++) {
4681            env->regs[i] = regs->regs[i];
4682        }
4683        for (i = 0; i < TILEGX_SPR_COUNT; i++) {
4684            env->spregs[i] = 0;
4685        }
4686        env->pc = regs->pc;
4687    }
4688#else
4689#error unsupported target CPU
4690#endif
4691
4692#if defined(TARGET_ARM) || defined(TARGET_M68K) || defined(TARGET_UNICORE32)
4693    ts->stack_base = info->start_stack;
4694    ts->heap_base = info->brk;
4695    /* This will be filled in on the first SYS_HEAPINFO call.  */
4696    ts->heap_limit = 0;
4697#endif
4698
4699    if (gdbstub_port) {
4700        if (gdbserver_start(gdbstub_port) < 0) {
4701            fprintf(stderr, "qemu: could not open gdbserver on port %d\n",
4702                    gdbstub_port);
4703            exit(EXIT_FAILURE);
4704        }
4705        gdb_handlesig(cpu, 0);
4706    }
4707    cpu_loop(env);
4708    /* never exits */
4709    return 0;
4710}
4711