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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Infrastructure to support line interrupts.

#![warn(missing_docs)]

use inspect::Inspect;
use parking_lot::Mutex;
use std::borrow::Cow;
use std::collections::btree_map::Entry;
use std::collections::BTreeMap;
use std::fmt::Debug;
use std::fmt::Display;
use std::ops::RangeInclusive;
use std::sync::Arc;
use thiserror::Error;

/// An error occurred while creating a new line interrupt.
#[derive(Debug, Error)]
pub enum NewLineError {
    /// The line interrupt has been shared too many times.
    #[error("irq {0} has been shared too many times")]
    TooMany(u32),
}

/// Unless you're implementing an interrupt controller (e.g: the PIC, IOAPIC),
/// you shouldn't be using this trait!
///
/// **NOTE: Individual devices should not use this trait directly!**
///
/// Devices are expected to use [`LineInterrupt`], which decouples the details
/// of IRQ numbers and assignment from concrete device implementations.
///
/// The alternative, where devices get handed an interface that allows them to
/// assert arbitrary IRQ lines, can lead to multiple devices inadvertently
/// trampling on one another's IRQ lines if you're not careful.
pub trait LineSetTarget: Send + Sync {
    /// Set an interrupt line state.
    fn set_irq(&self, vector: u32, high: bool);
}

#[derive(Debug)]
struct Line {
    debug_label: Cow<'static, str>,
    is_high: bool,
}

impl Line {
    fn new(debug_label: Cow<'static, str>) -> Self {
        Self {
            debug_label,
            is_high: false,
        }
    }
}

struct Target {
    debug_label: Arc<str>,
    inner: Arc<dyn LineSetTarget>,
    vector: u32,
}

impl Debug for Target {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Target")
            .field("debug_label", &self.debug_label)
            .field("vector", &self.vector)
            .finish()
    }
}

#[derive(Debug)]
struct LineInterruptInner {
    targets: Vec<Target>,
    lines: BTreeMap<u8, Line>,
    fresh_line_key: u8,
    vector: u32,
}

impl Display for LineInterruptInner {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "targets[")?;
        for (i, target) in self.targets.iter().enumerate() {
            if i != 0 {
                write!(f, ",")?;
            }
            write!(f, "{}({})", target.debug_label, target.vector)?;
        }
        write!(f, "],lines[")?;
        for (i, (_, line)) in self.lines.iter().enumerate() {
            if i != 0 {
                write!(f, ",")?;
            }
            write!(f, "{}({})", line.debug_label, line.is_high)?;
        }
        write!(f, "]")?;
        Ok(())
    }
}

impl Inspect for LineInterruptInner {
    fn inspect(&self, req: inspect::Request<'_>) {
        req.respond()
            .child("targets", |req| {
                let mut resp = req.respond();
                for target in self.targets.iter() {
                    resp.field(target.debug_label.as_ref(), target.vector);
                }
            })
            .child("lines", |req| {
                let mut resp = req.respond();
                for (_, line) in self.lines.iter() {
                    resp.field(&line.debug_label, line.is_high);
                }
            });
    }
}

impl LineInterruptInner {
    fn new(debug_label: Cow<'static, str>, vector: u32, targets: Vec<Target>) -> Self {
        Self {
            targets,
            lines: [(0, Line::new(debug_label))].into_iter().collect(),
            fresh_line_key: 1,
            vector,
        }
    }

    fn add_line(&mut self, debug_label: Cow<'static, str>) -> Option<u8> {
        const MAX_SHARED: usize = 16; // arbitrary choice
        if self.lines.len() >= MAX_SHARED {
            return None;
        }

        let line_key = self.fresh_line_key;
        // this loop would only go off in the unlikely case that a single
        // LineInterrupt is being constantly shared + dropped in a loop, and
        // is bounded to MAX_SHARED iterations.
        self.fresh_line_key = self.fresh_line_key.wrapping_add(1);
        while self.lines.contains_key(&self.fresh_line_key) {
            self.fresh_line_key = self.fresh_line_key.wrapping_add(1);
        }

        let existing = self.lines.insert(line_key, Line::new(debug_label));
        assert!(existing.is_none());

        Some(line_key)
    }
}

