drmkit-dumb 0.1.2

DRM dumb buffers for drmkit: GPU-free, CPU-mappable scanout surfaces with lifetime mmaps.
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
// SPDX-FileCopyrightText: (c) 2026 Joel Winarske
// SPDX-License-Identifier: MIT

//! Parity port of `tests/unit/test_dumb_buffer.cpp` and
//! `test_buffer_mapping.cpp` from drm-cxx @ `dc2915b`.
//!
//! Four of the five upstream `BufferMapping` cases test the C++ guard's unmap
//! bookkeeping — that the destructor calls the registered unmapper exactly
//! once, that a move transfers that responsibility, that move-assignment
//! destroys the target's, and that self-move is harmless. None of them survive
//! the port, and their absence is the point: [`Mapping`] carries no unmapper,
//! because for a dumb buffer there is nothing to unmap. The bookkeeping those
//! cases guard does not exist here, so there is no way for it to go wrong.
//!
//! What remains is the contract they were protecting, which is invariant 6, and
//! that is asserted directly below.

use super::*;
use std::sync::Mutex;

use drmkit_fmt::fourcc;

/// `Device::open` acquires DRM master, and master is per open file
/// description. Card-dependent cases serialize so they do not race for it —
/// the same hazard the `drmkit-core` suite hit.
static CARD_LOCK: Mutex<()> = Mutex::new(());

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

fn test_card() -> String {
    std::env::var("DRMKIT_TEST_CARD").unwrap_or_else(|_| "/dev/dri/card0".to_owned())
}

fn open_card() -> drmkit_core::Device {
    drmkit_core::Device::open(test_card()).expect("open test card")
}

// --- test_buffer_mapping.cpp / invariant 6 ----------------------------------

/// **Invariant 6.** `Mapping` has no `Drop` implementation, so "the guard's
/// destructor is a no-op" is a property of the type rather than a promise in a
/// comment.
///
/// `needs_drop` is the machine-checkable form of that. Adding a `Drop` impl —
/// or a field that has one — fails this immediately, which is what turns a
/// silent regression in per-frame cost into a visible, reviewable change.
#[test]
fn mapping_has_no_destructor() {
    assert!(
        !std::mem::needs_drop::<Mapping<'_>>(),
        "Mapping must have no drop glue: invariant 6 requires the guard's \
         destructor to be a no-op, and DumbScanoutSink's pacing depends on \
         map() costing nothing per frame"
    );
}

/// `BufferMapping.DefaultIsEmptyAndDestructorIsNoOp`
///
/// The C++ default-constructs an empty guard directly. Here a `Mapping` only
/// exists by borrowing a buffer, so the empty case is reached through an empty
/// buffer — which is the only way it can arise in practice anyway.
#[test]
fn empty_buffer_yields_an_empty_mapping() {
    let mut buffer = Buffer::new();
    let mapping = buffer.map(MapAccess::ReadWrite);

    assert!(mapping.is_empty());
    assert!(mapping.pixels().is_empty());
    assert_eq!(mapping.stride(), 0);
    assert_eq!(mapping.width(), 0);
    assert_eq!(mapping.height(), 0);
    // Falls out of scope without unmapping anything, because there is nothing
    // registered to unmap.
}

#[test]
fn mapping_records_the_access_mode() {
    let mut buffer = Buffer::new();
    for access in [MapAccess::Read, MapAccess::Write, MapAccess::ReadWrite] {
        assert_eq!(buffer.map(access).access(), access);
    }
    // ReadWrite is the default, matching the C++ member initializer.
    assert_eq!(MapAccess::default(), MapAccess::ReadWrite);
}

// --- test_dumb_buffer.cpp: pure cases ---------------------------------------

/// `DumbBuffer.DefaultCtorIsEmpty`
#[test]
fn default_buffer_is_empty() {
    let buffer = Buffer::new();
    assert!(buffer.is_empty());
    assert_eq!(buffer.width(), 0);
    assert_eq!(buffer.height(), 0);
    assert_eq!(buffer.stride(), 0);
    assert_eq!(buffer.size_bytes(), 0);
    assert_eq!(buffer.gem_handle(), None);
    assert_eq!(buffer.fb_id(), None);
    assert!(buffer.data().is_empty());

    assert!(Buffer::default().is_empty());
}

