xref: /openbmc/qemu/include/hw/core/cpu.h (revision 80f034c5)
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  * CPUNegativeOffsetState: Elements of CPUState most efficiently accessed
343  *                         from CPUArchState, via small negative offsets.
344  * @can_do_io: True if memory-mapped IO is allowed.
345  * @plugin_mem_cbs: active plugin memory callbacks
346  */
347 typedef struct CPUNegativeOffsetState {
348     CPUTLB tlb;
349 #ifdef CONFIG_PLUGIN
350     /*
351      * The callback pointer are accessed via TCG (see gen_empty_mem_helper).
352      */
353     GArray *plugin_mem_cbs;
354 #endif
355     IcountDecr icount_decr;
356     bool can_do_io;
357 } CPUNegativeOffsetState;
358 
359 struct KVMState;
360 struct kvm_run;
361 
362 /* work queue */
363 
364 /* The union type allows passing of 64 bit target pointers on 32 bit
365  * hosts in a single parameter
366  */
367 typedef union {
368     int           host_int;
369     unsigned long host_ulong;
370     void         *host_ptr;
371     vaddr         target_ptr;
372 } run_on_cpu_data;
373 
374 #define RUN_ON_CPU_HOST_PTR(p)    ((run_on_cpu_data){.host_ptr = (p)})
375 #define RUN_ON_CPU_HOST_INT(i)    ((run_on_cpu_data){.host_int = (i)})
376 #define RUN_ON_CPU_HOST_ULONG(ul) ((run_on_cpu_data){.host_ulong = (ul)})
377 #define RUN_ON_CPU_TARGET_PTR(v)  ((run_on_cpu_data){.target_ptr = (v)})
378 #define RUN_ON_CPU_NULL           RUN_ON_CPU_HOST_PTR(NULL)
379 
380 typedef void (*run_on_cpu_func)(CPUState *cpu, run_on_cpu_data data);
381 
382 struct qemu_work_item;
383 
384 #define CPU_UNSET_NUMA_NODE_ID -1
385 
386 /**
387  * CPUState:
388  * @cpu_index: CPU index (informative).
389  * @cluster_index: Identifies which cluster this CPU is in.
390  *   For boards which don't define clusters or for "loose" CPUs not assigned
391  *   to a cluster this will be UNASSIGNED_CLUSTER_INDEX; otherwise it will
392  *   be the same as the cluster-id property of the CPU object's TYPE_CPU_CLUSTER
393  *   QOM parent.
394  *   Under TCG this value is propagated to @tcg_cflags.
395  *   See TranslationBlock::TCG CF_CLUSTER_MASK.
396  * @tcg_cflags: Pre-computed cflags for this cpu.
397  * @nr_cores: Number of cores within this CPU package.
398  * @nr_threads: Number of threads within this CPU core.
399  * @running: #true if CPU is currently running (lockless).
400  * @has_waiter: #true if a CPU is currently waiting for the cpu_exec_end;
401  * valid under cpu_list_lock.
402  * @created: Indicates whether the CPU thread has been successfully created.
403  * @interrupt_request: Indicates a pending interrupt request.
404  * @halted: Nonzero if the CPU is in suspended state.
405  * @stop: Indicates a pending stop request.
406  * @stopped: Indicates the CPU has been artificially stopped.
407  * @unplug: Indicates a pending CPU unplug request.
408  * @crash_occurred: Indicates the OS reported a crash (panic) for this CPU
409  * @singlestep_enabled: Flags for single-stepping.
410  * @icount_extra: Instructions until next timer event.
411  * @cpu_ases: Pointer to array of CPUAddressSpaces (which define the
412  *            AddressSpaces this CPU has)
413  * @num_ases: number of CPUAddressSpaces in @cpu_ases
414  * @as: Pointer to the first AddressSpace, for the convenience of targets which
415  *      only have a single AddressSpace
416  * @gdb_regs: Additional GDB registers.
417  * @gdb_num_regs: Number of total registers accessible to GDB.
418  * @gdb_num_g_regs: Number of registers in GDB 'g' packets.
419  * @node: QTAILQ of CPUs sharing TB cache.
420  * @opaque: User data.
421  * @mem_io_pc: Host Program Counter at which the memory was accessed.
422  * @accel: Pointer to accelerator specific state.
423  * @kvm_fd: vCPU file descriptor for KVM.
424  * @work_mutex: Lock to prevent multiple access to @work_list.
425  * @work_list: List of pending asynchronous work.
426  * @plugin_state: per-CPU plugin state
427  * @ignore_memory_transaction_failures: Cached copy of the MachineState
428  *    flag of the same name: allows the board to suppress calling of the
429  *    CPU do_transaction_failed hook function.
430  * @kvm_dirty_gfns: Points to the KVM dirty ring for this CPU when KVM dirty
431  *    ring is enabled.
432  * @kvm_fetch_index: Keeps the index that we last fetched from the per-vCPU
433  *    dirty ring structure.
434  *
435  * State of one CPU core or thread.
436  *
437  * Align, in order to match possible alignment required by CPUArchState,
438  * and eliminate a hole between CPUState and CPUArchState within ArchCPU.
439  */
440 struct CPUState {
441     /*< private >*/
442     DeviceState parent_obj;
443     /* cache to avoid expensive CPU_GET_CLASS */
444     CPUClass *cc;
445     /*< public >*/
446 
447     int nr_cores;
448     int nr_threads;
449 
450     struct QemuThread *thread;
451 #ifdef _WIN32
452     QemuSemaphore sem;
453 #endif
454     int thread_id;
455     bool running, has_waiter;
456     struct QemuCond *halt_cond;
457     bool thread_kicked;
458     bool created;
459     bool stop;
460     bool stopped;
461 
462     /* Should CPU start in powered-off state? */
463     bool start_powered_off;
464 
465     bool unplug;
466     bool crash_occurred;
467     bool exit_request;
468     int exclusive_context_count;
469     uint32_t cflags_next_tb;
470     /* updates protected by BQL */
471     uint32_t interrupt_request;
472     int singlestep_enabled;
473     int64_t icount_budget;
474     int64_t icount_extra;
475     uint64_t random_seed;
476     sigjmp_buf jmp_env;
477 
478     QemuMutex work_mutex;
479     QSIMPLEQ_HEAD(, qemu_work_item) work_list;
480 
481     CPUAddressSpace *cpu_ases;
482     int num_ases;
483     AddressSpace *as;
484     MemoryRegion *memory;
485 
486     CPUJumpCache *tb_jmp_cache;
487 
488     GArray *gdb_regs;
489     int gdb_num_regs;
490     int gdb_num_g_regs;
491     QTAILQ_ENTRY(CPUState) node;
492 
493     /* ice debug support */
494     QTAILQ_HEAD(, CPUBreakpoint) breakpoints;
495 
496     QTAILQ_HEAD(, CPUWatchpoint) watchpoints;
497     CPUWatchpoint *watchpoint_hit;
498 
499     void *opaque;
500 
501     /* In order to avoid passing too many arguments to the MMIO helpers,
502      * we store some rarely used information in the CPU context.
503      */
504     uintptr_t mem_io_pc;
505 
506     /* Only used in KVM */
507     int kvm_fd;
508     struct KVMState *kvm_state;
509     struct kvm_run *kvm_run;
510     struct kvm_dirty_gfn *kvm_dirty_gfns;
511     uint32_t kvm_fetch_index;
512     uint64_t dirty_pages;
513     int kvm_vcpu_stats_fd;
514     bool vcpu_dirty;
515 
516     /* Use by accel-block: CPU is executing an ioctl() */
517     QemuLockCnt in_ioctl_lock;
518 
519 #ifdef CONFIG_PLUGIN
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_get_address_space:
1117  * @cpu: CPU to get address space from
1118  * @asidx: index identifying which address space to get
1119  *
1120  * Return the requested address space of this CPU. @asidx
1121  * specifies which address space to read.
1122  */
1123 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx);
1124 
1125 G_NORETURN void cpu_abort(CPUState *cpu, const char *fmt, ...)
1126     G_GNUC_PRINTF(2, 3);
1127 
1128 /* $(top_srcdir)/cpu.c */
1129 void cpu_class_init_props(DeviceClass *dc);
1130 void cpu_exec_initfn(CPUState *cpu);
1131 bool cpu_exec_realizefn(CPUState *cpu, Error **errp);
1132 void cpu_exec_unrealizefn(CPUState *cpu);
1133 void cpu_exec_reset_hold(CPUState *cpu);
1134 
1135 const char *target_name(void);
1136 
1137 #ifdef COMPILING_PER_TARGET
1138 
1139 #ifndef CONFIG_USER_ONLY
1140 
1141 extern const VMStateDescription vmstate_cpu_common;
1142 
1143 #define VMSTATE_CPU() {                                                     \
1144     .name = "parent_obj",                                                   \
1145     .size = sizeof(CPUState),                                               \
1146     .vmsd = &vmstate_cpu_common,                                            \
1147     .flags = VMS_STRUCT,                                                    \
1148     .offset = 0,                                                            \
1149 }
1150 #endif /* !CONFIG_USER_ONLY */
1151 
1152 #endif /* COMPILING_PER_TARGET */
1153 
1154 #define UNASSIGNED_CPU_INDEX -1
1155 #define UNASSIGNED_CLUSTER_INDEX -1
1156 
1157 #endif
1158