drmkit-present 0.1.2

The present spine for drmkit: scanout slot pools, damage accumulation, and frame pacing.
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
// SPDX-FileCopyrightText: (c) 2026 Joel Winarske
// SPDX-License-Identifier: MIT

//! Parity port of `tests/integration/test_scanout_backend_vkms.cpp` from
//! drm-cxx @ `4a0b64a`.
//!
//! End to end: discover the output, negotiate, allocate through a GBM
//! producer, build the single-layer scene, and commit. These modeset, so they
//! take DRM master and run one at a time.

use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::{Mutex, MutexGuard};

use drmkit_core::{AtomicCommitFlags, Device};
use drmkit_present::{BackendConfig, GbmScanoutProducer, RestorePolicy, ScanoutBackend, VrrPolicy};
use drmkit_scene::{
    AcquiredBuffer, BindingModel, DmaBufDesc, LayerBufferSource, SourceError, SourceFormat,
};
use drmkit_sync::SyncFence;

static CARD_LOCK: Mutex<()> = Mutex::new(());

/// The default configuration, on the output `DRMKIT_TEST_CONNECTORS` names
/// when it is set.
fn backend_config() -> BackendConfig {
    BackendConfig {
        connector_id: std::env::var_os("DRMKIT_TEST_CONNECTORS")
            .and_then(|_| open_card_for_names())
            .unwrap_or(0),
        ..BackendConfig::default()
    }
}

/// The named connector's id, looked up on its own descriptor so the config can
/// be built before the case opens the card.
fn open_card_for_names() -> Option<u32> {
    let path = std::env::var("DRMKIT_TEST_CARD").unwrap_or_else(|_| "/dev/dri/card0".to_owned());
    drmkit_testkit::connector::wanted(&Device::open(&path).ok()?)
}

fn card_guard() -> MutexGuard<'static, ()> {
    CARD_LOCK
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

fn open_card() -> Option<Device> {
    let path = std::env::var("DRMKIT_TEST_CARD").unwrap_or_else(|_| "/dev/dri/card0".to_owned());
    drmkit_testkit::announce_card(&path);
    let device = match Device::open(&path) {
        Ok(device) => device,
        Err(error) => {
            assert!(
                std::env::var_os("DRMKIT_REQUIRE_MASTER").is_none(),
                "{path}: {error}, but DRMKIT_REQUIRE_MASTER is set"
            );
            drmkit_testkit::skipped(&format!("no DRM device at {path} ({error})"));
            return None;
        }
    };
    device.enable_universal_planes().ok()?;
    device.enable_atomic().ok()?;
    if device.set_master().is_err() {
        assert!(
            std::env::var_os("DRMKIT_REQUIRE_MASTER").is_none(),
            "not DRM master, but DRMKIT_REQUIRE_MASTER is set"
        );
        drmkit_testkit::skipped("another client holds DRM master");
        return None;
    }
    Some(device)
}

/// The backend finds the output, allocates through the producer, and puts a
/// full-screen layer on a plane.
#[test]
#[ignore = "needs a DRM device and DRM master"]
fn a_full_screen_layer_reaches_a_plane_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };

    let mut producer = GbmScanoutProducer::new(&device);
    let mut backend = match ScanoutBackend::create(&device, &mut producer, &backend_config()) {
        Ok(backend) => backend,
        Err(error) => {
            drmkit_testkit::skipped(&format!("no scanout output here ({error})"));
            return;
        }
    };

    // The profile names the driver the device reports: vkms in the lane,
    // whatever drives the card on hardware.
    let driver = drm::Device::get_driver(&device).expect("the driver's name");
    assert_eq!(backend.profile().name, driver.name().to_string_lossy());
    assert_ne!(
        backend.target().primary_plane_id,
        0,
        "a target with no primary plane cannot scan anything out"
    );
    assert!(
        drmkit_modeset::ModeInfo::width(&backend.target().mode) > 0,
        "a zero-width mode is not something to scan out"
    );

    let report = backend
        .present(&device, AtomicCommitFlags::empty(), None)
        .expect("present the first frame");

    assert!(report.layers_total >= 1);
    assert!(
        report.layers_assigned >= 1,
        "the full-screen layer must land on a plane, not be composited"
    );
    assert!(!report.skipped_idle, "an unconditional present never skips");
}