/// A line interrupt, representing a (virtually) physical wire between a device
/// and an interrupt controller.
//
// DEVNOTE: while it's tempting to provide an `impl Clone` for this type which
// returns a new LineInterrupt that gets OR'd with the existing LineInterrupt,
// doing so would violate the principle of least surprise, as the `Clone` trait
// in Rust isn't supposed to change the semantics of the underlying type. This
// could become a problem if, say, the LineInterrupt was stored in a `Vec` which
// was absentmindedly cloned.
pub struct LineInterrupt {
    inner: Arc<Mutex<LineInterruptInner>>,
    line_key: u8,
}

impl Debug for LineInterrupt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LineInterrupt")
            .field("line_key", &self.line_key)
            .field("inner", &*self.inner.lock())
            .finish()
    }
}

impl Display for LineInterrupt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.inner.lock(), f)
    }
}

impl Inspect for LineInterrupt {
    fn inspect(&self, req: inspect::Request<'_>) {
        let inner = self.inner.lock();
        let line = inner
            .lines
            .get(&self.line_key)
            .expect("line_key is always valid");

        req.respond()
            .field("debug_label", line.debug_label.as_ref())
            .field("is_high", line.is_high)
            .child("targets", |req| {
                let mut resp = req.respond();
                for target in inner.targets.iter() {
                    resp.field(target.debug_label.as_ref(), target.vector);
                }
            });
    }
}

impl LineInterrupt {
    /// Creates a line that is not attached to any line set or target.
    ///
    /// This is useful for testing purposes.
    pub fn detached() -> Self {
        Self {
            inner: Arc::new(Mutex::new(LineInterruptInner {
                targets: Vec::new(),
                lines: [(0, Line::new("detached".into()))].into_iter().collect(),
                fresh_line_key: 1,
                vector: 0,
            })),
            line_key: 0,
        }
    }

    /// Creates a new line interrupt associated with provided target.
    ///
    /// This is a shorthand helper method for:
    ///
    /// ```rust
    /// # use vmcore::line_interrupt::*;
    /// # let f = || -> Result<LineInterrupt, NewLineError> {
    /// # let (label, target, vector) = ("", todo!(), 0);
    /// let set = LineSet::new();
    /// set.add_target(0..=0, vector, "target", target);
    /// set.new_line(0, label)
    /// # };
    /// ```
    pub fn new_with_target(
        debug_label: impl Into<Cow<'static, str>>,
        target: Arc<dyn LineSetTarget>,
        vector: u32,
    ) -> LineInterrupt {
        let set = LineSet::new();
        let debug_label = debug_label.into();
        set.add_target(0..=0, vector, debug_label.as_ref(), target);
        set.new_line(0, debug_label).unwrap()
    }

    /// Creates a new line interrupt sharing the same vector.
    pub fn new_shared(
        &self,
        debug_label: impl Into<Cow<'static, str>>,
    ) -> Result<Self, NewLineError> {
        let mut inner = self.inner.lock();
        let line_key = inner
            .add_line(debug_label.into())
            .ok_or(NewLineError::TooMany(inner.vector))?;

        Ok(Self {
            inner: self.inner.clone(),
            line_key,
        })
    }

    /// Sets the line level high or low.
    pub fn set_level(&self, high: bool) {
        let mut inner = self.inner.lock();
        inner
            .lines
            .get_mut(&self.line_key)
            .expect("line_key is always valid")
            .is_high = high;

        let is_high = inner.lines.iter().any(|(_, line)| line.is_high);

        if is_high && inner.targets.is_empty() {
            tracelimit::warn_ratelimited!(%inner, "LineInterrupt not hooked up to any targets!");
        }

        for target in inner.targets.iter() {
            target.inner.set_irq(target.vector, is_high);
        }
    }
}

impl Drop for LineInterrupt {
    fn drop(&mut self) {
        // make sure to deassert the line if this was the last shared line that
        // was being asserted.
        self.set_level(false);

        let mut inner = self.inner.lock();
        inner
            .lines
            .remove(&self.line_key)
            .expect("line_key is always valid");
    }
}

/// A set of line interrupts and their target mappings.
#[derive(Inspect)]
pub struct LineSet {
    #[inspect(flatten)]
    state: Mutex<LineSetState>,
}

