axdevice 0.5.6

A reusable, OS-agnostic device abstraction layer designed for virtual machines.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//! Reusable LoongArch PCH-PIC device model.
//!
//! This module is a target-gated architecture device package. It provides a
//! guest-visible MMIO irqchip plus a narrow output-port service for the AxVM
//! LoongArch architecture layer; it is not part of the architecture-neutral
//! device runtime core.

use alloc::{boxed::Box, sync::Arc};
use core::sync::atomic::{AtomicUsize, Ordering};

use ax_kspin::SpinNoIrq as Mutex;
use axdevice_base::{
    AccessWidth, BusAccess, BusKind, BusResponse, Device, DeviceAccess, DeviceError, DeviceResult,
    Resource,
};
use axvm_types::{EmulatedDeviceConfig, EmulatedDeviceType, GuestPhysAddr};

use crate::{
    DeviceBuildContext, DeviceBundle, DeviceFactory, DeviceManagerResult, DeviceRegistration,
    ServiceCardinality, ServiceKey,
};
const PCH_PIC_INT_ID_LO: usize = 0x000;
const PCH_PIC_INT_ID_HI: usize = 0x004;
const PCH_PIC_INT_MASK_LO: usize = 0x020;
const PCH_PIC_INT_MASK_HI: usize = 0x024;
const PCH_PIC_HTMSI_EN_LO: usize = 0x040;
const PCH_PIC_HTMSI_EN_HI: usize = 0x044;
const PCH_PIC_INT_EDGE_LO: usize = 0x060;
const PCH_PIC_INT_EDGE_HI: usize = 0x064;
const PCH_PIC_INT_CLEAR_LO: usize = 0x080;
const PCH_PIC_INT_CLEAR_HI: usize = 0x084;
const PCH_PIC_AUTO_CTRL0_LO: usize = 0x0c0;
const PCH_PIC_AUTO_CTRL0_HI: usize = 0x0c4;
const PCH_PIC_AUTO_CTRL1_LO: usize = 0x0e0;
const PCH_PIC_AUTO_CTRL1_HI: usize = 0x0e4;
const PCH_PIC_ROUTE_ENTRY_BASE: usize = 0x100;
const PCH_PIC_HTMSI_VEC_BASE: usize = 0x200;
const PCH_PIC_INT_IRR_LO: usize = 0x380;
const PCH_PIC_INT_IRR_HI: usize = 0x384;
const PCH_PIC_INT_ISR_LO: usize = 0x3a0;
const PCH_PIC_INT_ISR_HI: usize = 0x3a4;
const PCH_PIC_POL_LO: usize = 0x3e0;
const PCH_PIC_POL_HI: usize = 0x3e4;
const PCH_PIC_IRQ_COUNT: usize = 64;
const PCH_PIC_INT_ID_VAL: usize = 0x0700_0000;
const PCH_PIC_INT_ID_VER: usize = 0x1;
const PCH_PIC_IO_LOG_LIMIT: usize = 256;
const PCH_PIC_IRQ_LOG_LIMIT: usize = 64;
const PCH_PIC_LEVEL_LOG_LIMIT: usize = 64;
const PCH_PIC_OUTPUT_QUEUE_CAPACITY: usize = 16;

static PCH_PIC_IO_LOGS: AtomicUsize = AtomicUsize::new(0);
static PCH_PIC_IRQ_LOGS: AtomicUsize = AtomicUsize::new(0);
static PCH_PIC_LEVEL_LOGS: AtomicUsize = AtomicUsize::new(0);

#[derive(Clone, Debug)]
struct PchPicState {
    int_mask: u64,
    htmsi_en: u64,
    intedge: u64,
    last_intirr: u64,
    intirr: u64,
    intisr: u64,
    int_polarity: u64,
    auto_ctrl0: u64,
    auto_ctrl1: u64,
    route_entry: [u8; PCH_PIC_IRQ_COUNT],
    htmsi_vector: [u8; PCH_PIC_IRQ_COUNT],
    output_events: [Option<PchPicOutputEvent>; PCH_PIC_OUTPUT_QUEUE_CAPACITY],
    output_head: usize,
    output_len: usize,
}