/// An unchanged frame is suppressed; the first one never is.
///
/// The first frame commits whatever the caller says, because nothing is on
/// screen yet -- "unchanged" describes nothing, and suppressing it would leave
/// the scanout contents undefined.
#[test]
#[ignore = "needs a DRM device and DRM master"]
fn an_unchanged_frame_is_suppressed_but_never_the_first_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };

    let mut producer = GbmScanoutProducer::new(&device);
    let mut backend = match ScanoutBackend::create(&device, &mut producer, &backend_config()) {
        Ok(backend) => backend,
        Err(error) => {
            drmkit_testkit::skipped(&format!("no scanout output here ({error})"));
            return;
        }
    };

    let first = backend
        .present_if_changed(&device, false, AtomicCommitFlags::empty(), None)
        .expect("the first frame commits regardless");
    assert!(!first.skipped_idle, "the first frame is never suppressed");
    assert!(first.layers_assigned >= 1);

    let idle = backend
        .present_if_changed(&device, false, AtomicCommitFlags::empty(), None)
        .expect("a suppressed frame is not a failure");
    assert!(idle.skipped_idle);
    assert_eq!(
        idle.layers_total, 0,
        "there was no commit, so there is nothing to count"
    );
    assert!(idle.placements.is_empty());

    let changed = backend
        .present_if_changed(&device, true, AtomicCommitFlags::empty(), None)
        .expect("a changed frame commits again");
    assert!(!changed.skipped_idle);
    assert!(changed.layers_assigned >= 1);

    assert_eq!(backend.frames_committed(), 2);
    assert_eq!(backend.frames_skipped(), 1);
}

/// The caller's out-fence is filled in on a CRTC that advertises
/// `OUT_FENCE_PTR`.
///
/// Asserted on the second frame, not the first: the first brings the CRTC up
/// and the fence is for the steady-state flip, which is the case a producer
/// waits on instead of blocking until the flip event.
#[test]
#[ignore = "needs a DRM device and DRM master"]
fn a_commit_delivers_its_out_fence_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };

    let mut producer = GbmScanoutProducer::new(&device);
    let mut backend = match ScanoutBackend::create(&device, &mut producer, &backend_config()) {
        Ok(backend) => backend,
        Err(error) => {
            drmkit_testkit::skipped(&format!("no scanout output here ({error})"));
            return;
        }
    };

    let mut first_fence = None;
    backend
        .present(&device, AtomicCommitFlags::empty(), Some(&mut first_fence))
        .expect("the modeset frame");

    let mut flip_fence = None;
    backend
        .present(&device, AtomicCommitFlags::empty(), Some(&mut flip_fence))
        .expect("the steady-state frame");

    assert!(
        flip_fence.is_some(),
        "this CRTC advertises OUT_FENCE_PTR, so the caller must get the fence"
    );
}

