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