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