/// `Auto` takes variable refresh from the driver profile, and the resulting
/// commit still lands.
///
/// Arming `VRR_ENABLED` is a mode change on most drivers, so the transition
/// needs `ALLOW_MODESET` even though the mode itself is already set. A backend
/// that did not add it would commit cleanly until the first toggle and then
/// fail with `EINVAL` -- which is why each toggle here is followed by a frame.
///
/// **What this cannot prove on vkms.** Its `VRR_ENABLED` accepts the change on
/// a plain commit, so dropping `ALLOW_MODESET` passes every assertion here --
/// verified by injecting exactly that. Catching it needs a controller with
/// real variable refresh. Recorded as P-30.
#[test]
#[ignore = "needs a DRM device and DRM master"]
fn variable_refresh_arms_from_the_profile_and_toggles_cleanly_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };

    let mut producer = GbmScanoutProducer::new(&device);
    let config = BackendConfig {
        vrr: VrrPolicy::Auto,
        ..backend_config()
    };
    let mut backend = match ScanoutBackend::create(&device, &mut producer, &config) {
        Ok(backend) => backend,
        Err(error) => {
            drmkit_testkit::skipped(&format!("no scanout output here ({error})"));
            return;
        }
    };

    assert_eq!(
        backend.vrr_capable(),
        backend.profile().vrr_capable,
        "what Auto decided from must be what the caller can read back"
    );

    backend
        .present(&device, AtomicCommitFlags::empty(), None)
        .expect("present with VRR as Auto chose it");

    backend.set_vrr(false);
    backend
        .present(&device, AtomicCommitFlags::empty(), None)
        .expect("present with VRR disarmed");

    backend.set_vrr(true);
    backend
        .present(&device, AtomicCommitFlags::empty(), None)
        .expect("present with VRR re-armed");
}

/// `SavedCrtc` puts back the CRTC that was there before, on teardown.
///
/// Observed through the legacy CRTC framebuffer, because that is what the
/// restore writes: the backend's own commits are atomic and never touch that
/// field, so this drives it with legacy modesets. Establish a known
/// framebuffer, build the backend (which snapshots it), disable the CRTC, then
/// drop the backend and see the original come back.
///
/// This pins the connector: injecting an empty list into the legacy `set_crtc`
/// fails it, which is the failure that found the bug. It does **not** pin the
/// scene-before-restore ordering -- removing that drop passes here, since vkms
/// does not refuse a modeset against a framebuffer still referenced. P-30.
#[test]
#[ignore = "needs a DRM device and DRM master"]
fn a_saved_crtc_is_put_back_on_teardown_vkms() {
    use drm::control::Device as _;

    let _guard = card_guard();
    let Some(device) = open_card() else { return };

    let resources = device.resource_handles().expect("resources");
    // The output DRMKIT_TEST_CONNECTORS names, where set, and a CRTC its
    // encoders can drive: the first CRTC is not one on hardware with more
    // than one (vc4's HDMI is not on the first).
    let wanted = drmkit_testkit::connector::wanted(&device);
    let Some((connector, crtc, mode)) = resources.connectors().iter().find_map(|handle| {
        if wanted.is_some_and(|id| id != u32::from(*handle)) {
            return None;
        }
        let connector = device.get_connector(*handle, false).ok()?;
        if connector.state() != drm::control::connector::State::Connected {
            return None;
        }
        let mode = *connector.modes().first()?;
        let crtc = connector.encoders().iter().find_map(|encoder| {
            let encoder = device.get_encoder(*encoder).ok()?;
            resources
                .filter_crtcs(encoder.possible_crtcs())
                .first()
                .copied()
        })?;
        Some((*handle, crtc, mode))
    }) else {
        drmkit_testkit::skipped("no connected connector with a mode");
        return;
    };

    // Stand in for the prior on-screen contents, the way fbcon would.
    let buffer = drmkit_dumb::Buffer::create(
        &device,
        &drmkit_dumb::Config {
            width: u32::from(mode.size().0),
            height: u32::from(mode.size().1),
            fourcc: drmkit_fmt::fourcc::XRGB8888,
            ..drmkit_dumb::Config::default()
        },
    )
    .expect("a stand-in framebuffer");
    let original = buffer.fb_id().expect("its fb id");

    device
        .set_crtc(
            crtc,
            drm::control::framebuffer::Handle::from(
                std::num::NonZeroU32::new(original).expect("non-zero"),
            )
            .into(),
            (0, 0),
            &[connector],
            Some(mode),
        )
        .expect("establish a known CRTC configuration");

    let restored = {
        let mut producer = GbmScanoutProducer::new(&device);
        let config = BackendConfig {
            restore: RestorePolicy::SavedCrtc,
            ..backend_config()
        };
        let backend = match ScanoutBackend::create(&device, &mut producer, &config) {
            Ok(backend) => backend,
            Err(error) => {
                drmkit_testkit::skipped(&format!("no scanout output here ({error})"));
                return;
            }
        };

        // Take the CRTC down, so a backend that restored nothing leaves it down.
        device
            .set_crtc(crtc, None, (0, 0), &[], None)
            .expect("disable the CRTC");
        assert_eq!(
            device.get_crtc(crtc).expect("read it back").framebuffer(),
            None,
            "the CRTC must actually be down before teardown, or this proves nothing"
        );

        drop(backend);
        device.get_crtc(crtc).expect("read it back").framebuffer()
    };

    assert_eq!(
        restored.map(u32::from),
        Some(original),
        "teardown must put back the framebuffer that was on screen at create"
    );

    let _ = device.set_crtc(crtc, None, (0, 0), &[], None);
}