/// `DumbBuffer.ForgetOnEmptyIsSafe`
#[test]
fn forget_on_empty_is_safe() {
    let mut buffer = Buffer::new();
    buffer.forget();
    buffer.forget(); // twice
    assert!(buffer.is_empty());
}

/// `DumbBuffer.MoveConstructTransfersOwnership` / `MoveAssignReplacesTarget`
///
/// A move is not observable in Rust, so what is checkable is that the moved
/// value still describes the same allocation and that nothing was released
/// along the way. The card-backed case below covers the allocation half.
#[test]
fn move_preserves_an_empty_buffer() {
    let source = Buffer::new();
    let moved = source;
    assert!(moved.is_empty());
}

/// `DumbBuffer.CreateRejectsZeroWidth` / `ZeroHeight` / `ZeroFormat` /
/// `ZeroBpp`
///
/// These need a device in the C++ because validation happens after the fd
/// check. Here the configuration is validated first, so they are reachable
/// without a card — but they still need a `Device` to call, so the card-backed
/// variant below is what actually runs them.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn create_rejects_invalid_configs_vkms() {
    let _guard = card_guard();
    let device = open_card();

    let base = Config {
        width: 64,
        height: 64,
        fourcc: fourcc::XRGB8888,
        ..Config::default()
    };

    for (config, what) in [
        (Config { width: 0, ..base }, "zero width"),
        (Config { height: 0, ..base }, "zero height"),
        (Config { fourcc: 0, ..base }, "zero format"),
        (Config { bpp: 0, ..base }, "zero bpp"),
        (
            Config {
                width: 16385,
                ..base
            },
            "width past 16384",
        ),
        (
            Config {
                height: 16385,
                ..base
            },
            "height past 16384",
        ),
    ] {
        assert!(
            matches!(
                Buffer::create(&device, &config),
                Err(DumbError::InvalidConfig { .. })
            ),
            "{what} must be rejected"
        );
    }
}

/// An unrecognized `FourCC` is rejected rather than silently substituted.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn create_rejects_an_unknown_fourcc_vkms() {
    let _guard = card_guard();
    let device = open_card();
    let config = Config {
        width: 64,
        height: 64,
        fourcc: 0xdead_beef,
        ..Config::default()
    };
    assert!(matches!(
        Buffer::create(&device, &config),
        Err(DumbError::InvalidConfig { .. })
    ));
}

/// `create_planar` refuses formats outside the recognized semi-planar set, so
/// callers know to fall back to `create`.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn create_planar_rejects_unsupported_formats_vkms() {
    let _guard = card_guard();
    let device = open_card();

    assert!(matches!(
        Buffer::create_planar(&device, fourcc::XRGB8888, 64, 64),
        Err(DumbError::UnsupportedFormat { .. })
    ));
    assert!(
        matches!(
            Buffer::create_planar(&device, fourcc::YUV420, 64, 64),
            Err(DumbError::UnsupportedFormat { .. })
        ),
        "fully planar 4:2:0 is not in the semi-planar set"
    );
}

// --- card-backed allocation --------------------------------------------------

#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn create_allocates_maps_and_registers_a_framebuffer_vkms() {
    let _guard = card_guard();
    let device = open_card();

    let mut buffer = Buffer::create(
        &device,
        &Config {
            width: 64,
            height: 64,
            fourcc: fourcc::XRGB8888,
            ..Config::default()
        },
    )
    .expect("allocate");

    assert!(!buffer.is_empty());
    assert_eq!(buffer.width(), 64);
    assert_eq!(buffer.height(), 64);
    assert!(buffer.stride() >= 64 * 4, "stride covers at least the row");
    assert!(
        buffer.size_bytes() >= buffer.stride() as usize * 64,
        "the mapping covers the whole allocation"
    );
    assert!(buffer.gem_handle().is_some_and(|h| h != 0));
    assert!(buffer.fb_id().is_some_and(|f| f != 0));

    // The mapping is writable and readable back -- it is a real coherent view.
    {
        let mut view = buffer.map(MapAccess::Write);
        assert_eq!(view.width(), 64);
        assert_eq!(view.height(), 64);
        view.row_mut(0).expect("row 0").fill(0xab);
        view.row_mut(63).expect("row 63").fill(0xcd);
        assert!(view.row_mut(64).is_none(), "past the bottom");
    }

    let view = buffer.map(MapAccess::Read);
    assert!(view.row(0).expect("row 0").iter().all(|b| *b == 0xab));
    assert!(view.row(63).expect("row 63").iter().all(|b| *b == 0xcd));
}