impl Default for PchPicState {
    fn default() -> Self {
        let mut state = Self {
            int_mask: !0,
            htmsi_en: 0,
            intedge: 0,
            last_intirr: 0,
            intirr: 0,
            intisr: 0,
            int_polarity: 0,
            auto_ctrl0: 0,
            auto_ctrl1: 0,
            route_entry: [0; PCH_PIC_IRQ_COUNT],
            htmsi_vector: [0; PCH_PIC_IRQ_COUNT],
            output_events: [None; PCH_PIC_OUTPUT_QUEUE_CAPACITY],
            output_head: 0,
            output_len: 0,
        };
        for irq in 0..PCH_PIC_IRQ_COUNT {
            state.route_entry[irq] = 1;
            state.htmsi_vector[irq] = irq as u8;
        }
        state
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PchPicOutputEvent {
    pub vector: usize,
    pub asserted: bool,
}

/// Architecture port through which LoongArch consumes PCH-PIC output.
///
/// The guest-visible PCH-PIC remains a normal MMIO device.  This narrow port
/// is only for the architecture to feed physical IRQs into it and to drain
/// output vectors produced by guest MMIO configuration.
pub trait PchPicOutputPort: Send + Sync {
    /// Updates one PCH-PIC input level and returns the routed EIOINTC vector.
    fn set_input_level(&self, irq: usize, asserted: bool) -> Option<usize>;

    /// Takes the next output event produced by the PCH-PIC.
    fn take_output_event(&self) -> Option<PchPicOutputEvent>;
}

/// Type key for the VM-local LoongArch PCH-PIC output port.
pub struct PchPicOutputPortKey;

impl ServiceKey for PchPicOutputPortKey {
    type Service = dyn PchPicOutputPort;

    const NAME: &'static str = "loongarch-pch-pic-output-port";
    const CARDINALITY: ServiceCardinality = ServiceCardinality::Single;
}

/// Minimal LS7A PCH-PIC model for LoongArch QEMU virt guests.
///
/// Linux configures this irqchip through ACPI even when the backing PCI devices
/// are passthrough. The model must preserve the mask/IRR/ISR/route state so the
/// guest sees a coherent interrupt controller instead of changing the host PCH.
pub struct LoongArchPchPic {
    base: GuestPhysAddr,
    size: usize,
    resources: Box<[Resource]>,
    state: Mutex<PchPicState>,
}

impl LoongArchPchPic {
    pub fn new(base: GuestPhysAddr, size: usize) -> Self {
        Self {
            base,
            size,
            resources: alloc::vec![Resource::MmioRange {
                base: base.as_usize() as u64,
                size: size as u64,
            }]
            .into_boxed_slice(),
            state: Mutex::new(PchPicState::default()),
        }
    }

    /// Updates a PCH input source level and returns the EIOINTC source to assert, if any.
    pub fn set_irq_level(&self, irq: usize, level: bool) -> Option<usize> {
        let mut state = self.state.lock();
        if irq >= PCH_PIC_IRQ_COUNT {
            return None;
        }

        let mask = 1u64 << irq;
        if level {
            state.intirr |= mask;
            state.last_intirr |= mask;
        } else {
            state.intirr &= !mask;
            state.last_intirr &= !mask;
        }

        let routed = update_irq(&mut state, mask, level);
        log_pch_pic_level(&state, irq, level, routed);
        routed
    }

    /// Returns the pending EIOINTC source for an already-latched PCH source.
    pub fn pending_vector(&self, irq: usize) -> Option<usize> {
        let mut state = self.state.lock();
        if irq >= PCH_PIC_IRQ_COUNT {
            return None;
        }

        update_irq(&mut state, 1u64 << irq, true)
    }

    /// Drains output-line events generated by MMIO register writes.
    pub fn drain_output_events(&self, mut f: impl FnMut(PchPicOutputEvent)) {
        loop {
            let event = {
                let mut state = self.state.lock();
                pop_output_event(&mut state)
            };
            match event {
                Some(event) => f(event),
                None => return,
            }
        }
    }

    fn take_output_event(&self) -> Option<PchPicOutputEvent> {
        let mut state = self.state.lock();
        pop_output_event(&mut state)
    }

    fn contains(&self, addr: GuestPhysAddr) -> bool {
        let base = self.base.as_usize();
        let end = base.saturating_add(self.size);
        let addr = addr.as_usize();
        addr >= base && addr < end
    }

    /// Reads a guest-visible PCH-PIC MMIO register.
    pub fn read_register(&self, addr: GuestPhysAddr, width: AccessWidth) -> DeviceResult<usize> {
        if !self.contains(addr) {
            return Err(DeviceError::OutOfRange {
                addr: addr.as_usize() as u64,
            });
        }
        let offset = addr.as_usize() - self.base.as_usize();
        let state = self.state.lock();
        let value = match width {
            AccessWidth::Byte => read_byte(&state, offset),
            AccessWidth::Word => read_split_bytes(&state, offset, 2),
            AccessWidth::Dword => read_dword(&state, offset),
            AccessWidth::Qword => {
                read_dword(&state, offset) | (read_dword(&state, offset + 4) << 32)
            }
        };
        log_pch_pic_io("read", offset, width, value);
        Ok(value)
    }

    /// Writes a guest-visible PCH-PIC MMIO register.
    pub fn write_register(
        &self,
        addr: GuestPhysAddr,
        width: AccessWidth,
        val: usize,
    ) -> DeviceResult {
        if !self.contains(addr) {
            return Err(DeviceError::OutOfRange {
                addr: addr.as_usize() as u64,
            });
        }
        let offset = addr.as_usize() - self.base.as_usize();
        let mut state = self.state.lock();
        log_pch_pic_io("write", offset, width, val);
        match width {
            AccessWidth::Byte => write_byte(&mut state, offset, val as u8),
            AccessWidth::Word => write_split_bytes(&mut state, offset, 2, val),
            AccessWidth::Dword => write_dword(&mut state, offset, val as u32),
            AccessWidth::Qword => {
                write_dword(&mut state, offset, val as u32);
                write_dword(&mut state, offset + 4, (val >> 32) as u32);
            }
        }
        Ok(())
    }
}

impl PchPicOutputPort for LoongArchPchPic {
    fn set_input_level(&self, irq: usize, asserted: bool) -> Option<usize> {
        self.set_irq_level(irq, asserted)
    }

    fn take_output_event(&self) -> Option<PchPicOutputEvent> {
        self.take_output_event()
    }
}

/// Factory for the guest-visible LoongArch PCH-PIC contribution.
pub struct LoongArchPchPicFactory;

impl DeviceFactory for LoongArchPchPicFactory {
    fn device_type(&self) -> EmulatedDeviceType {
        EmulatedDeviceType::LoongArchPchPic
    }

    fn build(
        &self,
        config: &EmulatedDeviceConfig,
        _context: &DeviceBuildContext<'_>,
    ) -> DeviceManagerResult<DeviceBundle> {
        let pic = Arc::new(LoongArchPchPic::new(config.base_gpa.into(), config.length));
        let device: Arc<dyn Device> = pic.clone();
        let output: Arc<dyn PchPicOutputPort> = pic;
        DeviceBundle::from_registration(DeviceRegistration::Device(device))
            .with_service::<PchPicOutputPortKey>(output)
    }
}

impl Device for LoongArchPchPic {
    fn name(&self) -> &str {
        "loongarch-pch-pic"
    }

    fn resources(&self) -> &[Resource] {
        &self.resources
    }

    fn access(
        &self,
        access: &BusAccess,
        _context: &mut dyn DeviceAccess,
    ) -> Result<BusResponse, DeviceError> {
        if access.kind != BusKind::Mmio {
            return Err(DeviceError::OutOfRange { addr: access.addr });
        }
        let addr = GuestPhysAddr::from_usize(access.addr as usize);
        if !self.contains(addr) {
            return Err(DeviceError::OutOfRange { addr: access.addr });
        }

        if access.is_read {
            self.read_register(addr, access.width)
                .map(|value| BusResponse::Read {
                    value: value as u64,
                })
        } else {
            self.write_register(addr, access.width, access.data as usize)
                .map(|_| BusResponse::Write)
        }
    }
}

fn read_byte(state: &PchPicState, offset: usize) -> usize {
    if let Some(index) = reg8_offset(offset) {
        return match index {
            PCH_PIC_ROUTE_ENTRY_BASE..=0x13f => pch_pic_irq_index(index, PCH_PIC_ROUTE_ENTRY_BASE)
                .map(|irq| state.route_entry[irq] as usize)
                .unwrap_or(0),
            PCH_PIC_HTMSI_VEC_BASE..=0x23f => pch_pic_irq_index(index, PCH_PIC_HTMSI_VEC_BASE)
                .map(|irq| state.htmsi_vector[irq] as usize)
                .unwrap_or(0),
            _ => 0,
        };
    }

    let shift = (offset & 0x3) * 8;
    (read_dword(state, offset & !0x3) >> shift) & 0xff
}

fn write_byte(state: &mut PchPicState, offset: usize, val: u8) {
    if let Some(index) = reg8_offset(offset) {
        match index {
            PCH_PIC_ROUTE_ENTRY_BASE..=0x13f => {
                if let Some(irq) = pch_pic_irq_index(index, PCH_PIC_ROUTE_ENTRY_BASE) {
                    state.route_entry[irq] = val;
                }
            }
            PCH_PIC_HTMSI_VEC_BASE..=0x23f => {
                if let Some(irq) = pch_pic_irq_index(index, PCH_PIC_HTMSI_VEC_BASE) {
                    state.htmsi_vector[irq] = val;
                }
            }
            _ => {}
        }
        return;
    }

    let aligned = offset & !0x3;
    let shift = (offset & 0x3) * 8;
    let old = read_dword(state, aligned);
    let new = (old & !(0xff << shift)) | ((val as usize) << shift);
    write_dword(state, aligned, new as u32);
}

fn read_split_bytes(state: &PchPicState, offset: usize, len: usize) -> usize {
    let mut value = 0;
    for idx in 0..len {
        value |= read_byte(state, offset + idx) << (idx * 8);
    }
    value
}

fn write_split_bytes(state: &mut PchPicState, offset: usize, len: usize, val: usize) {
    for idx in 0..len {
        write_byte(state, offset + idx, (val >> (idx * 8)) as u8);
    }
}

fn read_dword(state: &PchPicState, offset: usize) -> usize {
    match offset {
        PCH_PIC_INT_ID_LO => PCH_PIC_INT_ID_VAL,
        PCH_PIC_INT_ID_HI => PCH_PIC_INT_ID_VER | ((PCH_PIC_IRQ_COUNT - 1) << 16),
        PCH_PIC_INT_MASK_LO => state.int_mask as u32 as usize,
        PCH_PIC_INT_MASK_HI => (state.int_mask >> 32) as u32 as usize,
        PCH_PIC_HTMSI_EN_LO => state.htmsi_en as u32 as usize,
        PCH_PIC_HTMSI_EN_HI => (state.htmsi_en >> 32) as u32 as usize,
        PCH_PIC_INT_EDGE_LO => state.intedge as u32 as usize,
        PCH_PIC_INT_EDGE_HI => (state.intedge >> 32) as u32 as usize,
        PCH_PIC_AUTO_CTRL0_LO => state.auto_ctrl0 as u32 as usize,
        PCH_PIC_AUTO_CTRL0_HI => (state.auto_ctrl0 >> 32) as u32 as usize,
        PCH_PIC_AUTO_CTRL1_LO => state.auto_ctrl1 as u32 as usize,
        PCH_PIC_AUTO_CTRL1_HI => (state.auto_ctrl1 >> 32) as u32 as usize,
        PCH_PIC_INT_IRR_LO => state.intirr as u32 as usize,
        PCH_PIC_INT_IRR_HI => (state.intirr >> 32) as u32 as usize,
        PCH_PIC_INT_ISR_LO => (state.intisr & !state.int_mask) as u32 as usize,
        PCH_PIC_INT_ISR_HI => ((state.intisr & !state.int_mask) >> 32) as u32 as usize,
        PCH_PIC_POL_LO => state.int_polarity as u32 as usize,
        PCH_PIC_POL_HI => (state.int_polarity >> 32) as u32 as usize,
        PCH_PIC_ROUTE_ENTRY_BASE..=0x13f | PCH_PIC_HTMSI_VEC_BASE..=0x23f => {
            read_split_bytes(state, offset, 4)
        }
        _ => 0,
    }
}

fn write_dword(state: &mut PchPicState, offset: usize, val: u32) {
    match offset {
        PCH_PIC_INT_MASK_LO => update_int_mask(state, val, false),
        PCH_PIC_INT_MASK_HI => update_int_mask(state, val, true),
        PCH_PIC_HTMSI_EN_LO => state.htmsi_en = replace_u32(state.htmsi_en, val, false),
        PCH_PIC_HTMSI_EN_HI => state.htmsi_en = replace_u32(state.htmsi_en, val, true),
        PCH_PIC_INT_EDGE_LO => state.intedge = replace_u32(state.intedge, val, false),
        PCH_PIC_INT_EDGE_HI => state.intedge = replace_u32(state.intedge, val, true),
        PCH_PIC_INT_CLEAR_LO => clear_irq(state, val as u64),
        PCH_PIC_INT_CLEAR_HI => clear_irq(state, (val as u64) << 32),
        PCH_PIC_AUTO_CTRL0_LO => state.auto_ctrl0 = replace_u32(state.auto_ctrl0, val, false),
        PCH_PIC_AUTO_CTRL0_HI => state.auto_ctrl0 = replace_u32(state.auto_ctrl0, val, true),
        PCH_PIC_AUTO_CTRL1_LO => state.auto_ctrl1 = replace_u32(state.auto_ctrl1, val, false),
        PCH_PIC_AUTO_CTRL1_HI => state.auto_ctrl1 = replace_u32(state.auto_ctrl1, val, true),
        PCH_PIC_INT_ISR_LO => state.intisr = replace_u32(state.intisr, val, false),
        PCH_PIC_INT_ISR_HI => state.intisr = replace_u32(state.intisr, val, true),
        PCH_PIC_POL_LO => state.int_polarity = replace_u32(state.int_polarity, val, false),
        PCH_PIC_POL_HI => state.int_polarity = replace_u32(state.int_polarity, val, true),
        PCH_PIC_ROUTE_ENTRY_BASE..=0x13f | PCH_PIC_HTMSI_VEC_BASE..=0x23f => {
            write_split_bytes(state, offset, 4, val as usize)
        }
        _ => {}
    }
}

fn update_irq(state: &mut PchPicState, mask: u64, level: bool) -> Option<usize> {
    let valid_irqs = if PCH_PIC_IRQ_COUNT >= u64::BITS as usize {
        u64::MAX
    } else {
        (1u64 << PCH_PIC_IRQ_COUNT) - 1
    };
    let mask = mask & valid_irqs;
    if mask == 0 {
        return None;
    }

    if level {
        let pending = mask & state.intirr & !state.int_mask & !state.intisr;
        if pending != 0 {
            let irq = pending.trailing_zeros() as usize;
            state.intisr |= 1u64 << irq;
            log_pch_pic_irq(state, "assert", irq, level, mask);
            return Some(state.htmsi_vector[irq] as usize);
        }
    } else {
        let inactive = mask & state.intisr & !state.intirr;
        if inactive != 0 {
            let irq = inactive.trailing_zeros() as usize;
            state.intisr &= !(1u64 << irq);
            log_pch_pic_irq(state, "deassert", irq, level, mask);
            return Some(state.htmsi_vector[irq] as usize);
        }
    }

    None
}

fn pch_pic_irq_index(offset: usize, base: usize) -> Option<usize> {
    let irq = offset - base;
    (irq < PCH_PIC_IRQ_COUNT).then_some(irq)
}

fn reg8_offset(offset: usize) -> Option<usize> {
    (PCH_PIC_ROUTE_ENTRY_BASE..PCH_PIC_INT_ISR_LO)
        .contains(&offset)
        .then_some(offset)
}

fn clear_irq(state: &mut PchPicState, mask: u64) {
    let active = state.intisr & mask;
    state.intirr &= !mask;
    state.last_intirr &= !mask;
    state.intisr &= !mask;
    queue_events_for_mask(state, active, false);
}

fn update_int_mask(state: &mut PchPicState, val: u32, high: bool) {
    let old = state.int_mask;
    state.int_mask = replace_u32(old, val, high);

    let old_part = if high { old >> 32 } else { old } as u32;
    let newly_unmasked = old_part & !val;
    if newly_unmasked != 0 {
        let mask = if high {
            (newly_unmasked as u64) << 32
        } else {
            newly_unmasked as u64
        };
        if let Some(vector) = update_irq(state, mask, true) {
            push_output_event(
                state,
                PchPicOutputEvent {
                    vector,
                    asserted: true,
                },
            );
        }
    }

    let newly_masked = !old_part & val;
    if newly_masked != 0 {
        let mask = if high {
            (newly_masked as u64) << 32
        } else {
            newly_masked as u64
        };
        // Masking disconnects the PCH source from EIOINTC even if its input
        // level remains high. Keep `intirr` latched so a later unmask can
        // assert it again, but retract every output line already in service.
        let active = state.intisr & mask;
        state.intisr &= !active;
        queue_events_for_mask(state, active, false);
    }
}

fn queue_events_for_mask(state: &mut PchPicState, mut mask: u64, asserted: bool) {
    while mask != 0 {
        let irq = mask.trailing_zeros() as usize;
        push_output_event(
            state,
            PchPicOutputEvent {
                vector: state.htmsi_vector[irq] as usize,
                asserted,
            },
        );
        mask &= !(1u64 << irq);
    }
}

fn push_output_event(state: &mut PchPicState, event: PchPicOutputEvent) {
    if state.output_len == PCH_PIC_OUTPUT_QUEUE_CAPACITY {
        warn!(
            "LoongArch PCH-PIC output event queue full, dropping event {:?}",
            event
        );
        return;
    }
    let index = (state.output_head + state.output_len) % PCH_PIC_OUTPUT_QUEUE_CAPACITY;
    state.output_events[index] = Some(event);
    state.output_len += 1;
}

fn pop_output_event(state: &mut PchPicState) -> Option<PchPicOutputEvent> {
    if state.output_len == 0 {
        return None;
    }

    let event = state.output_events[state.output_head].take();
    state.output_head = (state.output_head + 1) % PCH_PIC_OUTPUT_QUEUE_CAPACITY;
    state.output_len -= 1;
    event
}

fn replace_u32(old: u64, val: u32, high: bool) -> u64 {
    if high {
        (old & 0x0000_0000_ffff_ffff) | ((val as u64) << 32)
    } else {
        (old & 0xffff_ffff_0000_0000) | val as u64
    }
}

fn log_pch_pic_io(op: &str, offset: usize, width: AccessWidth, value: usize) {
    let is_key_reg = matches!(
        offset,
        PCH_PIC_INT_MASK_LO
            | PCH_PIC_INT_MASK_HI
            | PCH_PIC_INT_CLEAR_LO
            | PCH_PIC_INT_CLEAR_HI
            | PCH_PIC_HTMSI_EN_LO
            | PCH_PIC_HTMSI_EN_HI
    );
    if is_key_reg || PCH_PIC_IO_LOGS.fetch_add(1, Ordering::Relaxed) < PCH_PIC_IO_LOG_LIMIT {
        trace!(
            "LoongArch guest PCH-PIC {op}: offset={:#x}, width={:?}, value={:#x}",
            offset, width, value
        );
    }
}

fn log_pch_pic_level(state: &PchPicState, irq: usize, level: bool, routed: Option<usize>) {
    if PCH_PIC_LEVEL_LOGS.fetch_add(1, Ordering::Relaxed) < PCH_PIC_LEVEL_LOG_LIMIT {
        trace!(
            "LoongArch guest PCH-PIC level: input={}, level={}, routed={:?}, int_mask={:#x}, \
             intirr={:#x}, intisr={:#x}, htvec={}",
            irq, level, routed, state.int_mask, state.intirr, state.intisr, state.htmsi_vector[irq]
        );
    }
}

fn log_pch_pic_irq(state: &PchPicState, op: &str, irq: usize, level: bool, mask: u64) {
    if PCH_PIC_IRQ_LOGS.fetch_add(1, Ordering::Relaxed) < PCH_PIC_IRQ_LOG_LIMIT {
        trace!(
            "LoongArch guest PCH-PIC irq {op}: input={}, level={}, mask={:#x}, int_mask={:#x}, \
             intirr={:#x}, intisr={:#x}, htvec={}",
            irq, level, mask, state.int_mask, state.intirr, state.intisr, state.htmsi_vector[irq]
        );
    }
}

#[cfg(test)]
mod tests {
    use alloc::{vec, vec::Vec};

    use super::*;

    #[test]
    fn unmask_latched_irq_emits_assert_event() {
        let pic = LoongArchPchPic::new(GuestPhysAddr::from_usize(0x1000), 0x1000);
        assert_eq!(pic.set_irq_level(5, true), None);

        pic.write_register(
            GuestPhysAddr::from_usize(0x1000 + PCH_PIC_INT_MASK_LO),
            AccessWidth::Dword,
            !(1u32 << 5) as usize,
        )
        .unwrap();

        let mut events = Vec::new();
        pic.drain_output_events(|event| events.push(event));
        assert_eq!(
            events,
            vec![PchPicOutputEvent {
                vector: 5,
                asserted: true
            }]
        );
    }

    #[test]
    fn clear_asserted_irq_emits_deassert_event() {
        let pic = LoongArchPchPic::new(GuestPhysAddr::from_usize(0x1000), 0x1000);
        pic.write_register(
            GuestPhysAddr::from_usize(0x1000 + PCH_PIC_INT_MASK_LO),
            AccessWidth::Dword,
            !(1u32 << 5) as usize,
        )
        .unwrap();
        assert_eq!(pic.set_irq_level(5, true), Some(5));

        pic.write_register(
            GuestPhysAddr::from_usize(0x1000 + PCH_PIC_INT_CLEAR_LO),
            AccessWidth::Dword,
            (1u32 << 5) as usize,
        )
        .unwrap();

        let mut events = Vec::new();
        pic.drain_output_events(|event| events.push(event));
        assert_eq!(
            events,
            vec![PchPicOutputEvent {
                vector: 5,
                asserted: false
            }]
        );
    }

    #[test]
    fn output_port_preserves_deassert_then_reassert_order() {
        let pic = LoongArchPchPic::new(GuestPhysAddr::from_usize(0x1000), 0x1000);
        let irq = 5;
        let address = GuestPhysAddr::from_usize(0x1000 + PCH_PIC_INT_MASK_LO);

        pic.write_register(address, AccessWidth::Dword, !(1u32 << irq) as usize)
            .unwrap();
        assert_eq!(pic.set_input_level(irq, true), Some(irq));

        // Masking an active level produces a deassert event. Re-enabling the
        // same still-latched source must queue a later assert, not discard it.
        pic.write_register(address, AccessWidth::Dword, usize::MAX)
            .unwrap();
        pic.write_register(address, AccessWidth::Dword, !(1u32 << irq) as usize)
            .unwrap();

        let mut events = Vec::new();
        while let Some(event) = PchPicOutputPort::take_output_event(&pic) {
            events.push(event);
        }
        assert_eq!(
            events,
            vec![
                PchPicOutputEvent {
                    vector: irq,
                    asserted: false,
                },
                PchPicOutputEvent {
                    vector: irq,
                    asserted: true,
                },
            ]
        );
    }
}