/// What a source saw as it dropped: the CRTC's vblank sequence, `None` where
/// the CRTC has no counter, and whether the flip event was queued by then.
type Teardown = (Option<u64>, bool);

/// Wraps a producer's sources so each records the CRTC's vblank sequence at
/// the moment it is dropped -- which is when its buffer and framebuffer go.
struct SeqOnDrop<'a> {
    inner: GbmScanoutProducer<'a>,
    fd: std::os::fd::RawFd,
    crtc_id: Rc<Cell<u32>>,
    seqs: Rc<RefCell<Vec<Teardown>>>,
}

impl drmkit_present::ScanoutProducer for SeqOnDrop<'_> {
    fn exportable_modifiers(&mut self, fourcc: u32) -> Vec<u64> {
        self.inner.exportable_modifiers(fourcc)
    }

    fn create_buffer(
        &mut self,
        width: u32,
        height: u32,
        fourcc: u32,
        allowed: &[u64],
    ) -> Result<Box<dyn LayerBufferSource>, drmkit_present::ProducerError> {
        let inner = self.inner.create_buffer(width, height, fourcc, allowed)?;
        Ok(Box::new(SeqSource {
            inner,
            fd: self.fd,
            crtc_id: Rc::clone(&self.crtc_id),
            seqs: Rc::clone(&self.seqs),
        }))
    }
}

struct SeqSource {
    inner: Box<dyn LayerBufferSource>,
    fd: std::os::fd::RawFd,
    crtc_id: Rc<Cell<u32>>,
    seqs: Rc<RefCell<Vec<Teardown>>>,
}

impl Drop for SeqSource {
    fn drop(&mut self) {
        // Runs before `inner` drops, so this is the sequence the buffer and
        // its framebuffer are torn down at, and whether the flip event was
        // queued by then: a driver that completes the flip inside the commit
        // (the SA8155P) has moved the sequence before it is first read.
        //
        // SAFETY: the test's device outlives the backend, and so this source.
        let fd = unsafe { std::os::fd::BorrowedFd::borrow_raw(self.fd) };
        // `None` where the CRTC has no vblank counter (a `panel-mipi-dbi`
        // panel): the queued event is then the only witness.
        let seq = drmkit_core::crtc_sequence(&fd, self.crtc_id.get()).ok();
        let queued = drmkit_core::event_pending(&fd);
        self.seqs.borrow_mut().push((seq, queued));
    }
}

impl LayerBufferSource for SeqSource {
    fn acquire(&mut self) -> Result<AcquiredBuffer, SourceError> {
        self.inner.acquire()
    }

    fn release(&mut self, acquired: AcquiredBuffer) {
        self.inner.release(acquired);
    }

    fn release_with_fence(&mut self, acquired: AcquiredBuffer, fence: Option<SyncFence>) {
        self.inner.release_with_fence(acquired, fence);
    }