/// `add_fb: false` is the legacy cursor path: allocate and map, no framebuffer.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn create_without_a_framebuffer_vkms() {
    let _guard = card_guard();
    let device = open_card();

    let buffer = Buffer::create(
        &device,
        &Config {
            width: 64,
            height: 64,
            fourcc: fourcc::ARGB8888,
            add_fb: false,
            ..Config::default()
        },
    )
    .expect("allocate");

    assert!(buffer.gem_handle().is_some(), "the GEM handle still exists");
    assert_eq!(buffer.fb_id(), None, "but no framebuffer was registered");
    assert!(!buffer.data().is_empty());
}

/// The planar path over-allocates for the chroma plane and reports the *image*
/// height, not the allocated row count.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn create_planar_over_allocates_for_chroma_vkms() {
    let _guard = card_guard();
    let device = open_card();

    let buffer = match Buffer::create_planar(&device, fourcc::NV12, 64, 64) {
        Ok(buffer) => buffer,
        // vkms does not advertise every YUV format; a driver rejecting the
        // framebuffer is a statement about the driver, not about this code.
        Err(DumbError::Io(e)) => {
            println!("note: driver rejected NV12 dumb framebuffer: {e}");
            return;
        }
        Err(e) => panic!("unexpected failure: {e}"),
    };

    assert_eq!(buffer.height(), 64, "reports the image height");
    let y_plane = buffer.stride() as usize * 64;
    assert!(
        buffer.size_bytes() >= y_plane + y_plane / 2,
        "the allocation covers Y plus a half-height chroma plane: got {} for a \
         {}-byte Y plane",
        buffer.size_bytes(),
        y_plane
    );
}

/// `forget` releases the mapping without touching the descriptor, leaving a
/// valid empty buffer. The C++ needs this because libseat closes the
/// descriptor out from under a live buffer on session pause.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn forget_drops_handles_without_ioctls_vkms() {
    let _guard = card_guard();
    let device = open_card();

    let mut buffer = Buffer::create(
        &device,
        &Config {
            width: 32,
            height: 32,
            fourcc: fourcc::XRGB8888,
            ..Config::default()
        },
    )
    .expect("allocate");
    assert!(!buffer.is_empty());

    buffer.forget();

    assert!(buffer.is_empty());
    assert_eq!(buffer.gem_handle(), None);
    assert_eq!(buffer.fb_id(), None);
    assert!(buffer.data().is_empty());
    assert_eq!(buffer.size_bytes(), 0, "the mapping was torn down");

    // Dropping a forgotten buffer must not issue ioctls against a descriptor
    // it no longer owns.
    drop(buffer);
}

/// Allocating and dropping repeatedly must not leak GEM objects or mappings.
/// Measured as descriptor-table growth for the same reason as the
/// `drmkit-sync` leak test: an absolute count races the parallel harness.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn repeated_allocation_does_not_leak_vkms() {
    let _guard = card_guard();
    let device = open_card();
    let config = Config {
        width: 64,
        height: 64,
        fourcc: fourcc::XRGB8888,
        ..Config::default()
    };

    let allocate_and_drop = |times: usize| {
        for _ in 0..times {
            let buffer = Buffer::create(&device, &config).expect("allocate");
            assert!(!buffer.is_empty());
            drop(buffer);
        }
    };
    let count = || {
        std::fs::read_dir("/proc/self/fd")
            .expect("/proc/self/fd")
            .count()
    };

    allocate_and_drop(8);
    let after_few = count();
    allocate_and_drop(120);
    let after_many = count();

    let growth = after_many.saturating_sub(after_few);
    assert!(
        growth < 16,
        "120 further allocate/drop cycles grew the fd table by {growth}"
    );
}

