xref: /openbmc/qemu/include/hw/core/cpu.h (revision cbc183d2)
1 /*
2  * QEMU CPU model
3  *
4  * Copyright (c) 2012 SUSE LINUX Products GmbH
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (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
18  * <http://www.gnu.org/licenses/gpl-2.0.html>
19  */
20 #ifndef QEMU_CPU_H
21 #define QEMU_CPU_H
22 
23 #include "hw/qdev-core.h"
24 #include "disas/dis-asm.h"
25 #include "exec/hwaddr.h"
26 #include "exec/memattrs.h"
27 #include "qapi/qapi-types-run-state.h"
28 #include "qemu/bitmap.h"
29 #include "qemu/rcu_queue.h"
30 #include "qemu/queue.h"
31 #include "qemu/thread.h"
32 #include "qemu/plugin.h"
33 #include "qom/object.h"
34 
35 typedef int (*WriteCoreDumpFunction)(const void *buf, size_t size,
36                                      void *opaque);
37 
38 /**
39  * vaddr:
40  * Type wide enough to contain any #target_ulong virtual address.
41  */
42 typedef uint64_t vaddr;
43 #define VADDR_PRId PRId64
44 #define VADDR_PRIu PRIu64
45 #define VADDR_PRIo PRIo64
46 #define VADDR_PRIx PRIx64
47 #define VADDR_PRIX PRIX64
48 #define VADDR_MAX UINT64_MAX
49 
50 /**
51  * SECTION:cpu
52  * @section_id: QEMU-cpu
53  * @title: CPU Class
54  * @short_description: Base class for all CPUs
55  */
56 
57 #define TYPE_CPU "cpu"
58 
59 /* Since this macro is used a lot in hot code paths and in conjunction with
60  * FooCPU *foo_env_get_cpu(), we deviate from usual QOM practice by using
61  * an unchecked cast.
62  */
63 #define CPU(obj) ((CPUState *)(obj))
64 
65 typedef struct CPUClass CPUClass;
66 DECLARE_CLASS_CHECKERS(CPUClass, CPU,
67                        TYPE_CPU)
68 
69 typedef enum MMUAccessType {
70     MMU_DATA_LOAD  = 0,
71     MMU_DATA_STORE = 1,
72     MMU_INST_FETCH = 2
73 } MMUAccessType;
74 
75 typedef struct CPUWatchpoint CPUWatchpoint;
76 
77 struct TranslationBlock;
78 
79 /**
80  * struct TcgCpuOperations: TCG operations specific to a CPU class
81  */
82 typedef struct TcgCpuOperations {
83     /**
84      * @initialize: Initalize TCG state
85      *
86      * Called when the first CPU is realized.
87      */
88     void (*initialize)(void);
89     /**
90      * @synchronize_from_tb: Synchronize state from a TCG #TranslationBlock
91      *
92      * This is called when we abandon execution of a TB before starting it,
93      * and must set all parts of the CPU state which the previous TB in the
94      * chain may not have updated.
95      * By default, when this is NULL, a call is made to @set_pc(tb->pc).
96      *
97      * If more state needs to be restored, the target must implement a
98      * function to restore all the state, and register it here.
99      */
100     void (*synchronize_from_tb)(CPUState *cpu,
101                                 const struct TranslationBlock *tb);
102     /** @cpu_exec_enter: Callback for cpu_exec preparation */
103     void (*cpu_exec_enter)(CPUState *cpu);
104     /** @cpu_exec_exit: Callback for cpu_exec cleanup */
105     void (*cpu_exec_exit)(CPUState *cpu);
106     /** @cpu_exec_interrupt: Callback for processing interrupts in cpu_exec */
107     bool (*cpu_exec_interrupt)(CPUState *cpu, int interrupt_request);
108     /** @do_interrupt: Callback for interrupt handling. */
109     void (*do_interrupt)(CPUState *cpu);
110     /**
111      * @tlb_fill: Handle a softmmu tlb miss or user-only address fault
112      *
113      * For system mode, if the access is valid, call tlb_set_page
114      * and return true; if the access is invalid, and probe is
115      * true, return false; otherwise raise an exception and do
116      * not return.  For user-only mode, always raise an exception
117      * and do not return.
118      */
119     bool (*tlb_fill)(CPUState *cpu, vaddr address, int size,
120                      MMUAccessType access_type, int mmu_idx,
121                      bool probe, uintptr_t retaddr);
122     /** @debug_excp_handler: Callback for handling debug exceptions */
123     void (*debug_excp_handler)(CPUState *cpu);
124 
125     /**
126      * @do_transaction_failed: Callback for handling failed memory transactions
127      * (ie bus faults or external aborts; not MMU faults)
128      */
129     void (*do_transaction_failed)(CPUState *cpu, hwaddr physaddr, vaddr addr,
130                                   unsigned size, MMUAccessType access_type,
131                                   int mmu_idx, MemTxAttrs attrs,
132                                   MemTxResult response, uintptr_t retaddr);
133 } TcgCpuOperations;
134 
135 /**
136  * CPUClass:
137  * @class_by_name: Callback to map -cpu command line model name to an
138  * instantiatable CPU type.
139  * @parse_features: Callback to parse command line arguments.
140  * @reset_dump_flags: #CPUDumpFlags to use for reset logging.
141  * @has_work: Callback for checking if there is work to do.
142  * @do_unaligned_access: Callback for unaligned access handling, if
143  * the target defines #TARGET_ALIGNED_ONLY.
144  * @virtio_is_big_endian: Callback to return %true if a CPU which supports
145  * runtime configurable endianness is currently big-endian. Non-configurable
146  * CPUs can use the default implementation of this method. This method should
147  * not be used by any callers other than the pre-1.0 virtio devices.
148  * @memory_rw_debug: Callback for GDB memory access.
149  * @dump_state: Callback for dumping state.
150  * @dump_statistics: Callback for dumping statistics.
151  * @get_arch_id: Callback for getting architecture-dependent CPU ID.
152  * @get_paging_enabled: Callback for inquiring whether paging is enabled.
153  * @get_memory_mapping: Callback for obtaining the memory mappings.
154  * @set_pc: Callback for setting the Program Counter register. This
155  *       should have the semantics used by the target architecture when
156  *       setting the PC from a source such as an ELF file entry point;
157  *       for example on Arm it will also set the Thumb mode bit based
158  *       on the least significant bit of the new PC value.
159  *       If the target behaviour here is anything other than "set
160  *       the PC register to the value passed in" then the target must
161  *       also implement the synchronize_from_tb hook.
162  * @get_phys_page_debug: Callback for obtaining a physical address.
163  * @get_phys_page_attrs_debug: Callback for obtaining a physical address and the
164  *       associated memory transaction attributes to use for the access.
165  *       CPUs which use memory transaction attributes should implement this
166  *       instead of get_phys_page_debug.
167  * @asidx_from_attrs: Callback to return the CPU AddressSpace to use for
168  *       a memory access with the specified memory transaction attributes.
169  * @gdb_read_register: Callback for letting GDB read a register.
170  * @gdb_write_register: Callback for letting GDB write a register.
171  * @debug_check_watchpoint: Callback: return true if the architectural
172  *       watchpoint whose address has matched should really fire.
173  * @write_elf64_note: Callback for writing a CPU-specific ELF note to a
174  * 64-bit VM coredump.
175  * @write_elf32_qemunote: Callback for writing a CPU- and QEMU-specific ELF
176  * note to a 32-bit VM coredump.
177  * @write_elf32_note: Callback for writing a CPU-specific ELF note to a
178  * 32-bit VM coredump.
179  * @write_elf32_qemunote: Callback for writing a CPU- and QEMU-specific ELF
180  * note to a 32-bit VM coredump.
181  * @vmsd: State description for migration.
182  * @gdb_num_core_regs: Number of core registers accessible to GDB.
183  * @gdb_core_xml_file: File name for core registers GDB XML description.
184  * @gdb_stop_before_watchpoint: Indicates whether GDB expects the CPU to stop
185  *           before the insn which triggers a watchpoint rather than after it.
186  * @gdb_arch_name: Optional callback that returns the architecture name known
187  * to GDB. The caller must free the returned string with g_free.
188  * @gdb_get_dynamic_xml: Callback to return dynamically generated XML for the
189  *   gdb stub. Returns a pointer to the XML contents for the specified XML file
190  *   or NULL if the CPU doesn't have a dynamically generated content for it.
191  * @disas_set_info: Setup architecture specific components of disassembly info
192  * @adjust_watchpoint_address: Perform a target-specific adjustment to an
193  * address before attempting to match it against watchpoints.
194  * @deprecation_note: If this CPUClass is deprecated, this field provides
195  *                    related information.
196  *
197  * Represents a CPU family or model.
198  */
199 struct CPUClass {
200     /*< private >*/
201     DeviceClass parent_class;
202     /*< public >*/
203 
204     ObjectClass *(*class_by_name)(const char *cpu_model);
205     void (*parse_features)(const char *typename, char *str, Error **errp);
206 
207     int reset_dump_flags;
208     bool (*has_work)(CPUState *cpu);
209     void (*do_unaligned_access)(CPUState *cpu, vaddr addr,
210                                 MMUAccessType access_type,
211                                 int mmu_idx, uintptr_t retaddr);
212     bool (*virtio_is_big_endian)(CPUState *cpu);
213     int (*memory_rw_debug)(CPUState *cpu, vaddr addr,
214                            uint8_t *buf, int len, bool is_write);
215     void (*dump_state)(CPUState *cpu, FILE *, int flags);
216     GuestPanicInformation* (*get_crash_info)(CPUState *cpu);
217     void (*dump_statistics)(CPUState *cpu, int flags);
218     int64_t (*get_arch_id)(CPUState *cpu);
219     bool (*get_paging_enabled)(const CPUState *cpu);
220     void (*get_memory_mapping)(CPUState *cpu, MemoryMappingList *list,
221                                Error **errp);
222     void (*set_pc)(CPUState *cpu, vaddr value);
223     hwaddr (*get_phys_page_debug)(CPUState *cpu, vaddr addr);
224     hwaddr (*get_phys_page_attrs_debug)(CPUState *cpu, vaddr addr,
225                                         MemTxAttrs *attrs);
226     int (*asidx_from_attrs)(CPUState *cpu, MemTxAttrs attrs);
227     int (*gdb_read_register)(CPUState *cpu, GByteArray *buf, int reg);
228     int (*gdb_write_register)(CPUState *cpu, uint8_t *buf, int reg);
229     bool (*debug_check_watchpoint)(CPUState *cpu, CPUWatchpoint *wp);
230 
231     int (*write_elf64_note)(WriteCoreDumpFunction f, CPUState *cpu,
232                             int cpuid, void *opaque);
233     int (*write_elf64_qemunote)(WriteCoreDumpFunction f, CPUState *cpu,
234                                 void *opaque);
235     int (*write_elf32_note)(WriteCoreDumpFunction f, CPUState *cpu,
236                             int cpuid, void *opaque);
237     int (*write_elf32_qemunote)(WriteCoreDumpFunction f, CPUState *cpu,
238                                 void *opaque);
239 
240     const VMStateDescription *vmsd;
241     const char *gdb_core_xml_file;
242     gchar * (*gdb_arch_name)(CPUState *cpu);
243     const char * (*gdb_get_dynamic_xml)(CPUState *cpu, const char *xmlname);
244 
245     void (*disas_set_info)(CPUState *cpu, disassemble_info *info);
246     vaddr (*adjust_watchpoint_address)(CPUState *cpu, vaddr addr, int len);
247 
248     const char *deprecation_note;
249     /* Keep non-pointer data at the end to minimize holes.  */
250     int gdb_num_core_regs;
251     bool gdb_stop_before_watchpoint;
252 
253     TcgCpuOperations tcg_ops;
254 };
255 
256 /*
257  * Low 16 bits: number of cycles left, used only in icount mode.
258  * High 16 bits: Set to -1 to force TCG to stop executing linked TBs
259  * for this CPU and return to its top level loop (even in non-icount mode).
260  * This allows a single read-compare-cbranch-write sequence to test
261  * for both decrementer underflow and exceptions.
262  */
263 typedef union IcountDecr {
264     uint32_t u32;
265     struct {
266 #ifdef HOST_WORDS_BIGENDIAN
267         uint16_t high;
268         uint16_t low;
269 #else
270         uint16_t low;
271         uint16_t high;
272 #endif
273     } u16;
274 } IcountDecr;
275 
276 typedef struct CPUBreakpoint {
277     vaddr pc;
278     int flags; /* BP_* */
279     QTAILQ_ENTRY(CPUBreakpoint) entry;
280 } CPUBreakpoint;
281 
282 struct CPUWatchpoint {
283     vaddr vaddr;
284     vaddr len;
285     vaddr hitaddr;
286     MemTxAttrs hitattrs;
287     int flags; /* BP_* */
288     QTAILQ_ENTRY(CPUWatchpoint) entry;
289 };
290 
291 #ifdef CONFIG_PLUGIN
292 /*
293  * For plugins we sometime need to save the resolved iotlb data before
294  * the memory regions get moved around  by io_writex.
295  */
296 typedef struct SavedIOTLB {
297     hwaddr addr;
298     MemoryRegionSection *section;
299     hwaddr mr_offset;
300 } SavedIOTLB;
301 #endif
302 
303 struct KVMState;
304 struct kvm_run;
305 
306 struct hax_vcpu_state;
307 
308 #define TB_JMP_CACHE_BITS 12
309 #define TB_JMP_CACHE_SIZE (1 << TB_JMP_CACHE_BITS)
310 
311 /* work queue */
312 
313 /* The union type allows passing of 64 bit target pointers on 32 bit
314  * hosts in a single parameter
315  */
316 typedef union {
317     int           host_int;
318     unsigned long host_ulong;
319     void         *host_ptr;
320     vaddr         target_ptr;
321 } run_on_cpu_data;
322 
323 #define RUN_ON_CPU_HOST_PTR(p)    ((run_on_cpu_data){.host_ptr = (p)})
324 #define RUN_ON_CPU_HOST_INT(i)    ((run_on_cpu_data){.host_int = (i)})
325 #define RUN_ON_CPU_HOST_ULONG(ul) ((run_on_cpu_data){.host_ulong = (ul)})
326 #define RUN_ON_CPU_TARGET_PTR(v)  ((run_on_cpu_data){.target_ptr = (v)})
327 #define RUN_ON_CPU_NULL           RUN_ON_CPU_HOST_PTR(NULL)
328 
329 typedef void (*run_on_cpu_func)(CPUState *cpu, run_on_cpu_data data);
330 
331 struct qemu_work_item;
332 
333 #define CPU_UNSET_NUMA_NODE_ID -1
334 #define CPU_TRACE_DSTATE_MAX_EVENTS 32
335 
336 /**
337  * CPUState:
338  * @cpu_index: CPU index (informative).
339  * @cluster_index: Identifies which cluster this CPU is in.
340  *   For boards which don't define clusters or for "loose" CPUs not assigned
341  *   to a cluster this will be UNASSIGNED_CLUSTER_INDEX; otherwise it will
342  *   be the same as the cluster-id property of the CPU object's TYPE_CPU_CLUSTER
343  *   QOM parent.
344  * @nr_cores: Number of cores within this CPU package.
345  * @nr_threads: Number of threads within this CPU.
346  * @running: #true if CPU is currently running (lockless).
347  * @has_waiter: #true if a CPU is currently waiting for the cpu_exec_end;
348  * valid under cpu_list_lock.
349  * @created: Indicates whether the CPU thread has been successfully created.
350  * @interrupt_request: Indicates a pending interrupt request.
351  * @halted: Nonzero if the CPU is in suspended state.
352  * @stop: Indicates a pending stop request.
353  * @stopped: Indicates the CPU has been artificially stopped.
354  * @unplug: Indicates a pending CPU unplug request.
355  * @crash_occurred: Indicates the OS reported a crash (panic) for this CPU
356  * @singlestep_enabled: Flags for single-stepping.
357  * @icount_extra: Instructions until next timer event.
358  * @can_do_io: Nonzero if memory-mapped IO is safe. Deterministic execution
359  * requires that IO only be performed on the last instruction of a TB
360  * so that interrupts take effect immediately.
361  * @cpu_ases: Pointer to array of CPUAddressSpaces (which define the
362  *            AddressSpaces this CPU has)
363  * @num_ases: number of CPUAddressSpaces in @cpu_ases
364  * @as: Pointer to the first AddressSpace, for the convenience of targets which
365  *      only have a single AddressSpace
366  * @env_ptr: Pointer to subclass-specific CPUArchState field.
367  * @icount_decr_ptr: Pointer to IcountDecr field within subclass.
368  * @gdb_regs: Additional GDB registers.
369  * @gdb_num_regs: Number of total registers accessible to GDB.
370  * @gdb_num_g_regs: Number of registers in GDB 'g' packets.
371  * @next_cpu: Next CPU sharing TB cache.
372  * @opaque: User data.
373  * @mem_io_pc: Host Program Counter at which the memory was accessed.
374  * @kvm_fd: vCPU file descriptor for KVM.
375  * @work_mutex: Lock to prevent multiple access to @work_list.
376  * @work_list: List of pending asynchronous work.
377  * @trace_dstate_delayed: Delayed changes to trace_dstate (includes all changes
378  *                        to @trace_dstate).
379  * @trace_dstate: Dynamic tracing state of events for this vCPU (bitmask).
380  * @plugin_mask: Plugin event bitmap. Modified only via async work.
381  * @ignore_memory_transaction_failures: Cached copy of the MachineState
382  *    flag of the same name: allows the board to suppress calling of the
383  *    CPU do_transaction_failed hook function.
384  *
385  * State of one CPU core or thread.
386  */
387 struct CPUState {
388     /*< private >*/
389     DeviceState parent_obj;
390     /*< public >*/
391 
392     int nr_cores;
393     int nr_threads;
394 
395     struct QemuThread *thread;
396 #ifdef _WIN32
397     HANDLE hThread;
398 #endif
399     int thread_id;
400     bool running, has_waiter;
401     struct QemuCond *halt_cond;
402     bool thread_kicked;
403     bool created;
404     bool stop;
405     bool stopped;
406 
407     /* Should CPU start in powered-off state? */
408     bool start_powered_off;
409 
410     bool unplug;
411     bool crash_occurred;
412     bool exit_request;
413     bool in_exclusive_context;
414     uint32_t cflags_next_tb;
415     /* updates protected by BQL */
416     uint32_t interrupt_request;
417     int singlestep_enabled;
418     int64_t icount_budget;
419     int64_t icount_extra;
420     uint64_t random_seed;
421     sigjmp_buf jmp_env;
422 
423     QemuMutex work_mutex;
424     QSIMPLEQ_HEAD(, qemu_work_item) work_list;
425 
426     CPUAddressSpace *cpu_ases;
427     int num_ases;
428     AddressSpace *as;
429     MemoryRegion *memory;
430 
431     void *env_ptr; /* CPUArchState */
432     IcountDecr *icount_decr_ptr;
433 
434     /* Accessed in parallel; all accesses must be atomic */
435     struct TranslationBlock *tb_jmp_cache[TB_JMP_CACHE_SIZE];
436 
437     struct GDBRegisterState *gdb_regs;
438     int gdb_num_regs;
439     int gdb_num_g_regs;
440     QTAILQ_ENTRY(CPUState) node;
441 
442     /* ice debug support */
443     QTAILQ_HEAD(, CPUBreakpoint) breakpoints;
444 
445     QTAILQ_HEAD(, CPUWatchpoint) watchpoints;
446     CPUWatchpoint *watchpoint_hit;
447 
448     void *opaque;
449 
450     /* In order to avoid passing too many arguments to the MMIO helpers,
451      * we store some rarely used information in the CPU context.
452      */
453     uintptr_t mem_io_pc;
454 
455     int kvm_fd;
456     struct KVMState *kvm_state;
457     struct kvm_run *kvm_run;
458 
459     /* Used for events with 'vcpu' and *without* the 'disabled' properties */
460     DECLARE_BITMAP(trace_dstate_delayed, CPU_TRACE_DSTATE_MAX_EVENTS);
461     DECLARE_BITMAP(trace_dstate, CPU_TRACE_DSTATE_MAX_EVENTS);
462 
463     DECLARE_BITMAP(plugin_mask, QEMU_PLUGIN_EV_MAX);
464 
465 #ifdef CONFIG_PLUGIN
466     GArray *plugin_mem_cbs;
467     /* saved iotlb data from io_writex */
468     SavedIOTLB saved_iotlb;
469 #endif
470 
471     /* TODO Move common fields from CPUArchState here. */
472     int cpu_index;
473     int cluster_index;
474     uint32_t halted;
475     uint32_t can_do_io;
476     int32_t exception_index;
477 
478     /* shared by kvm, hax and hvf */
479     bool vcpu_dirty;
480 
481     /* Used to keep track of an outstanding cpu throttle thread for migration
482      * autoconverge
483      */
484     bool throttle_thread_scheduled;
485 
486     bool ignore_memory_transaction_failures;
487 
488     struct hax_vcpu_state *hax_vcpu;
489 
490     int hvf_fd;
491 
492     /* track IOMMUs whose translations we've cached in the TCG TLB */
493     GArray *iommu_notifiers;
494 };
495 
496 typedef QTAILQ_HEAD(CPUTailQ, CPUState) CPUTailQ;
497 extern CPUTailQ cpus;
498 
499 #define first_cpu        QTAILQ_FIRST_RCU(&cpus)
500 #define CPU_NEXT(cpu)    QTAILQ_NEXT_RCU(cpu, node)
501 #define CPU_FOREACH(cpu) QTAILQ_FOREACH_RCU(cpu, &cpus, node)
502 #define CPU_FOREACH_SAFE(cpu, next_cpu) \
503     QTAILQ_FOREACH_SAFE_RCU(cpu, &cpus, node, next_cpu)
504 
505 extern __thread CPUState *current_cpu;
506 
507 static inline void cpu_tb_jmp_cache_clear(CPUState *cpu)
508 {
509     unsigned int i;
510 
511     for (i = 0; i < TB_JMP_CACHE_SIZE; i++) {
512         qatomic_set(&cpu->tb_jmp_cache[i], NULL);
513     }
514 }
515 
516 /**
517  * qemu_tcg_mttcg_enabled:
518  * Check whether we are running MultiThread TCG or not.
519  *
520  * Returns: %true if we are in MTTCG mode %false otherwise.
521  */
522 extern bool mttcg_enabled;
523 #define qemu_tcg_mttcg_enabled() (mttcg_enabled)
524 
525 /**
526  * cpu_paging_enabled:
527  * @cpu: The CPU whose state is to be inspected.
528  *
529  * Returns: %true if paging is enabled, %false otherwise.
530  */
531 bool cpu_paging_enabled(const CPUState *cpu);
532 
533 /**
534  * cpu_get_memory_mapping:
535  * @cpu: The CPU whose memory mappings are to be obtained.
536  * @list: Where to write the memory mappings to.
537  * @errp: Pointer for reporting an #Error.
538  */
539 void cpu_get_memory_mapping(CPUState *cpu, MemoryMappingList *list,
540                             Error **errp);
541 
542 #if !defined(CONFIG_USER_ONLY)
543 
544 /**
545  * cpu_write_elf64_note:
546  * @f: pointer to a function that writes memory to a file
547  * @cpu: The CPU whose memory is to be dumped
548  * @cpuid: ID number of the CPU
549  * @opaque: pointer to the CPUState struct
550  */
551 int cpu_write_elf64_note(WriteCoreDumpFunction f, CPUState *cpu,
552                          int cpuid, void *opaque);
553 
554 /**
555  * cpu_write_elf64_qemunote:
556  * @f: pointer to a function that writes memory to a file
557  * @cpu: The CPU whose memory is to be dumped
558  * @cpuid: ID number of the CPU
559  * @opaque: pointer to the CPUState struct
560  */
561 int cpu_write_elf64_qemunote(WriteCoreDumpFunction f, CPUState *cpu,
562                              void *opaque);
563 
564 /**
565  * cpu_write_elf32_note:
566  * @f: pointer to a function that writes memory to a file
567  * @cpu: The CPU whose memory is to be dumped
568  * @cpuid: ID number of the CPU
569  * @opaque: pointer to the CPUState struct
570  */
571 int cpu_write_elf32_note(WriteCoreDumpFunction f, CPUState *cpu,
572                          int cpuid, void *opaque);
573 
574 /**
575  * cpu_write_elf32_qemunote:
576  * @f: pointer to a function that writes memory to a file
577  * @cpu: The CPU whose memory is to be dumped
578  * @cpuid: ID number of the CPU
579  * @opaque: pointer to the CPUState struct
580  */
581 int cpu_write_elf32_qemunote(WriteCoreDumpFunction f, CPUState *cpu,
582                              void *opaque);
583 
584 /**
585  * cpu_get_crash_info:
586  * @cpu: The CPU to get crash information for
587  *
588  * Gets the previously saved crash information.
589  * Caller is responsible for freeing the data.
590  */
591 GuestPanicInformation *cpu_get_crash_info(CPUState *cpu);
592 
593 #endif /* !CONFIG_USER_ONLY */
594 
595 /**
596  * CPUDumpFlags:
597  * @CPU_DUMP_CODE:
598  * @CPU_DUMP_FPU: dump FPU register state, not just integer
599  * @CPU_DUMP_CCOP: dump info about TCG QEMU's condition code optimization state
600  */
601 enum CPUDumpFlags {
602     CPU_DUMP_CODE = 0x00010000,
603     CPU_DUMP_FPU  = 0x00020000,
604     CPU_DUMP_CCOP = 0x00040000,
605 };
606 
607 /**
608  * cpu_dump_state:
609  * @cpu: The CPU whose state is to be dumped.
610  * @f: If non-null, dump to this stream, else to current print sink.
611  *
612  * Dumps CPU state.
613  */
614 void cpu_dump_state(CPUState *cpu, FILE *f, int flags);
615 
616 /**
617  * cpu_dump_statistics:
618  * @cpu: The CPU whose state is to be dumped.
619  * @flags: Flags what to dump.
620  *
621  * Dump CPU statistics to the current monitor if we have one, else to
622  * stdout.
623  */
624 void cpu_dump_statistics(CPUState *cpu, int flags);
625 
626 #ifndef CONFIG_USER_ONLY
627 /**
628  * cpu_get_phys_page_attrs_debug:
629  * @cpu: The CPU to obtain the physical page address for.
630  * @addr: The virtual address.
631  * @attrs: Updated on return with the memory transaction attributes to use
632  *         for this access.
633  *
634  * Obtains the physical page corresponding to a virtual one, together
635  * with the corresponding memory transaction attributes to use for the access.
636  * Use it only for debugging because no protection checks are done.
637  *
638  * Returns: Corresponding physical page address or -1 if no page found.
639  */
640 static inline hwaddr cpu_get_phys_page_attrs_debug(CPUState *cpu, vaddr addr,
641                                                    MemTxAttrs *attrs)
642 {
643     CPUClass *cc = CPU_GET_CLASS(cpu);
644 
645     if (cc->get_phys_page_attrs_debug) {
646         return cc->get_phys_page_attrs_debug(cpu, addr, attrs);
647     }
648     /* Fallback for CPUs which don't implement the _attrs_ hook */
649     *attrs = MEMTXATTRS_UNSPECIFIED;
650     return cc->get_phys_page_debug(cpu, addr);
651 }
652 
653 /**
654  * cpu_get_phys_page_debug:
655  * @cpu: The CPU to obtain the physical page address for.
656  * @addr: The virtual address.
657  *
658  * Obtains the physical page corresponding to a virtual one.
659  * Use it only for debugging because no protection checks are done.
660  *
661  * Returns: Corresponding physical page address or -1 if no page found.
662  */
663 static inline hwaddr cpu_get_phys_page_debug(CPUState *cpu, vaddr addr)
664 {
665     MemTxAttrs attrs = {};
666 
667     return cpu_get_phys_page_attrs_debug(cpu, addr, &attrs);
668 }
669 
670 /** cpu_asidx_from_attrs:
671  * @cpu: CPU
672  * @attrs: memory transaction attributes
673  *
674  * Returns the address space index specifying the CPU AddressSpace
675  * to use for a memory access with the given transaction attributes.
676  */
677 static inline int cpu_asidx_from_attrs(CPUState *cpu, MemTxAttrs attrs)
678 {
679     CPUClass *cc = CPU_GET_CLASS(cpu);
680     int ret = 0;
681 
682     if (cc->asidx_from_attrs) {
683         ret = cc->asidx_from_attrs(cpu, attrs);
684         assert(ret < cpu->num_ases && ret >= 0);
685     }
686     return ret;
687 }
688 
689 #endif /* CONFIG_USER_ONLY */
690 
691 /**
692  * cpu_list_add:
693  * @cpu: The CPU to be added to the list of CPUs.
694  */
695 void cpu_list_add(CPUState *cpu);
696 
697 /**
698  * cpu_list_remove:
699  * @cpu: The CPU to be removed from the list of CPUs.
700  */
701 void cpu_list_remove(CPUState *cpu);
702 
703 /**
704  * cpu_reset:
705  * @cpu: The CPU whose state is to be reset.
706  */
707 void cpu_reset(CPUState *cpu);
708 
709 /**
710  * cpu_class_by_name:
711  * @typename: The CPU base type.
712  * @cpu_model: The model string without any parameters.
713  *
714  * Looks up a CPU #ObjectClass matching name @cpu_model.
715  *
716  * Returns: A #CPUClass or %NULL if not matching class is found.
717  */
718 ObjectClass *cpu_class_by_name(const char *typename, const char *cpu_model);
719 
720 /**
721  * cpu_create:
722  * @typename: The CPU type.
723  *
724  * Instantiates a CPU and realizes the CPU.
725  *
726  * Returns: A #CPUState or %NULL if an error occurred.
727  */
728 CPUState *cpu_create(const char *typename);
729 
730 /**
731  * parse_cpu_option:
732  * @cpu_option: The -cpu option including optional parameters.
733  *
734  * processes optional parameters and registers them as global properties
735  *
736  * Returns: type of CPU to create or prints error and terminates process
737  *          if an error occurred.
738  */
739 const char *parse_cpu_option(const char *cpu_option);
740 
741 /**
742  * cpu_has_work:
743  * @cpu: The vCPU to check.
744  *
745  * Checks whether the CPU has work to do.
746  *
747  * Returns: %true if the CPU has work, %false otherwise.
748  */
749 static inline bool cpu_has_work(CPUState *cpu)
750 {
751     CPUClass *cc = CPU_GET_CLASS(cpu);
752 
753     g_assert(cc->has_work);
754     return cc->has_work(cpu);
755 }
756 
757 /**
758  * qemu_cpu_is_self:
759  * @cpu: The vCPU to check against.
760  *
761  * Checks whether the caller is executing on the vCPU thread.
762  *
763  * Returns: %true if called from @cpu's thread, %false otherwise.
764  */
765 bool qemu_cpu_is_self(CPUState *cpu);
766 
767 /**
768  * qemu_cpu_kick:
769  * @cpu: The vCPU to kick.
770  *
771  * Kicks @cpu's thread.
772  */
773 void qemu_cpu_kick(CPUState *cpu);
774 
775 /**
776  * cpu_is_stopped:
777  * @cpu: The CPU to check.
778  *
779  * Checks whether the CPU is stopped.
780  *
781  * Returns: %true if run state is not running or if artificially stopped;
782  * %false otherwise.
783  */
784 bool cpu_is_stopped(CPUState *cpu);
785 
786 /**
787  * do_run_on_cpu:
788  * @cpu: The vCPU to run on.
789  * @func: The function to be executed.
790  * @data: Data to pass to the function.
791  * @mutex: Mutex to release while waiting for @func to run.
792  *
793  * Used internally in the implementation of run_on_cpu.
794  */
795 void do_run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data data,
796                    QemuMutex *mutex);
797 
798 /**
799  * run_on_cpu:
800  * @cpu: The vCPU to run on.
801  * @func: The function to be executed.
802  * @data: Data to pass to the function.
803  *
804  * Schedules the function @func for execution on the vCPU @cpu.
805  */
806 void run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data data);
807 
808 /**
809  * async_run_on_cpu:
810  * @cpu: The vCPU to run on.
811  * @func: The function to be executed.
812  * @data: Data to pass to the function.
813  *
814  * Schedules the function @func for execution on the vCPU @cpu asynchronously.
815  */
816 void async_run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data data);
817 
818 /**
819  * async_safe_run_on_cpu:
820  * @cpu: The vCPU to run on.
821  * @func: The function to be executed.
822  * @data: Data to pass to the function.
823  *
824  * Schedules the function @func for execution on the vCPU @cpu asynchronously,
825  * while all other vCPUs are sleeping.
826  *
827  * Unlike run_on_cpu and async_run_on_cpu, the function is run outside the
828  * BQL.
829  */
830 void async_safe_run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data data);
831 
832 /**
833  * cpu_in_exclusive_context()
834  * @cpu: The vCPU to check
835  *
836  * Returns true if @cpu is an exclusive context, for example running
837  * something which has previously been queued via async_safe_run_on_cpu().
838  */
839 static inline bool cpu_in_exclusive_context(const CPUState *cpu)
840 {
841     return cpu->in_exclusive_context;
842 }
843 
844 /**
845  * qemu_get_cpu:
846  * @index: The CPUState@cpu_index value of the CPU to obtain.
847  *
848  * Gets a CPU matching @index.
849  *
850  * Returns: The CPU or %NULL if there is no matching CPU.
851  */
852 CPUState *qemu_get_cpu(int index);
853 
854 /**
855  * cpu_exists:
856  * @id: Guest-exposed CPU ID to lookup.
857  *
858  * Search for CPU with specified ID.
859  *
860  * Returns: %true - CPU is found, %false - CPU isn't found.
861  */
862 bool cpu_exists(int64_t id);
863 
864 /**
865  * cpu_by_arch_id:
866  * @id: Guest-exposed CPU ID of the CPU to obtain.
867  *
868  * Get a CPU with matching @id.
869  *
870  * Returns: The CPU or %NULL if there is no matching CPU.
871  */
872 CPUState *cpu_by_arch_id(int64_t id);
873 
874 /**
875  * cpu_interrupt:
876  * @cpu: The CPU to set an interrupt on.
877  * @mask: The interrupts to set.
878  *
879  * Invokes the interrupt handler.
880  */
881 
882 void cpu_interrupt(CPUState *cpu, int mask);
883 
884 static inline void cpu_unaligned_access(CPUState *cpu, vaddr addr,
885                                         MMUAccessType access_type,
886                                         int mmu_idx, uintptr_t retaddr)
887 {
888     CPUClass *cc = CPU_GET_CLASS(cpu);
889 
890     cc->do_unaligned_access(cpu, addr, access_type, mmu_idx, retaddr);
891 }
892 
893 static inline void cpu_transaction_failed(CPUState *cpu, hwaddr physaddr,
894                                           vaddr addr, unsigned size,
895                                           MMUAccessType access_type,
896                                           int mmu_idx, MemTxAttrs attrs,
897                                           MemTxResult response,
898                                           uintptr_t retaddr)
899 {
900     CPUClass *cc = CPU_GET_CLASS(cpu);
901 
902     if (!cpu->ignore_memory_transaction_failures &&
903         cc->tcg_ops.do_transaction_failed) {
904         cc->tcg_ops.do_transaction_failed(cpu, physaddr, addr, size,
905                                           access_type, mmu_idx, attrs,
906                                           response, retaddr);
907     }
908 }
909 
910 /**
911  * cpu_set_pc:
912  * @cpu: The CPU to set the program counter for.
913  * @addr: Program counter value.
914  *
915  * Sets the program counter for a CPU.
916  */
917 static inline void cpu_set_pc(CPUState *cpu, vaddr addr)
918 {
919     CPUClass *cc = CPU_GET_CLASS(cpu);
920 
921     cc->set_pc(cpu, addr);
922 }
923 
924 /**
925  * cpu_reset_interrupt:
926  * @cpu: The CPU to clear the interrupt on.
927  * @mask: The interrupt mask to clear.
928  *
929  * Resets interrupts on the vCPU @cpu.
930  */
931 void cpu_reset_interrupt(CPUState *cpu, int mask);
932 
933 /**
934  * cpu_exit:
935  * @cpu: The CPU to exit.
936  *
937  * Requests the CPU @cpu to exit execution.
938  */
939 void cpu_exit(CPUState *cpu);
940 
941 /**
942  * cpu_resume:
943  * @cpu: The CPU to resume.
944  *
945  * Resumes CPU, i.e. puts CPU into runnable state.
946  */
947 void cpu_resume(CPUState *cpu);
948 
949 /**
950  * cpu_remove_sync:
951  * @cpu: The CPU to remove.
952  *
953  * Requests the CPU to be removed and waits till it is removed.
954  */
955 void cpu_remove_sync(CPUState *cpu);
956 
957 /**
958  * process_queued_cpu_work() - process all items on CPU work queue
959  * @cpu: The CPU which work queue to process.
960  */
961 void process_queued_cpu_work(CPUState *cpu);
962 
963 /**
964  * cpu_exec_start:
965  * @cpu: The CPU for the current thread.
966  *
967  * Record that a CPU has started execution and can be interrupted with
968  * cpu_exit.
969  */
970 void cpu_exec_start(CPUState *cpu);
971 
972 /**
973  * cpu_exec_end:
974  * @cpu: The CPU for the current thread.
975  *
976  * Record that a CPU has stopped execution and exclusive sections
977  * can be executed without interrupting it.
978  */
979 void cpu_exec_end(CPUState *cpu);
980 
981 /**
982  * start_exclusive:
983  *
984  * Wait for a concurrent exclusive section to end, and then start
985  * a section of work that is run while other CPUs are not running
986  * between cpu_exec_start and cpu_exec_end.  CPUs that are running
987  * cpu_exec are exited immediately.  CPUs that call cpu_exec_start
988  * during the exclusive section go to sleep until this CPU calls
989  * end_exclusive.
990  */
991 void start_exclusive(void);
992 
993 /**
994  * end_exclusive:
995  *
996  * Concludes an exclusive execution section started by start_exclusive.
997  */
998 void end_exclusive(void);
999 
1000 /**
1001  * qemu_init_vcpu:
1002  * @cpu: The vCPU to initialize.
1003  *
1004  * Initializes a vCPU.
1005  */
1006 void qemu_init_vcpu(CPUState *cpu);
1007 
1008 #define SSTEP_ENABLE  0x1  /* Enable simulated HW single stepping */
1009 #define SSTEP_NOIRQ   0x2  /* Do not use IRQ while single stepping */
1010 #define SSTEP_NOTIMER 0x4  /* Do not Timers while single stepping */
1011 
1012 /**
1013  * cpu_single_step:
1014  * @cpu: CPU to the flags for.
1015  * @enabled: Flags to enable.
1016  *
1017  * Enables or disables single-stepping for @cpu.
1018  */
1019 void cpu_single_step(CPUState *cpu, int enabled);
1020 
1021 /* Breakpoint/watchpoint flags */
1022 #define BP_MEM_READ           0x01
1023 #define BP_MEM_WRITE          0x02
1024 #define BP_MEM_ACCESS         (BP_MEM_READ | BP_MEM_WRITE)
1025 #define BP_STOP_BEFORE_ACCESS 0x04
1026 /* 0x08 currently unused */
1027 #define BP_GDB                0x10
1028 #define BP_CPU                0x20
1029 #define BP_ANY                (BP_GDB | BP_CPU)
1030 #define BP_WATCHPOINT_HIT_READ 0x40
1031 #define BP_WATCHPOINT_HIT_WRITE 0x80
1032 #define BP_WATCHPOINT_HIT (BP_WATCHPOINT_HIT_READ | BP_WATCHPOINT_HIT_WRITE)
1033 
1034 int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags,
1035                           CPUBreakpoint **breakpoint);
1036 int cpu_breakpoint_remove(CPUState *cpu, vaddr pc, int flags);
1037 void cpu_breakpoint_remove_by_ref(CPUState *cpu, CPUBreakpoint *breakpoint);
1038 void cpu_breakpoint_remove_all(CPUState *cpu, int mask);
1039 
1040 /* Return true if PC matches an installed breakpoint.  */
1041 static inline bool cpu_breakpoint_test(CPUState *cpu, vaddr pc, int mask)
1042 {
1043     CPUBreakpoint *bp;
1044 
1045     if (unlikely(!QTAILQ_EMPTY(&cpu->breakpoints))) {
1046         QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
1047             if (bp->pc == pc && (bp->flags & mask)) {
1048                 return true;
1049             }
1050         }
1051     }
1052     return false;
1053 }
1054 
1055 #ifdef CONFIG_USER_ONLY
1056 static inline int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
1057                                         int flags, CPUWatchpoint **watchpoint)
1058 {
1059     return -ENOSYS;
1060 }
1061 
1062 static inline int cpu_watchpoint_remove(CPUState *cpu, vaddr addr,
1063                                         vaddr len, int flags)
1064 {
1065     return -ENOSYS;
1066 }
1067 
1068 static inline void cpu_watchpoint_remove_by_ref(CPUState *cpu,
1069                                                 CPUWatchpoint *wp)
1070 {
1071 }
1072 
1073 static inline void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
1074 {
1075 }
1076 
1077 static inline void cpu_check_watchpoint(CPUState *cpu, vaddr addr, vaddr len,
1078                                         MemTxAttrs atr, int fl, uintptr_t ra)
1079 {
1080 }
1081 
1082 static inline int cpu_watchpoint_address_matches(CPUState *cpu,
1083                                                  vaddr addr, vaddr len)
1084 {
1085     return 0;
1086 }
1087 #else
1088 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
1089                           int flags, CPUWatchpoint **watchpoint);
1090 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr,
1091                           vaddr len, int flags);
1092 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint);
1093 void cpu_watchpoint_remove_all(CPUState *cpu, int mask);
1094 
1095 /**
1096  * cpu_check_watchpoint:
1097  * @cpu: cpu context
1098  * @addr: guest virtual address
1099  * @len: access length
1100  * @attrs: memory access attributes
1101  * @flags: watchpoint access type
1102  * @ra: unwind return address
1103  *
1104  * Check for a watchpoint hit in [addr, addr+len) of the type
1105  * specified by @flags.  Exit via exception with a hit.
1106  */
1107 void cpu_check_watchpoint(CPUState *cpu, vaddr addr, vaddr len,
1108                           MemTxAttrs attrs, int flags, uintptr_t ra);
1109 
1110 /**
1111  * cpu_watchpoint_address_matches:
1112  * @cpu: cpu context
1113  * @addr: guest virtual address
1114  * @len: access length
1115  *
1116  * Return the watchpoint flags that apply to [addr, addr+len).
1117  * If no watchpoint is registered for the range, the result is 0.
1118  */
1119 int cpu_watchpoint_address_matches(CPUState *cpu, vaddr addr, vaddr len);
1120 #endif
1121 
1122 /**
1123  * cpu_get_address_space:
1124  * @cpu: CPU to get address space from
1125  * @asidx: index identifying which address space to get
1126  *
1127  * Return the requested address space of this CPU. @asidx
1128  * specifies which address space to read.
1129  */
1130 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx);
1131 
1132 void QEMU_NORETURN cpu_abort(CPUState *cpu, const char *fmt, ...)
1133     GCC_FMT_ATTR(2, 3);
1134 
1135 /* $(top_srcdir)/cpu.c */
1136 void cpu_exec_initfn(CPUState *cpu);
1137 void cpu_exec_realizefn(CPUState *cpu, Error **errp);
1138 void cpu_exec_unrealizefn(CPUState *cpu);
1139 
1140 /**
1141  * target_words_bigendian:
1142  * Returns true if the (default) endianness of the target is big endian,
1143  * false otherwise. Note that in target-specific code, you can use
1144  * TARGET_WORDS_BIGENDIAN directly instead. On the other hand, common
1145  * code should normally never need to know about the endianness of the
1146  * target, so please do *not* use this function unless you know very well
1147  * what you are doing!
1148  */
1149 bool target_words_bigendian(void);
1150 
1151 #ifdef NEED_CPU_H
1152 
1153 #ifdef CONFIG_SOFTMMU
1154 extern const VMStateDescription vmstate_cpu_common;
1155 #else
1156 #define vmstate_cpu_common vmstate_dummy
1157 #endif
1158 
1159 #define VMSTATE_CPU() {                                                     \
1160     .name = "parent_obj",                                                   \
1161     .size = sizeof(CPUState),                                               \
1162     .vmsd = &vmstate_cpu_common,                                            \
1163     .flags = VMS_STRUCT,                                                    \
1164     .offset = 0,                                                            \
1165 }
1166 
1167 #endif /* NEED_CPU_H */
1168 
1169 #define UNASSIGNED_CPU_INDEX -1
1170 #define UNASSIGNED_CLUSTER_INDEX -1
1171 
1172 #endif
1173