    fn wants_release_fence(&self) -> bool {
        self.inner.wants_release_fence()
    }

    fn has_fresh_content(&self) -> bool {
        self.inner.has_fresh_content()
    }

    fn on_retired(&mut self) {
        self.inner.on_retired();
    }

    fn binding_model(&self) -> BindingModel {
        self.inner.binding_model()
    }

    fn format(&self) -> SourceFormat {
        self.inner.format()
    }

    fn map(
        &mut self,
        access: drmkit_dumb::MapAccess,
    ) -> Result<drmkit_dumb::Mapping<'_>, SourceError> {
        self.inner.map(access)
    }

    fn export_dma_buf(&mut self) -> Result<DmaBufDesc<'_>, SourceError> {
        self.inner.export_dma_buf()
    }

    fn bind_to_plane(&mut self, plane_id: u32) -> Result<(), SourceError> {
        self.inner.bind_to_plane(plane_id)
    }

    fn unbind_from_plane(&mut self, plane_id: u32) {
        self.inner.unbind_from_plane(plane_id);
    }

    fn on_session_paused(&mut self) {
        self.inner.on_session_paused();
    }

    fn on_session_resumed(&mut self, device: &Device) -> Result<(), SourceError> {
        self.inner.on_session_resumed(device)
    }
}

/// Dropping the backend with a flip still armed waits for it to land.
///
/// Port of `LayerSceneReleaseVkms.DestructorWaitsForArmedFlip` (`debd061`),
/// on the owner of the scene: the scene itself holds no device to wait on.
/// The caller neither dispatches the event nor calls `flip_landed`. The
/// layer's source must be torn down after the armed vblank, and the event
/// must still be queued, because the wait never reads the event queue.
///
/// Upstream reads the sequence when the scene hands each buffer back. The
/// port's scene hands nothing back at teardown -- it drops its sources, and
/// their buffers with them -- so the sequence is read as the source drops.
/// Reading it after the whole drop returns instead would prove nothing: the
/// framebuffer still on screen is removed on the way out, and the kernel's
/// disable commit for that waits out a vblank of its own.
#[test]
#[ignore = "needs a DRM device and DRM master"]
fn dropping_the_backend_waits_for_the_armed_flip_vkms() {
    drop_with_a_flip_armed(AtomicCommitFlags::PAGE_FLIP_EVENT | AtomicCommitFlags::NONBLOCK);
}

/// As above, after a blocking commit, as upstream's case commits.
///
/// A driver that completes the flip inside the commit (the SA8155P) has
/// already moved the CRTC's sequence when the backend reads it, and does not
/// move it again until the next commit, so a wait that watched only the
/// sequence ran to its 100 ms bound on every teardown. The queued event ends
/// it (drm-cxx `42287bd`). On vkms the sequence keeps counting, so this passes
/// either way there; the SA8155P's DP-4 is where it fails without the event.
#[test]
#[ignore = "needs a DRM device and DRM master"]
fn dropping_the_backend_after_a_blocking_flip_ends_the_wait_vkms() {
    drop_with_a_flip_armed(AtomicCommitFlags::PAGE_FLIP_EVENT);
}