/// A `P010` buffer allocates, registers a framebuffer, and is writable as
/// 16-bit samples.
///
/// Parity port of `tests/integration/test_dumb_buffer_p010_vkms.cpp`, which
/// goes on to scan it out. The scanout half needs a primary plane that
/// advertises `P010`; this asserts everything up to that and reports whether
/// the plane would take it, so the same case answers on hardware that does.
///
/// `P010` is the 10-bit HDR path. Its samples are `u16` with the value in the
/// **high** ten bits, so a row stride is two bytes per pixel rather than one —
/// a buffer sized as though it were 8-bit is half what the format needs, and
/// the driver reads the second half of every frame from whatever follows.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn create_planar_p010_allocates_and_registers_a_framebuffer_vkms() {
    let _guard = card_guard();
    let device = open_card();

    let mut buffer = match Buffer::create_planar(&device, fourcc::P010, 64, 64) {
        Ok(buffer) => buffer,
        Err(error) => {
            println!("note: skipped -- this driver refuses a P010 dumb buffer ({error})");
            return;
        }
    };

    assert!(buffer.gem_handle().is_some());
    assert!(
        buffer.fb_id().is_some_and(|id| id != 0),
        "a P010 buffer the kernel would not register as a framebuffer cannot \
         be scanned out, whatever the allocation says"
    );
    assert!(
        buffer.stride() >= 64 * 2,
        "two bytes per sample, not one -- a stride sized for 8-bit is half \
         what P010 needs, and the driver reads the rest of every row from \
         whatever follows the allocation"
    );
    assert_eq!(
        buffer.height(),
        64,
        "the image height, not the allocated rows"
    );

    // Writable as u16 samples, which is what a producer does.
    let stride = buffer.stride() as usize;
    let mapping = buffer.data_mut();
    assert!(
        mapping.len() >= stride * 64,
        "the luma plane alone needs height * stride"
    );
    for row in 0..64usize {
        for column in 0..64usize {
            let at = row * stride + column * 2;
            if let Some(sample) = mapping.get_mut(at..at + 2) {
                // Mid-gray in the high ten bits, little-endian.
                sample[0] = 0x00;
                sample[1] = 0x40;
            }
        }
    }
    assert_eq!(mapping[1], 0x40, "the write reached the mapping");
}

/// Whether any plane on this card would scan `P010` out.
///
/// Reported rather than asserted: it is a property of the driver, and vkms
/// answering no is not a failure of anything drmkit does. What it decides is
/// whether the scanout half of the upstream case can run here at all — which
/// is worth knowing before a board arrives rather than after.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn report_whether_any_plane_scans_out_p010_vkms() {
    use drm::control::Device as _;

    let _guard = card_guard();
    let device = open_card();
    device.enable_universal_planes().ok();

    let Ok(handles) = device.plane_handles() else {
        println!("note: skipped -- planes could not be listed");
        return;
    };
    let mut takers = 0usize;
    for handle in &handles {
        let Ok(info) = device.get_plane(*handle) else {
            continue;
        };
        if info.formats().contains(&fourcc::P010) {
            takers += 1;
        }
    }

    println!("note: {takers} of {} planes advertise P010", handles.len());
}

/// Dropping a buffer after its device has closed touches nothing on the device
/// that replaced it.
///
/// After a session loss the caller's descriptor closes and the next open of
/// the card takes the same number. GEM handles are numbered per file, so the
/// new file's first buffer has the handle the old one had. A teardown through
/// the number would destroy the new file's buffer; through the buffer's own
/// descriptor it reaches the old file.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn dropping_a_buffer_after_its_device_closed_spares_the_next_one_vkms() {
    use std::os::fd::{AsFd as _, AsRawFd as _};

    let _guard = card_guard();
    let config = Config {
        width: 16,
        height: 16,
        fourcc: fourcc::XRGB8888,
        ..Config::default()
    };
    let before = open_card();
    let number = before.as_fd().as_raw_fd();
    let old = Buffer::create(&before, &config).expect("allocate on the old open");
    drop(before);

    let after = open_card();
    if after.as_fd().as_raw_fd() != number {
        println!("note: skipped -- the descriptor number was not reused");
        return;
    }
    let new = Buffer::create(&after, &config).expect("allocate on the new open");
    let handle = new.gem_handle().expect("a live buffer has a handle");
    if Some(handle) != old.gem_handle() {
        println!("note: the GEM handle was not reused");
    }

    drop(old);
    assert!(
        drm_ffi::mode::dumbbuffer::map(after.as_fd(), handle, 0, 0).is_ok(),
        "dropping the old buffer destroyed GEM handle {handle} on the device that replaced its own"
    );
}