#[derive(Inspect, Default)]
struct LineSetState {
    #[inspect(with = "inspect_mappings")]
    targets: Vec<TargetMapping>,
    #[inspect(iter_by_key)]
    lines: BTreeMap<u32, Arc<Mutex<LineInterruptInner>>>,
}

#[derive(Clone)]
struct TargetMapping {
    source_range: RangeInclusive<u32>,
    target_start: u32,
    debug_label: Arc<str>,
    target: Arc<dyn LineSetTarget>,
}

fn inspect_mappings(mappings: &[TargetMapping]) -> impl '_ + Inspect {
    inspect::iter_by_key(mappings.iter().map(|mapping| {
        (
            format!(
                "{}:{}-{}",
                mapping.debug_label,
                mapping.target_start,
                mapping.target_start + (mapping.source_range.end() - mapping.source_range.start())
            ),
            format!(
                "{}-{}",
                mapping.source_range.start(),
                mapping.source_range.end(),
            ),
        )
    }))
}

impl LineSet {
    /// Creates a new line set.
    pub fn new() -> Self {
        Self {
            state: Default::default(),
        }
    }

    /// Adds a target mapping to the set.
    ///
    /// The mapping is over a portion of the line set as specified by
    /// `source_range`, and it is mapped into the target's vector space starting
    /// at `target_start`.
    pub fn add_target(
        &self,
        source_range: RangeInclusive<u32>,
        target_start: u32,
        debug_label: impl Into<Arc<str>>,
        target: Arc<dyn LineSetTarget>,
    ) {
        let debug_label = debug_label.into();
        let mut state = self.state.lock();
        // Add this target to any existing lines that overlap with
        // `source_range`.
        for (&vector, line) in &mut state.lines {
            if source_range.contains(&vector) {
                let target_vector = vector - source_range.start() + target_start;
                let is_high = {
                    let mut line = line.lock();
                    line.targets.push(Target {
                        debug_label: debug_label.clone(),
                        inner: target.clone(),
                        vector: target_vector,
                    });
                    line.lines.iter().any(|(_, line)| line.is_high)
                };
                if is_high {
                    target.set_irq(target_vector, true);
                }
            }
        }
        state.targets.push(TargetMapping {
            source_range,
            target_start,
            target,
            debug_label,
        });
    }

    /// Adds a new line interrupt to the set.
    pub fn new_line(
        &self,
        vector: u32,
        debug_label: impl Into<Cow<'static, str>>,
    ) -> Result<LineInterrupt, NewLineError> {
        self.new_line_(vector, debug_label.into())
    }

    fn new_line_(
        &self,
        vector: u32,
        debug_label: Cow<'static, str>,
    ) -> Result<LineInterrupt, NewLineError> {
        let mut state = self.state.lock();
        let state = &mut *state;
        let line = match state.lines.entry(vector) {
            Entry::Occupied(entry) => {
                let inner = entry.get();
                let line_key = inner
                    .lock()
                    .add_line(debug_label)
                    .ok_or(NewLineError::TooMany(vector))?;

                LineInterrupt {
                    inner: inner.clone(),
                    line_key,
                }
            }
            Entry::Vacant(entry) => {
                let inner = Arc::new(Mutex::new(LineInterruptInner::new(
                    debug_label,
                    vector,
                    state
                        .targets
                        .iter()
                        .filter(|&mapping| mapping.source_range.contains(&vector))
                        .map(|mapping| Target {
                            debug_label: mapping.debug_label.clone(),
                            inner: mapping.target.clone(),
                            vector: vector - mapping.source_range.start() + mapping.target_start,
                        })
                        .collect(),
                )));
                entry.insert(inner.clone());
                LineInterrupt { inner, line_key: 0 }
            }
        };
        Ok(line)
    }
}

#[allow(missing_docs)] // self explanatory struct/functions
pub mod test_helpers {
    use crate::line_interrupt::LineSetTarget;
    use parking_lot::Mutex;
    use std::collections::BTreeMap;
    use std::sync::Arc;
    use std::task::Context;
    use std::task::Poll;
    use std::task::Waker;

    pub struct TestLineInterruptTarget {
        state: Mutex<BTreeMap<u32, LineState>>,
    }