fn drop_with_a_flip_armed(flags: AtomicCommitFlags) {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicU32, Ordering};
    use std::time::{Duration, Instant};

    use drmkit_modeset::{PageFlip, Timeout};

    let _guard = card_guard();
    let Some(device) = open_card() else { return };

    let crtc_id = Rc::new(Cell::new(0));
    let seqs = Rc::new(RefCell::new(Vec::new()));
    let mut producer = SeqOnDrop {
        inner: GbmScanoutProducer::new(&device),
        fd: device.raw_fd(),
        crtc_id: Rc::clone(&crtc_id),
        seqs: Rc::clone(&seqs),
    };
    let mut backend = match ScanoutBackend::create(&device, &mut producer, &backend_config()) {
        Ok(backend) => backend,
        Err(error) => {
            drmkit_testkit::skipped(&format!("no scanout output here ({error})"));
            return;
        }
    };
    crtc_id.set(backend.target().crtc.id);

    let mut flip = PageFlip::new(&device).expect("page flip");
    let flips = Arc::new(AtomicU32::new(0));
    let counted = Arc::clone(&flips);
    flip.set_handler(Box::new(move |_| {
        counted.fetch_add(1, Ordering::Relaxed);
    }));

    // The modeset, with no event, then the frame whose flip is left armed.
    backend
        .present(&device, AtomicCommitFlags::empty(), None)
        .expect("modeset frame");
    backend.present(&device, flags, None).expect("armed frame");
    // Unreadable on a CRTC with no vblank counter, where only the queued
    // event can say the flip landed.
    let armed = drmkit_core::crtc_sequence(&device, crtc_id.get()).ok();
    seqs.borrow_mut().clear();

    let started = Instant::now();
    drop(backend); // no dispatch, no flip_landed
    let took = started.elapsed();

    let seqs = seqs.borrow();
    assert!(!seqs.is_empty(), "teardown should drop the layer's source");
    for (seq, queued) in seqs.iter() {
        let passed = armed.zip(*seq).is_some_and(|(armed, seq)| seq > armed);
        assert!(
            passed || *queued,
            "a buffer was torn down before the flip landed ({seq:?} vs {armed:?}, no event queued)"
        );
    }
    // Before its 100 ms bound, not at it: on a driver that lands the flip
    // inside the commit the sequence never passes `armed`, and a wait that
    // watched only the sequence ran to the bound every time (drm-cxx
    // `42287bd`).
    assert!(
        took < Duration::from_millis(100),
        "the wait must end when the flip lands, took {took:?}"
    );
    flip.dispatch(Timeout::Bounded(Duration::from_millis(500)))
        .expect("dispatch");
    assert_eq!(
        flips.load(Ordering::Relaxed),
        1,
        "the wait must leave the event queued for the caller"
    );
}

/// `Config::connector_id` pins the output the backend drives (drm-cxx
/// `882dbf8`), whichever connector the kernel lists first.
#[test]
#[ignore = "needs a DRM device and DRM master"]
fn a_pinned_connector_is_the_output_driven_vkms() {
    use drm::control::Device as _;

    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let resources = device.resource_handles().expect("resources");
    let Some(last) = resources
        .connectors()
        .iter()
        .filter(|handle| {
            device.get_connector(**handle, false).is_ok_and(|info| {
                info.state() == drm::control::connector::State::Connected
                    && !info.modes().is_empty()
            })
        })
        .map(|handle| u32::from(*handle))
        .next_back()
    else {
        drmkit_testkit::skipped("no display attached");
        return;
    };

    let mut producer = GbmScanoutProducer::new(&device);
    let config = BackendConfig {
        connector_id: last,
        ..backend_config()
    };
    let backend = match ScanoutBackend::create(&device, &mut producer, &config) {
        Ok(backend) => backend,
        Err(error) => {
            drmkit_testkit::skipped(&format!("no scanout output here ({error})"));
            return;
        }
    };
    assert_eq!(backend.target().connector_id, last);
}

