xref: /openbmc/qemu/include/hw/core/cpu.h (revision f1a5287f)
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/vaddr.h"
27 #include "exec/memattrs.h"
28 #include "exec/tlb-common.h"
29 #include "qapi/qapi-types-run-state.h"
30 #include "qemu/bitmap.h"
31 #include "qemu/rcu_queue.h"
32 #include "qemu/queue.h"
33 #include "qemu/thread.h"
34 #include "qemu/plugin-event.h"
35 #include "qom/object.h"
36 
37 typedef int (*WriteCoreDumpFunction)(const void *buf, size_t size,
38                                      void *opaque);
39 
40 /**
41  * SECTION:cpu
42  * @section_id: QEMU-cpu
43  * @title: CPU Class
44  * @short_description: Base class for all CPUs
45  */
46 
47 #define TYPE_CPU "cpu"
48 
49 /* Since this macro is used a lot in hot code paths and in conjunction with
50  * FooCPU *foo_env_get_cpu(), we deviate from usual QOM practice by using
51  * an unchecked cast.
52  */
53 #define CPU(obj) ((CPUState *)(obj))
54 
55 /*
56  * The class checkers bring in CPU_GET_CLASS() which is potentially
57  * expensive given the eventual call to
58  * object_class_dynamic_cast_assert(). Because of this the CPUState
59  * has a cached value for the class in cs->cc which is set up in
60  * cpu_exec_realizefn() for use in hot code paths.
61  */
62 typedef struct CPUClass CPUClass;
63 DECLARE_CLASS_CHECKERS(CPUClass, CPU,
64                        TYPE_CPU)
65 
66 /**
67  * OBJECT_DECLARE_CPU_TYPE:
68  * @CpuInstanceType: instance struct name
69  * @CpuClassType: class struct name
70  * @CPU_MODULE_OBJ_NAME: the CPU name in uppercase with underscore separators
71  *
72  * This macro is typically used in "cpu-qom.h" header file, and will:
73  *
74  *   - create the typedefs for the CPU object and class structs
75  *   - register the type for use with g_autoptr
76  *   - provide three standard type cast functions
77  *
78  * The object struct and class struct need to be declared manually.
79  */
80 #define OBJECT_DECLARE_CPU_TYPE(CpuInstanceType, CpuClassType, CPU_MODULE_OBJ_NAME) \
81     typedef struct ArchCPU CpuInstanceType; \
82     OBJECT_DECLARE_TYPE(ArchCPU, CpuClassType, CPU_MODULE_OBJ_NAME);
83 
84 typedef enum MMUAccessType {
85     MMU_DATA_LOAD  = 0,
86     MMU_DATA_STORE = 1,
87     MMU_INST_FETCH = 2
88 #define MMU_ACCESS_COUNT 3
89 } MMUAccessType;
90 
91 typedef struct CPUWatchpoint CPUWatchpoint;
92 
93 /* see accel-cpu.h */
94 struct AccelCPUClass;
95 
96 /* see sysemu-cpu-ops.h */
97 struct SysemuCPUOps;
98 
99 /**
100  * CPUClass:
101  * @class_by_name: Callback to map -cpu command line model name to an
102  *                 instantiatable CPU type.
103  * @parse_features: Callback to parse command line arguments.
104  * @reset_dump_flags: #CPUDumpFlags to use for reset logging.
105  * @has_work: Callback for checking if there is work to do.
106  * @mmu_index: Callback for choosing softmmu mmu index;
107  *       may be used internally by memory_rw_debug without TCG.
108  * @memory_rw_debug: Callback for GDB memory access.
109  * @dump_state: Callback for dumping state.
110  * @query_cpu_fast:
111  *       Fill in target specific information for the "query-cpus-fast"
112  *       QAPI call.
113  * @get_arch_id: Callback for getting architecture-dependent CPU ID.
114  * @set_pc: Callback for setting the Program Counter register. This
115  *       should have the semantics used by the target architecture when
116  *       setting the PC from a source such as an ELF file entry point;
117  *       for example on Arm it will also set the Thumb mode bit based
118  *       on the least significant bit of the new PC value.
119  *       If the target behaviour here is anything other than "set
120  *       the PC register to the value passed in" then the target must
121  *       also implement the synchronize_from_tb hook.
122  * @get_pc: Callback for getting the Program Counter register.
123  *       As above, with the semantics of the target architecture.
124  * @gdb_read_register: Callback for letting GDB read a register.
125  * @gdb_write_register: Callback for letting GDB write a register.
126  * @gdb_adjust_breakpoint: Callback for adjusting the address of a
127  *       breakpoint.  Used by AVR to handle a gdb mis-feature with
128  *       its Harvard architecture split code and data.
129  * @gdb_num_core_regs: Number of core registers accessible to GDB or 0 to infer
130  *                     from @gdb_core_xml_file.
131  * @gdb_core_xml_file: File name for core registers GDB XML description.
132  * @gdb_stop_before_watchpoint: Indicates whether GDB expects the CPU to stop
133  *           before the insn which triggers a watchpoint rather than after it.
134  * @gdb_arch_name: Optional callback that returns the architecture name known
135  * to GDB. The caller must free the returned string with g_free.
136  * @disas_set_info: Setup architecture specific components of disassembly info
137  * @adjust_watchpoint_address: Perform a target-specific adjustment to an
138  * address before attempting to match it against watchpoints.
139  * @deprecation_note: If this CPUClass is deprecated, this field provides
140  *                    related information.
141  *
142  * Represents a CPU family or model.
143  */
144 struct CPUClass {
145     /*< private >*/
146     DeviceClass parent_class;
147     /*< public >*/
148 
149     ObjectClass *(*class_by_name)(const char *cpu_model);
150     void (*parse_features)(const char *typename, char *str, Error **errp);
151 
152     bool (*has_work)(CPUState *cpu);
153     int (*mmu_index)(CPUState *cpu, bool ifetch);
154     int (*memory_rw_debug)(CPUState *cpu, vaddr addr,
155                            uint8_t *buf, int len, bool is_write);
156     void (*dump_state)(CPUState *cpu, FILE *, int flags);
157     void (*query_cpu_fast)(CPUState *cpu, CpuInfoFast *value);
158     int64_t (*get_arch_id)(CPUState *cpu);
159     void (*set_pc)(CPUState *cpu, vaddr value);
160     vaddr (*get_pc)(CPUState *cpu);
161     int (*gdb_read_register)(CPUState *cpu, GByteArray *buf, int reg);
162     int (*gdb_write_register)(CPUState *cpu, uint8_t *buf, int reg);
163     vaddr (*gdb_adjust_breakpoint)(CPUState *cpu, vaddr addr);
164 
165     const char *gdb_core_xml_file;
166     const gchar * (*gdb_arch_name)(CPUState *cpu);
167 
168     void (*disas_set_info)(CPUState *cpu, disassemble_info *info);
169 
170     const char *deprecation_note;
171     struct AccelCPUClass *accel_cpu;
172 
173     /* when system emulation is not available, this pointer is NULL */
174     const struct SysemuCPUOps *sysemu_ops;
175 
176     /* when TCG is not available, this pointer is NULL */
177     const TCGCPUOps *tcg_ops;
178 
179     /*
180      * if not NULL, this is called in order for the CPUClass to initialize
181      * class data that depends on the accelerator, see accel/accel-common.c.
182      */
183     void (*init_accel_cpu)(struct AccelCPUClass *accel_cpu, CPUClass *cc);
184 
185     /*
186      * Keep non-pointer data at the end to minimize holes.
187      */
188     int reset_dump_flags;
189     int gdb_num_core_regs;
190     bool gdb_stop_before_watchpoint;
191 };
192 
193 /*
194  * Fix the number of mmu modes to 16, which is also the maximum
195  * supported by the softmmu tlb api.
196  */
197 #define NB_MMU_MODES 16
198 
199 /* Use a fully associative victim tlb of 8 entries. */
200 #define CPU_VTLB_SIZE 8
201 
202 /*
203  * The full TLB entry, which is not accessed by generated TCG code,
204  * so the layout is not as critical as that of CPUTLBEntry. This is
205  * also why we don't want to combine the two structs.
206  */
207 typedef struct CPUTLBEntryFull {
208     /*
209      * @xlat_section contains:
210      *  - in the lower TARGET_PAGE_BITS, a physical section number
211      *  - with the lower TARGET_PAGE_BITS masked off, an offset which
212      *    must be added to the virtual address to obtain:
213      *     + the ram_addr_t of the target RAM (if the physical section
214      *       number is PHYS_SECTION_NOTDIRTY or PHYS_SECTION_ROM)
215      *     + the offset within the target MemoryRegion (otherwise)
216      */
217     hwaddr xlat_section;
218 
219     /*
220      * @phys_addr contains the physical address in the address space
221      * given by cpu_asidx_from_attrs(cpu, @attrs).
222      */
223     hwaddr phys_addr;
224 
225     /* @attrs contains the memory transaction attributes for the page. */
226     MemTxAttrs attrs;
227 
228     /* @prot contains the complete protections for the page. */
229     uint8_t prot;
230 
231     /* @lg_page_size contains the log2 of the page size. */
232     uint8_t lg_page_size;
233 
234     /*
235      * Additional tlb flags for use by the slow path. If non-zero,
236      * the corresponding CPUTLBEntry comparator must have TLB_FORCE_SLOW.
237      */
238     uint8_t slow_flags[MMU_ACCESS_COUNT];
239 
240     /*
241      * Allow target-specific additions to this structure.
242      * This may be used to cache items from the guest cpu
243      * page tables for later use by the implementation.
244      */
245     union {
246         /*
247          * Cache the attrs and shareability fields from the page table entry.
248          *
249          * For ARMMMUIdx_Stage2*, pte_attrs is the S2 descriptor bits [5:2].
250          * Otherwise, pte_attrs is the same as the MAIR_EL1 8-bit format.
251          * For shareability and guarded, as in the SH and GP fields respectively
252          * of the VMSAv8-64 PTEs.
253          */
254         struct {
255             uint8_t pte_attrs;
256             uint8_t shareability;
257             bool guarded;
258         } arm;
259     } extra;
260 } CPUTLBEntryFull;
261 
262 /*
263  * Data elements that are per MMU mode, minus the bits accessed by
264  * the TCG fast path.
265  */
266 typedef struct CPUTLBDesc {
267     /*
268      * Describe a region covering all of the large pages allocated
269      * into the tlb.  When any page within this region is flushed,
270      * we must flush the entire tlb.  The region is matched if
271      * (addr & large_page_mask) == large_page_addr.
272      */
273     vaddr large_page_addr;
274     vaddr large_page_mask;
275     /* host time (in ns) at the beginning of the time window */
276     int64_t window_begin_ns;
277     /* maximum number of entries observed in the window */
278     size_t window_max_entries;
279     size_t n_used_entries;
280     /* The next index to use in the tlb victim table.  */
281     size_t vindex;
282     /* The tlb victim table, in two parts.  */
283     CPUTLBEntry vtable[CPU_VTLB_SIZE];
284     CPUTLBEntryFull vfulltlb[CPU_VTLB_SIZE];
285     CPUTLBEntryFull *fulltlb;
286 } CPUTLBDesc;
287 
288 /*
289  * Data elements that are shared between all MMU modes.
290  */
291 typedef struct CPUTLBCommon {
292     /* Serialize updates to f.table and d.vtable, and others as noted. */
293     QemuSpin lock;
294     /*
295      * Within dirty, for each bit N, modifications have been made to
296      * mmu_idx N since the last time that mmu_idx was flushed.
297      * Protected by tlb_c.lock.
298      */
299     uint16_t dirty;
300     /*
301      * Statistics.  These are not lock protected, but are read and
302      * written atomically.  This allows the monitor to print a snapshot
303      * of the stats without interfering with the cpu.
304      */
305     size_t full_flush_count;
306     size_t part_flush_count;
307     size_t elide_flush_count;
308 } CPUTLBCommon;
309 
310 /*
311  * The entire softmmu tlb, for all MMU modes.
312  * The meaning of each of the MMU modes is defined in the target code.
313  * Since this is placed within CPUNegativeOffsetState, the smallest
314  * negative offsets are at the end of the struct.
315  */
316 typedef struct CPUTLB {
317 #ifdef CONFIG_TCG
318     CPUTLBCommon c;
319     CPUTLBDesc d[NB_MMU_MODES];
320     CPUTLBDescFast f[NB_MMU_MODES];
321 #endif
322 } CPUTLB;
323 
324 /*
325  * Low 16 bits: number of cycles left, used only in icount mode.
326  * High 16 bits: Set to -1 to force TCG to stop executing linked TBs
327  * for this CPU and return to its top level loop (even in non-icount mode).
328  * This allows a single read-compare-cbranch-write sequence to test
329  * for both decrementer underflow and exceptions.
330  */
331 typedef union IcountDecr {
332     uint32_t u32;
333     struct {
334 #if HOST_BIG_ENDIAN
335         uint16_t high;
336         uint16_t low;
337 #else
338         uint16_t low;
339         uint16_t high;
340 #endif
341     } u16;
342 } IcountDecr;
343 
344 /*
345  * Elements of CPUState most efficiently accessed from CPUArchState,
346  * via small negative offsets.
347  */
348 typedef struct CPUNegativeOffsetState {
349     CPUTLB tlb;
350     IcountDecr icount_decr;
351     bool can_do_io;
352 } CPUNegativeOffsetState;
353 
354 typedef struct CPUBreakpoint {
355     vaddr pc;
356     int flags; /* BP_* */
357     QTAILQ_ENTRY(CPUBreakpoint) entry;
358 } CPUBreakpoint;
359 
360 struct CPUWatchpoint {
361     vaddr vaddr;
362     vaddr len;
363     vaddr hitaddr;
364     MemTxAttrs hitattrs;
365     int flags; /* BP_* */
366     QTAILQ_ENTRY(CPUWatchpoint) entry;
367 };
368 
369 struct KVMState;
370 struct kvm_run;
371 
372 /* work queue */
373 
374 /* The union type allows passing of 64 bit target pointers on 32 bit
375  * hosts in a single parameter
376  */
377 typedef union {
378     int           host_int;
379     unsigned long host_ulong;
380     void         *host_ptr;
381     vaddr         target_ptr;
382 } run_on_cpu_data;
383 
384 #define RUN_ON_CPU_HOST_PTR(p)    ((run_on_cpu_data){.host_ptr = (p)})
385 #define RUN_ON_CPU_HOST_INT(i)    ((run_on_cpu_data){.host_int = (i)})
386 #define RUN_ON_CPU_HOST_ULONG(ul) ((run_on_cpu_data){.host_ulong = (ul)})
387 #define RUN_ON_CPU_TARGET_PTR(v)  ((run_on_cpu_data){.target_ptr = (v)})
388 #define RUN_ON_CPU_NULL           RUN_ON_CPU_HOST_PTR(NULL)
389 
390 typedef void (*run_on_cpu_func)(CPUState *cpu, run_on_cpu_data data);
391 
392 struct qemu_work_item;
393 
394 #define CPU_UNSET_NUMA_NODE_ID -1
395 
396 /**
397  * CPUState:
398  * @cpu_index: CPU index (informative).
399  * @cluster_index: Identifies which cluster this CPU is in.
400  *   For boards which don't define clusters or for "loose" CPUs not assigned
401  *   to a cluster this will be UNASSIGNED_CLUSTER_INDEX; otherwise it will
402  *   be the same as the cluster-id property of the CPU object's TYPE_CPU_CLUSTER
403  *   QOM parent.
404  *   Under TCG this value is propagated to @tcg_cflags.
405  *   See TranslationBlock::TCG CF_CLUSTER_MASK.
406  * @tcg_cflags: Pre-computed cflags for this cpu.
407  * @nr_cores: Number of cores within this CPU package.
408  * @nr_threads: Number of threads within this CPU core.
409  * @running: #true if CPU is currently running (lockless).
410  * @has_waiter: #true if a CPU is currently waiting for the cpu_exec_end;
411  * valid under cpu_list_lock.
412  * @created: Indicates whether the CPU thread has been successfully created.
413  * @interrupt_request: Indicates a pending interrupt request.
414  * @halted: Nonzero if the CPU is in suspended state.
415  * @stop: Indicates a pending stop request.
416  * @stopped: Indicates the CPU has been artificially stopped.
417  * @unplug: Indicates a pending CPU unplug request.
418  * @crash_occurred: Indicates the OS reported a crash (panic) for this CPU
419  * @singlestep_enabled: Flags for single-stepping.
420  * @icount_extra: Instructions until next timer event.
421  * @neg.can_do_io: True if memory-mapped IO is allowed.
422  * @cpu_ases: Pointer to array of CPUAddressSpaces (which define the
423  *            AddressSpaces this CPU has)
424  * @num_ases: number of CPUAddressSpaces in @cpu_ases
425  * @as: Pointer to the first AddressSpace, for the convenience of targets which
426  *      only have a single AddressSpace
427  * @gdb_regs: Additional GDB registers.
428  * @gdb_num_regs: Number of total registers accessible to GDB.
429  * @gdb_num_g_regs: Number of registers in GDB 'g' packets.
430  * @node: QTAILQ of CPUs sharing TB cache.
431  * @opaque: User data.
432  * @mem_io_pc: Host Program Counter at which the memory was accessed.
433  * @accel: Pointer to accelerator specific state.
434  * @kvm_fd: vCPU file descriptor for KVM.
435  * @work_mutex: Lock to prevent multiple access to @work_list.
436  * @work_list: List of pending asynchronous work.
437  * @plugin_mask: Plugin event bitmap. Modified only via async work.
438  * @ignore_memory_transaction_failures: Cached copy of the MachineState
439  *    flag of the same name: allows the board to suppress calling of the
440  *    CPU do_transaction_failed hook function.
441  * @kvm_dirty_gfns: Points to the KVM dirty ring for this CPU when KVM dirty
442  *    ring is enabled.
443  * @kvm_fetch_index: Keeps the index that we last fetched from the per-vCPU
444  *    dirty ring structure.
445  *
446  * State of one CPU core or thread.
447  *
448  * Align, in order to match possible alignment required by CPUArchState,
449  * and eliminate a hole between CPUState and CPUArchState within ArchCPU.
450  */
451 struct CPUState {
452     /*< private >*/
453     DeviceState parent_obj;
454     /* cache to avoid expensive CPU_GET_CLASS */
455     CPUClass *cc;
456     /*< public >*/
457 
458     int nr_cores;
459     int nr_threads;
460 
461     struct QemuThread *thread;
462 #ifdef _WIN32
463     QemuSemaphore sem;
464 #endif
465     int thread_id;
466     bool running, has_waiter;
467     struct QemuCond *halt_cond;
468     bool thread_kicked;
469     bool created;
470     bool stop;
471     bool stopped;
472 
473     /* Should CPU start in powered-off state? */
474     bool start_powered_off;
475 
476     bool unplug;
477     bool crash_occurred;
478     bool exit_request;
479     int exclusive_context_count;
480     uint32_t cflags_next_tb;
481     /* updates protected by BQL */
482     uint32_t interrupt_request;
483     int singlestep_enabled;
484     int64_t icount_budget;
485     int64_t icount_extra;
486     uint64_t random_seed;
487     sigjmp_buf jmp_env;
488 
489     QemuMutex work_mutex;
490     QSIMPLEQ_HEAD(, qemu_work_item) work_list;
491 
492     CPUAddressSpace *cpu_ases;
493     int num_ases;
494     AddressSpace *as;
495     MemoryRegion *memory;
496 
497     CPUJumpCache *tb_jmp_cache;
498 
499     GArray *gdb_regs;
500     int gdb_num_regs;
501     int gdb_num_g_regs;
502     QTAILQ_ENTRY(CPUState) node;
503 
504     /* ice debug support */
505     QTAILQ_HEAD(, CPUBreakpoint) breakpoints;
506 
507     QTAILQ_HEAD(, CPUWatchpoint) watchpoints;
508     CPUWatchpoint *watchpoint_hit;
509 
510     void *opaque;
511 
512     /* In order to avoid passing too many arguments to the MMIO helpers,
513      * we store some rarely used information in the CPU context.
514      */
515     uintptr_t mem_io_pc;
516 
517     /* Only used in KVM */
518     int kvm_fd;
519     struct KVMState *kvm_state;
520     struct kvm_run *kvm_run;
521     struct kvm_dirty_gfn *kvm_dirty_gfns;
522     uint32_t kvm_fetch_index;
523     uint64_t dirty_pages;
524     int kvm_vcpu_stats_fd;
525 
526     /* Use by accel-block: CPU is executing an ioctl() */
527     QemuLockCnt in_ioctl_lock;
528 
529     DECLARE_BITMAP(plugin_mask, QEMU_PLUGIN_EV_MAX);
530 
531 #ifdef CONFIG_PLUGIN
532     GArray *plugin_mem_cbs;
533 #endif
534 
535     /* TODO Move common fields from CPUArchState here. */
536     int cpu_index;
537     int cluster_index;
538     uint32_t tcg_cflags;
539     uint32_t halted;
540     int32_t exception_index;
541 
542     AccelCPUState *accel;
543     /* shared by kvm and hvf */
544     bool vcpu_dirty;
545 
546     /* Used to keep track of an outstanding cpu throttle thread for migration
547      * autoconverge
548      */
549     bool throttle_thread_scheduled;
550 
551     /*
552      * Sleep throttle_us_per_full microseconds once dirty ring is full
553      * if dirty page rate limit is enabled.
554      */
555     int64_t throttle_us_per_full;
556 
557     bool ignore_memory_transaction_failures;
558 
559     /* Used for user-only emulation of prctl(PR_SET_UNALIGN). */
560     bool prctl_unalign_sigbus;
561 
562     /* track IOMMUs whose translations we've cached in the TCG TLB */
563     GArray *iommu_notifiers;
564 
565     /*
566      * MUST BE LAST in order to minimize the displacement to CPUArchState.
567      */
568     char neg_align[-sizeof(CPUNegativeOffsetState) % 16] QEMU_ALIGNED(16);
569     CPUNegativeOffsetState neg;
570 };
571 
572 /* Validate placement of CPUNegativeOffsetState. */
573 QEMU_BUILD_BUG_ON(offsetof(CPUState, neg) !=
574                   sizeof(CPUState) - sizeof(CPUNegativeOffsetState));
575 
576 static inline CPUArchState *cpu_env(CPUState *cpu)
577 {
578     /* We validate that CPUArchState follows CPUState in cpu-all.h. */
579     return (CPUArchState *)(cpu + 1);
580 }
581 
582 typedef QTAILQ_HEAD(CPUTailQ, CPUState) CPUTailQ;
583 extern CPUTailQ cpus_queue;
584 
585 #define first_cpu        QTAILQ_FIRST_RCU(&cpus_queue)
586 #define CPU_NEXT(cpu)    QTAILQ_NEXT_RCU(cpu, node)
587 #define CPU_FOREACH(cpu) QTAILQ_FOREACH_RCU(cpu, &cpus_queue, node)
588 #define CPU_FOREACH_SAFE(cpu, next_cpu) \
589     QTAILQ_FOREACH_SAFE_RCU(cpu, &cpus_queue, node, next_cpu)
590 
591 extern __thread CPUState *current_cpu;
592 
593 /**
594  * qemu_tcg_mttcg_enabled:
595  * Check whether we are running MultiThread TCG or not.
596  *
597  * Returns: %true if we are in MTTCG mode %false otherwise.
598  */
599 extern bool mttcg_enabled;
600 #define qemu_tcg_mttcg_enabled() (mttcg_enabled)
601 
602 /**
603  * cpu_paging_enabled:
604  * @cpu: The CPU whose state is to be inspected.
605  *
606  * Returns: %true if paging is enabled, %false otherwise.
607  */
608 bool cpu_paging_enabled(const CPUState *cpu);
609 
610 /**
611  * cpu_get_memory_mapping:
612  * @cpu: The CPU whose memory mappings are to be obtained.
613  * @list: Where to write the memory mappings to.
614  * @errp: Pointer for reporting an #Error.
615  *
616  * Returns: %true on success, %false otherwise.
617  */
618 bool cpu_get_memory_mapping(CPUState *cpu, MemoryMappingList *list,
619                             Error **errp);
620 
621 #if !defined(CONFIG_USER_ONLY)
622 
623 /**
624  * cpu_write_elf64_note:
625  * @f: pointer to a function that writes memory to a file
626  * @cpu: The CPU whose memory is to be dumped
627  * @cpuid: ID number of the CPU
628  * @opaque: pointer to the CPUState struct
629  */
630 int cpu_write_elf64_note(WriteCoreDumpFunction f, CPUState *cpu,
631                          int cpuid, void *opaque);
632 
633 /**
634  * cpu_write_elf64_qemunote:
635  * @f: pointer to a function that writes memory to a file
636  * @cpu: The CPU whose memory is to be dumped
637  * @cpuid: ID number of the CPU
638  * @opaque: pointer to the CPUState struct
639  */
640 int cpu_write_elf64_qemunote(WriteCoreDumpFunction f, CPUState *cpu,
641                              void *opaque);
642 
643 /**
644  * cpu_write_elf32_note:
645  * @f: pointer to a function that writes memory to a file
646  * @cpu: The CPU whose memory is to be dumped
647  * @cpuid: ID number of the CPU
648  * @opaque: pointer to the CPUState struct
649  */
650 int cpu_write_elf32_note(WriteCoreDumpFunction f, CPUState *cpu,
651                          int cpuid, void *opaque);
652 
653 /**
654  * cpu_write_elf32_qemunote:
655  * @f: pointer to a function that writes memory to a file
656  * @cpu: The CPU whose memory is to be dumped
657  * @cpuid: ID number of the CPU
658  * @opaque: pointer to the CPUState struct
659  */
660 int cpu_write_elf32_qemunote(WriteCoreDumpFunction f, CPUState *cpu,
661                              void *opaque);
662 
663 /**
664  * cpu_get_crash_info:
665  * @cpu: The CPU to get crash information for
666  *
667  * Gets the previously saved crash information.
668  * Caller is responsible for freeing the data.
669  */
670 GuestPanicInformation *cpu_get_crash_info(CPUState *cpu);
671 
672 #endif /* !CONFIG_USER_ONLY */
673 
674 /**
675  * CPUDumpFlags:
676  * @CPU_DUMP_CODE:
677  * @CPU_DUMP_FPU: dump FPU register state, not just integer
678  * @CPU_DUMP_CCOP: dump info about TCG QEMU's condition code optimization state
679  * @CPU_DUMP_VPU: dump VPU registers
680  */
681 enum CPUDumpFlags {
682     CPU_DUMP_CODE = 0x00010000,
683     CPU_DUMP_FPU  = 0x00020000,
684     CPU_DUMP_CCOP = 0x00040000,
685     CPU_DUMP_VPU  = 0x00080000,
686 };
687 
688 /**
689  * cpu_dump_state:
690  * @cpu: The CPU whose state is to be dumped.
691  * @f: If non-null, dump to this stream, else to current print sink.
692  *
693  * Dumps CPU state.
694  */
695 void cpu_dump_state(CPUState *cpu, FILE *f, int flags);
696 
697 #ifndef CONFIG_USER_ONLY
698 /**
699  * cpu_get_phys_page_attrs_debug:
700  * @cpu: The CPU to obtain the physical page address for.
701  * @addr: The virtual address.
702  * @attrs: Updated on return with the memory transaction attributes to use
703  *         for this access.
704  *
705  * Obtains the physical page corresponding to a virtual one, together
706  * with the corresponding memory transaction attributes to use for the access.
707  * Use it only for debugging because no protection checks are done.
708  *
709  * Returns: Corresponding physical page address or -1 if no page found.
710  */
711 hwaddr cpu_get_phys_page_attrs_debug(CPUState *cpu, vaddr addr,
712                                      MemTxAttrs *attrs);
713 
714 /**
715  * cpu_get_phys_page_debug:
716  * @cpu: The CPU to obtain the physical page address for.
717  * @addr: The virtual address.
718  *
719  * Obtains the physical page corresponding to a virtual one.
720  * Use it only for debugging because no protection checks are done.
721  *
722  * Returns: Corresponding physical page address or -1 if no page found.
723  */
724 hwaddr cpu_get_phys_page_debug(CPUState *cpu, vaddr addr);
725 
726 /** cpu_asidx_from_attrs:
727  * @cpu: CPU
728  * @attrs: memory transaction attributes
729  *
730  * Returns the address space index specifying the CPU AddressSpace
731  * to use for a memory access with the given transaction attributes.
732  */
733 int cpu_asidx_from_attrs(CPUState *cpu, MemTxAttrs attrs);
734 
735 /**
736  * cpu_virtio_is_big_endian:
737  * @cpu: CPU
738 
739  * Returns %true if a CPU which supports runtime configurable endianness
740  * is currently big-endian.
741  */
742 bool cpu_virtio_is_big_endian(CPUState *cpu);
743 
744 #endif /* CONFIG_USER_ONLY */
745 
746 /**
747  * cpu_list_add:
748  * @cpu: The CPU to be added to the list of CPUs.
749  */
750 void cpu_list_add(CPUState *cpu);
751 
752 /**
753  * cpu_list_remove:
754  * @cpu: The CPU to be removed from the list of CPUs.
755  */
756 void cpu_list_remove(CPUState *cpu);
757 
758 /**
759  * cpu_reset:
760  * @cpu: The CPU whose state is to be reset.
761  */
762 void cpu_reset(CPUState *cpu);
763 
764 /**
765  * cpu_class_by_name:
766  * @typename: The CPU base type.
767  * @cpu_model: The model string without any parameters.
768  *
769  * Looks up a concrete CPU #ObjectClass matching name @cpu_model.
770  *
771  * Returns: A concrete #CPUClass or %NULL if no matching class is found
772  *          or if the matching class is abstract.
773  */
774 ObjectClass *cpu_class_by_name(const char *typename, const char *cpu_model);
775 
776 /**
777  * cpu_model_from_type:
778  * @typename: The CPU type name
779  *
780  * Extract the CPU model name from the CPU type name. The
781  * CPU type name is either the combination of the CPU model
782  * name and suffix, or same to the CPU model name.
783  *
784  * Returns: CPU model name or NULL if the CPU class doesn't exist
785  *          The user should g_free() the string once no longer needed.
786  */
787 char *cpu_model_from_type(const char *typename);
788 
789 /**
790  * cpu_create:
791  * @typename: The CPU type.
792  *
793  * Instantiates a CPU and realizes the CPU.
794  *
795  * Returns: A #CPUState or %NULL if an error occurred.
796  */
797 CPUState *cpu_create(const char *typename);
798 
799 /**
800  * parse_cpu_option:
801  * @cpu_option: The -cpu option including optional parameters.
802  *
803  * processes optional parameters and registers them as global properties
804  *
805  * Returns: type of CPU to create or prints error and terminates process
806  *          if an error occurred.
807  */
808 const char *parse_cpu_option(const char *cpu_option);
809 
810 /**
811  * cpu_has_work:
812  * @cpu: The vCPU to check.
813  *
814  * Checks whether the CPU has work to do.
815  *
816  * Returns: %true if the CPU has work, %false otherwise.
817  */
818 static inline bool cpu_has_work(CPUState *cpu)
819 {
820     CPUClass *cc = CPU_GET_CLASS(cpu);
821 
822     g_assert(cc->has_work);
823     return cc->has_work(cpu);
824 }
825 
826 /**
827  * qemu_cpu_is_self:
828  * @cpu: The vCPU to check against.
829  *
830  * Checks whether the caller is executing on the vCPU thread.
831  *
832  * Returns: %true if called from @cpu's thread, %false otherwise.
833  */
834 bool qemu_cpu_is_self(CPUState *cpu);
835 
836 /**
837  * qemu_cpu_kick:
838  * @cpu: The vCPU to kick.
839  *
840  * Kicks @cpu's thread.
841  */
842 void qemu_cpu_kick(CPUState *cpu);
843 
844 /**
845  * cpu_is_stopped:
846  * @cpu: The CPU to check.
847  *
848  * Checks whether the CPU is stopped.
849  *
850  * Returns: %true if run state is not running or if artificially stopped;
851  * %false otherwise.
852  */
853 bool cpu_is_stopped(CPUState *cpu);
854 
855 /**
856  * do_run_on_cpu:
857  * @cpu: The vCPU to run on.
858  * @func: The function to be executed.
859  * @data: Data to pass to the function.
860  * @mutex: Mutex to release while waiting for @func to run.
861  *
862  * Used internally in the implementation of run_on_cpu.
863  */
864 void do_run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data data,
865                    QemuMutex *mutex);
866 
867 /**
868  * run_on_cpu:
869  * @cpu: The vCPU to run on.
870  * @func: The function to be executed.
871  * @data: Data to pass to the function.
872  *
873  * Schedules the function @func for execution on the vCPU @cpu.
874  */
875 void run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data data);
876 
877 /**
878  * async_run_on_cpu:
879  * @cpu: The vCPU to run on.
880  * @func: The function to be executed.
881  * @data: Data to pass to the function.
882  *
883  * Schedules the function @func for execution on the vCPU @cpu asynchronously.
884  */
885 void async_run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data data);
886 
887 /**
888  * async_safe_run_on_cpu:
889  * @cpu: The vCPU to run on.
890  * @func: The function to be executed.
891  * @data: Data to pass to the function.
892  *
893  * Schedules the function @func for execution on the vCPU @cpu asynchronously,
894  * while all other vCPUs are sleeping.
895  *
896  * Unlike run_on_cpu and async_run_on_cpu, the function is run outside the
897  * BQL.
898  */
899 void async_safe_run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data data);
900 
901 /**
902  * cpu_in_exclusive_context()
903  * @cpu: The vCPU to check
904  *
905  * Returns true if @cpu is an exclusive context, for example running
906  * something which has previously been queued via async_safe_run_on_cpu().
907  */
908 static inline bool cpu_in_exclusive_context(const CPUState *cpu)
909 {
910     return cpu->exclusive_context_count;
911 }
912 
913 /**
914  * qemu_get_cpu:
915  * @index: The CPUState@cpu_index value of the CPU to obtain.
916  *
917  * Gets a CPU matching @index.
918  *
919  * Returns: The CPU or %NULL if there is no matching CPU.
920  */
921 CPUState *qemu_get_cpu(int index);
922 
923 /**
924  * cpu_exists:
925  * @id: Guest-exposed CPU ID to lookup.
926  *
927  * Search for CPU with specified ID.
928  *
929  * Returns: %true - CPU is found, %false - CPU isn't found.
930  */
931 bool cpu_exists(int64_t id);
932 
933 /**
934  * cpu_by_arch_id:
935  * @id: Guest-exposed CPU ID of the CPU to obtain.
936  *
937  * Get a CPU with matching @id.
938  *
939  * Returns: The CPU or %NULL if there is no matching CPU.
940  */
941 CPUState *cpu_by_arch_id(int64_t id);
942 
943 /**
944  * cpu_interrupt:
945  * @cpu: The CPU to set an interrupt on.
946  * @mask: The interrupts to set.
947  *
948  * Invokes the interrupt handler.
949  */
950 
951 void cpu_interrupt(CPUState *cpu, int mask);
952 
953 /**
954  * cpu_set_pc:
955  * @cpu: The CPU to set the program counter for.
956  * @addr: Program counter value.
957  *
958  * Sets the program counter for a CPU.
959  */
960 static inline void cpu_set_pc(CPUState *cpu, vaddr addr)
961 {
962     CPUClass *cc = CPU_GET_CLASS(cpu);
963 
964     cc->set_pc(cpu, addr);
965 }
966 
967 /**
968  * cpu_reset_interrupt:
969  * @cpu: The CPU to clear the interrupt on.
970  * @mask: The interrupt mask to clear.
971  *
972  * Resets interrupts on the vCPU @cpu.
973  */
974 void cpu_reset_interrupt(CPUState *cpu, int mask);
975 
976 /**
977  * cpu_exit:
978  * @cpu: The CPU to exit.
979  *
980  * Requests the CPU @cpu to exit execution.
981  */
982 void cpu_exit(CPUState *cpu);
983 
984 /**
985  * cpu_resume:
986  * @cpu: The CPU to resume.
987  *
988  * Resumes CPU, i.e. puts CPU into runnable state.
989  */
990 void cpu_resume(CPUState *cpu);
991 
992 /**
993  * cpu_remove_sync:
994  * @cpu: The CPU to remove.
995  *
996  * Requests the CPU to be removed and waits till it is removed.
997  */
998 void cpu_remove_sync(CPUState *cpu);
999 
1000 /**
1001  * process_queued_cpu_work() - process all items on CPU work queue
1002  * @cpu: The CPU which work queue to process.
1003  */
1004 void process_queued_cpu_work(CPUState *cpu);
1005 
1006 /**
1007  * cpu_exec_start:
1008  * @cpu: The CPU for the current thread.
1009  *
1010  * Record that a CPU has started execution and can be interrupted with
1011  * cpu_exit.
1012  */
1013 void cpu_exec_start(CPUState *cpu);
1014 
1015 /**
1016  * cpu_exec_end:
1017  * @cpu: The CPU for the current thread.
1018  *
1019  * Record that a CPU has stopped execution and exclusive sections
1020  * can be executed without interrupting it.
1021  */
1022 void cpu_exec_end(CPUState *cpu);
1023 
1024 /**
1025  * start_exclusive:
1026  *
1027  * Wait for a concurrent exclusive section to end, and then start
1028  * a section of work that is run while other CPUs are not running
1029  * between cpu_exec_start and cpu_exec_end.  CPUs that are running
1030  * cpu_exec are exited immediately.  CPUs that call cpu_exec_start
1031  * during the exclusive section go to sleep until this CPU calls
1032  * end_exclusive.
1033  */
1034 void start_exclusive(void);
1035 
1036 /**
1037  * end_exclusive:
1038  *
1039  * Concludes an exclusive execution section started by start_exclusive.
1040  */
1041 void end_exclusive(void);
1042 
1043 /**
1044  * qemu_init_vcpu:
1045  * @cpu: The vCPU to initialize.
1046  *
1047  * Initializes a vCPU.
1048  */
1049 void qemu_init_vcpu(CPUState *cpu);
1050 
1051 #define SSTEP_ENABLE  0x1  /* Enable simulated HW single stepping */
1052 #define SSTEP_NOIRQ   0x2  /* Do not use IRQ while single stepping */
1053 #define SSTEP_NOTIMER 0x4  /* Do not Timers while single stepping */
1054 
1055 /**
1056  * cpu_single_step:
1057  * @cpu: CPU to the flags for.
1058  * @enabled: Flags to enable.
1059  *
1060  * Enables or disables single-stepping for @cpu.
1061  */
1062 void cpu_single_step(CPUState *cpu, int enabled);
1063 
1064 /* Breakpoint/watchpoint flags */
1065 #define BP_MEM_READ           0x01
1066 #define BP_MEM_WRITE          0x02
1067 #define BP_MEM_ACCESS         (BP_MEM_READ | BP_MEM_WRITE)
1068 #define BP_STOP_BEFORE_ACCESS 0x04
1069 /* 0x08 currently unused */
1070 #define BP_GDB                0x10
1071 #define BP_CPU                0x20
1072 #define BP_ANY                (BP_GDB | BP_CPU)
1073 #define BP_HIT_SHIFT          6
1074 #define BP_WATCHPOINT_HIT_READ  (BP_MEM_READ << BP_HIT_SHIFT)
1075 #define BP_WATCHPOINT_HIT_WRITE (BP_MEM_WRITE << BP_HIT_SHIFT)
1076 #define BP_WATCHPOINT_HIT       (BP_MEM_ACCESS << BP_HIT_SHIFT)
1077 
1078 int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags,
1079                           CPUBreakpoint **breakpoint);
1080 int cpu_breakpoint_remove(CPUState *cpu, vaddr pc, int flags);
1081 void cpu_breakpoint_remove_by_ref(CPUState *cpu, CPUBreakpoint *breakpoint);
1082 void cpu_breakpoint_remove_all(CPUState *cpu, int mask);
1083 
1084 /* Return true if PC matches an installed breakpoint.  */
1085 static inline bool cpu_breakpoint_test(CPUState *cpu, vaddr pc, int mask)
1086 {
1087     CPUBreakpoint *bp;
1088 
1089     if (unlikely(!QTAILQ_EMPTY(&cpu->breakpoints))) {
1090         QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
1091             if (bp->pc == pc && (bp->flags & mask)) {
1092                 return true;
1093             }
1094         }
1095     }
1096     return false;
1097 }
1098 
1099 #if defined(CONFIG_USER_ONLY)
1100 static inline int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
1101                                         int flags, CPUWatchpoint **watchpoint)
1102 {
1103     return -ENOSYS;
1104 }
1105 
1106 static inline int cpu_watchpoint_remove(CPUState *cpu, vaddr addr,
1107                                         vaddr len, int flags)
1108 {
1109     return -ENOSYS;
1110 }
1111 
1112 static inline void cpu_watchpoint_remove_by_ref(CPUState *cpu,
1113                                                 CPUWatchpoint *wp)
1114 {
1115 }
1116 
1117 static inline void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
1118 {
1119 }
1120 #else
1121 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
1122                           int flags, CPUWatchpoint **watchpoint);
1123 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr,
1124                           vaddr len, int flags);
1125 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint);
1126 void cpu_watchpoint_remove_all(CPUState *cpu, int mask);
1127 #endif
1128 
1129 /**
1130  * cpu_plugin_mem_cbs_enabled() - are plugin memory callbacks enabled?
1131  * @cs: CPUState pointer
1132  *
1133  * The memory callbacks are installed if a plugin has instrumented an
1134  * instruction for memory. This can be useful to know if you want to
1135  * force a slow path for a series of memory accesses.
1136  */
1137 static inline bool cpu_plugin_mem_cbs_enabled(const CPUState *cpu)
1138 {
1139 #ifdef CONFIG_PLUGIN
1140     return !!cpu->plugin_mem_cbs;
1141 #else
1142     return false;
1143 #endif
1144 }
1145 
1146 /**
1147  * cpu_get_address_space:
1148  * @cpu: CPU to get address space from
1149  * @asidx: index identifying which address space to get
1150  *
1151  * Return the requested address space of this CPU. @asidx
1152  * specifies which address space to read.
1153  */
1154 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx);
1155 
1156 G_NORETURN void cpu_abort(CPUState *cpu, const char *fmt, ...)
1157     G_GNUC_PRINTF(2, 3);
1158 
1159 /* $(top_srcdir)/cpu.c */
1160 void cpu_class_init_props(DeviceClass *dc);
1161 void cpu_exec_initfn(CPUState *cpu);
1162 bool cpu_exec_realizefn(CPUState *cpu, Error **errp);
1163 void cpu_exec_unrealizefn(CPUState *cpu);
1164 void cpu_exec_reset_hold(CPUState *cpu);
1165 
1166 /**
1167  * target_words_bigendian:
1168  * Returns true if the (default) endianness of the target is big endian,
1169  * false otherwise. Note that in target-specific code, you can use
1170  * TARGET_BIG_ENDIAN directly instead. On the other hand, common
1171  * code should normally never need to know about the endianness of the
1172  * target, so please do *not* use this function unless you know very well
1173  * what you are doing!
1174  */
1175 bool target_words_bigendian(void);
1176 
1177 const char *target_name(void);
1178 
1179 void page_size_init(void);
1180 
1181 #ifdef NEED_CPU_H
1182 
1183 #ifndef CONFIG_USER_ONLY
1184 
1185 extern const VMStateDescription vmstate_cpu_common;
1186 
1187 #define VMSTATE_CPU() {                                                     \
1188     .name = "parent_obj",                                                   \
1189     .size = sizeof(CPUState),                                               \
1190     .vmsd = &vmstate_cpu_common,                                            \
1191     .flags = VMS_STRUCT,                                                    \
1192     .offset = 0,                                                            \
1193 }
1194 #endif /* !CONFIG_USER_ONLY */
1195 
1196 #endif /* NEED_CPU_H */
1197 
1198 #define UNASSIGNED_CPU_INDEX -1
1199 #define UNASSIGNED_CLUSTER_INDEX -1
1200 
1201 #endif
1202