    #[derive(Default)]
    struct LineState {
        is_high: bool,
        waker: Option<Waker>,
    }

    impl TestLineInterruptTarget {
        pub fn new_arc() -> Arc<TestLineInterruptTarget> {
            Arc::new(TestLineInterruptTarget {
                state: Default::default(),
            })
        }

        pub fn is_high(&self, vector: u32) -> bool {
            self.state.lock().get(&vector).map_or(false, |s| s.is_high)
        }

        pub fn poll_high(&self, cx: &mut Context<'_>, vector: u32) -> Poll<()> {
            let mut state = self.state.lock();
            let state = state.get_mut(&vector).unwrap();
            if state.is_high {
                Poll::Ready(())
            } else {
                state.waker = Some(cx.waker().clone());
                Poll::Pending
            }
        }
    }

    impl LineSetTarget for TestLineInterruptTarget {
        fn set_irq(&self, vector: u32, high: bool) {
            let mut state = self.state.lock();
            let state = &mut state.entry(vector).or_default();
            state.is_high = high;
            if high {
                if let Some(waker) = state.waker.take() {
                    waker.wake();
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::line_interrupt::test_helpers::TestLineInterruptTarget;

    #[test]
    fn basic() {
        let intcon = TestLineInterruptTarget::new_arc();

        let line0 = LineInterrupt::new_with_target("line0", intcon.clone(), 0);
        let line1 = LineInterrupt::new_with_target("line1", intcon.clone(), 1);

        line0.set_level(true);
        assert!(intcon.is_high(0));
        line0.set_level(false);
        assert!(!intcon.is_high(0));

        line1.set_level(true);
        assert!(intcon.is_high(1));
        line1.set_level(false);
        assert!(!intcon.is_high(1));
    }

    #[test]
    fn multi_target() {
        let intcon1 = TestLineInterruptTarget::new_arc();
        let intcon2 = TestLineInterruptTarget::new_arc();

        let line_set = LineSet::new();

        let line = line_set.new_line(2, "line").unwrap();

        line_set.add_target(1..=5, 7, "intcon1", intcon1.clone());
        line.set_level(true);
        line_set.add_target(2..=2, 3, "intcon2", intcon2.clone());

        assert!(intcon1.is_high(8));
        assert!(intcon2.is_high(3));
    }

    #[test]
    fn shared_line() {
        let intcon = TestLineInterruptTarget::new_arc();

        let line_set = LineSet::new();
        line_set.add_target(0..=0, 0, "intcon", intcon.clone());

        let line00 = line_set.new_line(0, "line00").unwrap();
        let line01 = line_set.new_line(0, "line01").unwrap();

        line00.set_level(true);
        assert!(intcon.is_high(0));
        line01.set_level(true);
        assert!(intcon.is_high(0));
        line00.set_level(false);
        assert!(intcon.is_high(0)); // still high, since line01 is still asserting
        line01.set_level(false);
        assert!(!intcon.is_high(0)); // finally low
    }

    #[test]
    fn drop_impl() {
        let intcon = TestLineInterruptTarget::new_arc();

        let line_set = LineSet::new();
        line_set.add_target(0..=0, 0, "intcon", intcon.clone());

        let line00 = line_set.new_line(0, "line00").unwrap();
        let line01 = line_set.new_line(0, "line01").unwrap();

        line00.set_level(true);
        assert!(intcon.is_high(0));
        line01.set_level(true);
        assert!(intcon.is_high(0));
        line00.set_level(false);
        assert!(intcon.is_high(0)); // still high, since line01 is still asserting
        drop(line01);
        assert!(!intcon.is_high(0)); // low, because line01 disappeared
    }

    #[test]
    fn share_drop_loop() {
        let intcon = TestLineInterruptTarget::new_arc();

        let line_set = LineSet::new();
        line_set.add_target(0..=0, 0, "intcon", intcon.clone());

        let _line00 = line_set.new_line(0, "line00").unwrap();

        for _ in 0..1000 {
            let line01 = line_set.new_line(0, "line01").unwrap();
            line01.set_level(true);
            assert!(intcon.is_high(0));
            drop(line01);
            assert!(!intcon.is_high(0));
        }
    }
}