/// The GBM producer honors the negotiated set: `LINEAR`, or no constraint,
/// allocates; a set it can make nothing in is refused, not ignored (drm-cxx
/// `f5bed8f`). Port of `GbmProducerHonorsAllowedModifiers`.
#[test]
#[ignore = "needs a DRM device"]
fn the_gbm_producer_honors_the_allowed_modifiers_vkms() {
    use drmkit_present::ScanoutProducer as _;

    const LINEAR: u64 = 0;
    // I915_FORMAT_MOD_X_TILED: a layout vkms's allocator cannot make.
    const X_TILED: u64 = (1 << 56) | 1;
    const INVALID: u64 = (1 << 56) - 1;

    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let mut producer = GbmScanoutProducer::new(&device);
    let xrgb = drmkit_fmt::fourcc::XRGB8888;
    // The producer registers a framebuffer for each buffer, so ask for one
    // the device frames: a `panel-mipi-dbi` panel takes only its mode's size.
    let (w, h) = drmkit_testkit::framebuffer::size(&device, 64, 64);

    for allowed in [&[][..], &[LINEAR], &[X_TILED, LINEAR]] {
        let source = producer
            .create_buffer(w, h, xrgb, allowed)
            .unwrap_or_else(|error| panic!("{allowed:?}: {error}"));
        // INVALID is a driver without the modifier entry point reporting no
        // explicit layout for the buffer it fell back to (CI's Mesa does).
        let modifier = source.format().modifier;
        assert!(
            allowed.is_empty() || allowed.contains(&modifier) || modifier == INVALID,
            "{allowed:?} allocated {modifier:#x}"
        );
    }
    let refused = producer.create_buffer(w, h, xrgb, &[X_TILED]);
    assert!(
        matches!(refused, Err(drmkit_present::ProducerError::Unsupported)),
        "a set the producer can make nothing in must be refused: {:?}",
        refused.map(|source| source.format().modifier)
    );
}

/// A damaged frame reaches the kernel with its clips, where the driver takes
/// them.
///
/// `FB_DAMAGE_CLIPS` is a blob the request names by id, so it has to outlive
/// the commit. The backend emits inside the closure `commit_with_out_fence`
/// commits after, and a blob dropped at the end of that closure is destroyed
/// before the ioctl: the kernel then refuses every damaged frame with `EINVAL`
/// (P-49). vkms exposes the property on no plane, so there it pins only that
/// nothing claims a clip; the refusal needs a driver that takes damage, first
/// seen on a `panel-mipi-dbi` panel.
#[test]
#[ignore = "needs a DRM device and DRM master"]
fn a_damaged_frame_reaches_the_kernel_with_its_clips_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let takes_damage = drmkit_display::DriverProfile::probe(&device)
        .map(|profile| profile.fb_damage_clips)
        .unwrap_or(false);

    let mut producer = Damaging {
        inner: GbmScanoutProducer::new(&device),
    };
    let mut backend = match ScanoutBackend::create(&device, &mut producer, &backend_config()) {
        Ok(backend) => backend,
        Err(error) => {
            drmkit_testkit::skipped(&format!("no scanout output here ({error})"));
            return;
        }
    };

    let mut damaged = 0;
    for frame in 0..4 {
        let report = backend
            .present(&device, AtomicCommitFlags::empty(), None)
            .unwrap_or_else(|error| panic!("damaged frame {frame}: {error}"));
        damaged += report.damaged_layers;
    }

    if takes_damage {
        assert!(
            damaged > 0,
            "this driver takes FB_DAMAGE_CLIPS, so the frames' damage must reach it"
        );
    } else {
        assert_eq!(
            damaged, 0,
            "the driver takes no damage property, so nothing should claim a clip"
        );
    }
}

/// Wraps a producer's sources so every buffer reports a small dirty region.
struct Damaging<'a> {
    inner: GbmScanoutProducer<'a>,
}

impl drmkit_present::ScanoutProducer for Damaging<'_> {
    fn exportable_modifiers(&mut self, fourcc: u32) -> Vec<u64> {
        self.inner.exportable_modifiers(fourcc)
    }

    fn create_buffer(
        &mut self,
        width: u32,
        height: u32,
        fourcc: u32,
        allowed: &[u64],
    ) -> Result<Box<dyn LayerBufferSource>, drmkit_present::ProducerError> {
        let inner = self.inner.create_buffer(width, height, fourcc, allowed)?;
        Ok(Box::new(DamagingSource { inner }))
    }
}

struct DamagingSource {
    inner: Box<dyn LayerBufferSource>,
}

