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