impl LayerBufferSource for DamagingSource {
    fn acquire(&mut self) -> Result<AcquiredBuffer, SourceError> {
        let mut acquired = self.inner.acquire()?;
        acquired.damage = vec![drmkit_scene::DamageRect {
            x: 8,
            y: 8,
            w: 16,
            h: 16,
        }];
        Ok(acquired)
    }

    fn release(&mut self, acquired: AcquiredBuffer) {
        self.inner.release(acquired);
    }

    fn release_with_fence(&mut self, acquired: AcquiredBuffer, fence: Option<SyncFence>) {
        self.inner.release_with_fence(acquired, fence);
    }

    fn wants_release_fence(&self) -> bool {
        self.inner.wants_release_fence()
    }

    fn has_fresh_content(&self) -> bool {
        self.inner.has_fresh_content()
    }

    fn on_retired(&mut self) {
        self.inner.on_retired();
    }

    fn binding_model(&self) -> BindingModel {
        self.inner.binding_model()
    }

    fn format(&self) -> SourceFormat {
        self.inner.format()
    }

    fn map(
        &mut self,
        access: drmkit_dumb::MapAccess,
    ) -> Result<drmkit_dumb::Mapping<'_>, SourceError> {
        self.inner.map(access)
    }

    fn export_dma_buf(&mut self) -> Result<DmaBufDesc<'_>, SourceError> {
        self.inner.export_dma_buf()
    }

    fn bind_to_plane(&mut self, plane_id: u32) -> Result<(), SourceError> {
        self.inner.bind_to_plane(plane_id)
    }

    fn unbind_from_plane(&mut self, plane_id: u32) {
        self.inner.unbind_from_plane(plane_id);
    }

    fn on_session_paused(&mut self) {
        self.inner.on_session_paused();
    }

    fn on_session_resumed(&mut self, device: &Device) -> Result<(), SourceError> {
        self.inner.on_session_resumed(device)
    }
}

/// A producer with no opinion, or with layouts no plane takes: what the
/// backend allows it is recorded, and the allocation goes to the GBM producer.
struct Recording<'a> {
    inner: GbmScanoutProducer<'a>,
    exportable: Vec<u64>,
    allowed: Vec<u64>,
}

impl drmkit_present::ScanoutProducer for Recording<'_> {
    fn exportable_modifiers(&mut self, _fourcc: u32) -> Vec<u64> {
        self.exportable.clone()
    }

    fn create_buffer(
        &mut self,
        width: u32,
        height: u32,
        fourcc: u32,
        allowed: &[u64],
    ) -> Result<Box<dyn LayerBufferSource>, drmkit_present::ProducerError> {
        self.allowed = allowed.to_vec();
        self.inner.create_buffer(width, height, fourcc, allowed)
    }
}

/// With nothing negotiated the producer is allowed `LINEAR`, which every
/// plane scans out, as the reference falls back -- never an empty set, which
/// a producer reads as no constraint at all.
#[test]
#[ignore = "needs a DRM device and DRM master"]
fn nothing_negotiated_falls_back_to_linear_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };

    // No opinion, and a vendor layout no plane on vkms advertises.
    for exportable in [Vec::new(), vec![0x0200_0000_0000_0001]] {
        let mut producer = Recording {
            inner: GbmScanoutProducer::new(&device),
            exportable: exportable.clone(),
            allowed: Vec::new(),
        };
        let backend = match ScanoutBackend::create(&device, &mut producer, &backend_config()) {
            Ok(backend) => backend,
            Err(error) => {
                drmkit_testkit::skipped(&format!("no scanout output here ({error})"));
                return;
            }
        };
        assert!(
            backend.modifiers().is_empty(),
            "{exportable:x?}: nothing was negotiated"
        );
        drop(backend);
        assert_eq!(
            producer.allowed,
            [0],
            "{exportable:x?}: the producer is allowed LINEAR alone"
        );
    }
}