feat(nvkms): implement surface lifecycle registry and FFI (14/66 NVKMS PORTED) (#471)

* feat(nvkms): implement surface lifecycle registry and FFI (REGISTER/UNREGISTER/GRANT/ACQUIRE/RELEASE)

* fix(nvkms): validate format, reject userspace skipSync, check plane extent, avoid ID/handle wraparound collisions, and preserve idempotent unregister/release

* fix(nvkms): retain backing dma-buf/RM fd ref until unregister, reject multi-plane formats, and validate format Bpp row pitch

* fix(nvkms): tie backing dma-buf/RM ref lifetime to SurfaceRegistry reap across orphan lifetimes

---------

Co-authored-by: Eric Hartford <eric@quixi.ai>
This commit is contained in:
Eric Hartford
2026-12-03 12:06:55 -08:00
committed by GitHub
parent 4e46f44f43
commit fe16cf34e2
7 changed files with 1342 additions and 25 deletions

View File

@ -9,10 +9,10 @@ Generated by `python3 tools/build_parity_ledger.py` against stock 580.178.04 ker
| `rm_controls_userspace` | 295 | 0 | 0 | 14 |
| `uvm_ioctls` | 49 | 0 | 0 | 1 |
| `drm_ioctls` | 15 | 9 | 0 | 0 |
| `nvkms_ioctls` | 9 | 57 | 0 | 0 |
| `nvkms_ioctls` | 14 | 52 | 0 | 0 |
| `procfs_and_caps` | 9 | 0 | 0 | 0 |
| `mmio_bus_loss_guards` | 32 | 0 | 0 | 0 |
| **TOTAL** | **2550** | **66** | **0** | **19** |
| **TOTAL** | **2555** | **61** | **0** | **19** |
## Remaining `MISSING` / `PARTIAL` Entries
@ -40,11 +40,6 @@ Generated by `python3 tools/build_parity_ledger.py` against stock 580.178.04 ker
- **[PARTIAL]** `nvkms_ioctls` `14:NVKMS_IOCTL_IDLE_BASE_CHANNEL` — cmd=14 exact 580.178.04 paramSize=36 + deviceHandle validated in nvidia_rs_modeset.c (display/surface backend or per-cmd test pending)
- **[PARTIAL]** `nvkms_ioctls` `15:NVKMS_IOCTL_FLIP` — cmd=15 exact 580.178.04 paramSize=3112 + deviceHandle validated in nvidia_rs_modeset.c (display/surface backend or per-cmd test pending)
- **[PARTIAL]** `nvkms_ioctls` `16:NVKMS_IOCTL_DECLARE_DYNAMIC_DPY_INTEREST` — cmd=16 exact 580.178.04 paramSize=20 + deviceHandle validated in nvidia_rs_modeset.c (display/surface backend or per-cmd test pending)
- **[PARTIAL]** `nvkms_ioctls` `17:NVKMS_IOCTL_REGISTER_SURFACE` — cmd=17 exact 580.178.04 paramSize=152 + deviceHandle validated in nvidia_rs_modeset.c (display/surface backend or per-cmd test pending)
- **[PARTIAL]** `nvkms_ioctls` `18:NVKMS_IOCTL_UNREGISTER_SURFACE` — cmd=18 exact 580.178.04 paramSize=16 + deviceHandle validated in nvidia_rs_modeset.c (display/surface backend or per-cmd test pending)
- **[PARTIAL]** `nvkms_ioctls` `19:NVKMS_IOCTL_GRANT_SURFACE` — cmd=19 exact 580.178.04 paramSize=16 + deviceHandle validated in nvidia_rs_modeset.c (display/surface backend or per-cmd test pending)
- **[PARTIAL]** `nvkms_ioctls` `20:NVKMS_IOCTL_ACQUIRE_SURFACE` — cmd=20 exact 580.178.04 paramSize=12 + deviceHandle validated in nvidia_rs_modeset.c (display/surface backend or per-cmd test pending)
- **[PARTIAL]** `nvkms_ioctls` `21:NVKMS_IOCTL_RELEASE_SURFACE` — cmd=21 exact 580.178.04 paramSize=12 + deviceHandle validated in nvidia_rs_modeset.c (display/surface backend or per-cmd test pending)
- **[PARTIAL]** `nvkms_ioctls` `22:NVKMS_IOCTL_SET_DPY_ATTRIBUTE` — cmd=22 exact 580.178.04 paramSize=32 + deviceHandle validated in nvidia_rs_modeset.c (display/surface backend or per-cmd test pending)
- **[PARTIAL]** `nvkms_ioctls` `23:NVKMS_IOCTL_GET_DPY_ATTRIBUTE` — cmd=23 exact 580.178.04 paramSize=24 + deviceHandle validated in nvidia_rs_modeset.c (display/surface backend or per-cmd test pending)
- **[PARTIAL]** `nvkms_ioctls` `24:NVKMS_IOCTL_GET_DPY_ATTRIBUTE_VALID_VALUES` — cmd=24 exact 580.178.04 paramSize=40 + deviceHandle validated in nvidia_rs_modeset.c (display/surface backend or per-cmd test pending)

View File

@ -5,6 +5,8 @@
* queries nvidia_rs.ko's exported modeset RM ops interface
* (nv_rs_modeset_get_rm_ops) to complete 5-module parity with stock 580.178.04.
*/
#include <linux/atomic.h>
#include <linux/dma-buf.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/ioctl.h>
@ -14,6 +16,7 @@
#include <linux/poll.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/version.h>
extern u32 nv_rs_modeset_get_rm_ops(void *rm_ops);
extern u32 nv_rs_nvkms_param_size_580(u32 cmd);
@ -34,6 +37,23 @@ extern int nv_rs_nvkms_ownership_release(u32 rm_device_id, u64 file_id, u32 devi
extern u8 nv_rs_nvkms_ownership_is_owner(u32 rm_device_id, u64 file_id, u32 device_handle);
extern void nv_rs_nvkms_ownership_release_device(u64 file_id, u32 device_handle);
extern void nv_rs_nvkms_ownership_release_file(u64 file_id);
extern int nv_rs_nvkms_surface_register(u64 file_id, u32 device_handle, u32 rm_device_id,
u8 use_fd, s32 plane0_fd, u64 plane0_offset,
u32 plane0_pitch, u64 plane0_size, u32 width,
u32 height, u32 layout, u32 format,
u64 backing_token, u32 *out_surface_handle);
extern int nv_rs_nvkms_surface_unregister(u64 file_id, u32 device_handle, u32 surface_handle,
u8 skip_sync);
extern int nv_rs_nvkms_surface_grant(u64 owner_file_id, u32 device_handle, u32 surface_handle,
u64 grant_file_id);
extern int nv_rs_nvkms_surface_grant_rm_device(u64 grant_file_id, u32 *out_rm_device_id);
extern int nv_rs_nvkms_surface_acquire(u64 acquirer_file_id, u32 acquirer_device_handle,
u32 acquirer_rm_device_id, u64 grant_file_id,
u32 *out_surface_handle);
extern int nv_rs_nvkms_surface_release(u64 acquirer_file_id, u32 device_handle, u32 surface_handle);
extern void nv_rs_nvkms_surface_release_device(u64 file_id, u32 device_handle);
extern void nv_rs_nvkms_surface_release_file(u64 file_id);
extern u64 nv_rs_nvkms_surface_pop_reaped_backing(void);
extern int nv_rs_nvkms_validate_fbcon_disabled_userspace(u64 address, u32 size, u8 device_exists);
/* Exact NvKmsIoctlParams UAPI from 580.178.04 nvkms-ioctl.h. */
@ -59,6 +79,9 @@ struct nv_rs_kms_ioctl_params {
#define NV_RS_KMS_CMD_CHECK_LUT_NOTIFIER 13u
#define NV_RS_KMS_CMD_REGISTER_SURFACE 17u
#define NV_RS_KMS_CMD_UNREGISTER_SURFACE 18u
#define NV_RS_KMS_CMD_GRANT_SURFACE 19u
#define NV_RS_KMS_CMD_ACQUIRE_SURFACE 20u
#define NV_RS_KMS_CMD_RELEASE_SURFACE 21u
#define NV_RS_KMS_CMD_QUERY_FRAMELOCK 28u
#define NV_RS_KMS_CMD_GET_NEXT_EVENT 32u
#define NV_RS_KMS_CMD_DECLARE_EVENT_INTEREST 33u
@ -75,7 +98,16 @@ struct nv_rs_kms_ioctl_params {
#define NV_RS_KMS_MAX_DEVICES_PER_FILE 16u
#define NV_RS_KMS_MAX_RM_DEVICES 32u
#define NV_RS_KMS_MAX_SWAP_GROUPS_PER_FILE 16u
#define NV_RS_KMS_MAX_SURFACE_BACKINGS_PER_FILE 64u
#define NV_RS_KMS_REGISTER_SURFACE_SIZE 152u
#define NV_RS_KMS_REGISTER_SURFACE_REPLY_OFFSET 144u
#define NV_RS_KMS_UNREGISTER_SURFACE_SIZE 16u
#define NV_RS_KMS_GRANT_SURFACE_SIZE 16u
#define NV_RS_KMS_ACQUIRE_SURFACE_SIZE 12u
#define NV_RS_KMS_RELEASE_SURFACE_SIZE 12u
#define NV_RS_FD_ROLE_FRESH 0
#define NV_RS_FD_ROLE_CLIENT 1
#define NV_RS_FD_ROLE_GRANT 2
#define NV_RS_KMS_GET_NEXT_EVENT_SIZE 48u
#define NV_RS_KMS_GET_NEXT_EVENT_REPLY_OFFSET 8u
#define NV_RS_KMS_GET_NEXT_EVENT_REPLY_SIZE 40u
@ -124,8 +156,14 @@ struct nv_rs_kms_swap_group_slot {
u32 swap_group_handle;
};
struct nv_rs_kms_surface_backing {
struct dma_buf *dmabuf;
struct file *rm_filp;
};
struct nv_rs_modeset_file {
struct mutex lock;
atomic_t fd_role;
u32 next_handle;
u32 next_swap_group_handle;
u32 event_interest_mask;
@ -142,16 +180,36 @@ static DEFINE_MUTEX(nv_rs_modeset_owner_lock);
static const struct file_operations nv_rs_modeset_fops;
static void nv_rs_modeset_drain_reaped_backings_locked(void)
{
u64 tok;
while ((tok = nv_rs_nvkms_surface_pop_reaped_backing()) != 0) {
struct nv_rs_kms_surface_backing *b =
(struct nv_rs_kms_surface_backing *)(uintptr_t)tok;
if (b->dmabuf)
dma_buf_put(b->dmabuf);
if (b->rm_filp)
fput(b->rm_filp);
kfree(b);
}
}
static void nv_rs_modeset_release_owner_locked(struct nv_rs_modeset_file *f,
u32 device_handle,
bool all_for_file)
{
u64 file_id = (u64)(uintptr_t)f;
if (all_for_file)
if (all_for_file) {
nv_rs_nvkms_ownership_release_file(file_id);
else
nv_rs_nvkms_surface_release_file(file_id);
} else {
nv_rs_nvkms_ownership_release_device(file_id, device_handle);
nv_rs_nvkms_surface_release_device(file_id, device_handle);
}
nv_rs_modeset_drain_reaped_backings_locked();
}
static bool nv_rs_modeset_is_owner_locked(const struct nv_rs_modeset_file *f,
@ -352,28 +410,319 @@ nv_rs_modeset_find_device_locked(struct nv_rs_modeset_file *f, u32 handle)
static long nv_rs_modeset_register_surface(struct nv_rs_modeset_file *f,
const struct nv_rs_kms_ioctl_params *p)
{
u32 device_handle = 0;
u8 *buf;
u32 device_handle;
u8 use_fd;
s32 plane0_fd;
u64 plane0_offset;
u32 plane0_pitch;
u64 plane0_size;
u32 width;
u32 height;
u32 layout;
u32 format;
u32 rm_device_id = 0;
u32 surface_handle = 0;
struct nv_rs_kms_device_slot *dev;
struct nv_rs_kms_surface_backing *backing;
struct dma_buf *dmabuf = NULL;
struct file *rm_filp = NULL;
int rc;
if (!p->address || p->size != NV_RS_KMS_REGISTER_SURFACE_SIZE)
return -EINVAL;
if (copy_from_user(&device_handle, (const void __user *)(uintptr_t)p->address,
sizeof(device_handle)))
buf = kmalloc(NV_RS_KMS_REGISTER_SURFACE_SIZE, GFP_KERNEL);
if (!buf)
return -ENOMEM;
if (copy_from_user(buf, (const void __user *)(uintptr_t)p->address,
NV_RS_KMS_REGISTER_SURFACE_SIZE)) {
kfree(buf);
return -EFAULT;
mutex_lock(&f->lock);
if (!nv_rs_modeset_find_device_locked(f, device_handle)) {
mutex_unlock(&f->lock);
return -EINVAL;
}
mutex_unlock(&f->lock);
/* Exact 580.178.04 NvKmsRegisterSurfaceParams byte offsets (152 bytes). */
memcpy(&device_handle, buf + 0, sizeof(device_handle));
use_fd = buf[4];
memcpy(&plane0_fd, buf + 16, sizeof(plane0_fd));
memcpy(&plane0_offset, buf + 24, sizeof(plane0_offset));
memcpy(&plane0_pitch, buf + 32, sizeof(plane0_pitch));
memcpy(&plane0_size, buf + 40, sizeof(plane0_size));
memcpy(&width, buf + 112, sizeof(width));
memcpy(&height, buf + 116, sizeof(height));
memcpy(&layout, buf + 120, sizeof(layout));
memcpy(&format, buf + 124, sizeof(format));
kfree(buf);
if (!use_fd || plane0_fd < 0)
return -EINVAL;
/*
* Stock nvKmsRegisterSurface requires useFd == TRUE for userspace and
* imports/retains the backing RM memory object. Return -EOPNOTSUPP until
* the backing surface fd import path is implemented rather than fabricating
* an unbacked handle.
* Retain a real kernel reference to the backing memory object until the
* surface is fully reaped (including across orphan lifetimes while acquiring
* clients or grant fds still hold references).
*/
return -EOPNOTSUPP;
dmabuf = dma_buf_get(plane0_fd);
if (IS_ERR(dmabuf)) {
struct file *cand = fget(plane0_fd);
dmabuf = NULL;
if (!cand)
return -EBADF;
if (!S_ISCHR(file_inode(cand)->i_mode) || imajor(file_inode(cand)) != 195) {
fput(cand);
return -EINVAL;
}
rm_filp = cand;
} else if (plane0_size > dmabuf->size) {
dma_buf_put(dmabuf);
return -EINVAL;
}
backing = kzalloc(sizeof(*backing), GFP_KERNEL);
if (!backing) {
if (dmabuf)
dma_buf_put(dmabuf);
if (rm_filp)
fput(rm_filp);
return -ENOMEM;
}
backing->dmabuf = dmabuf;
backing->rm_filp = rm_filp;
mutex_lock(&nv_rs_modeset_owner_lock);
mutex_lock(&f->lock);
dev = nv_rs_modeset_find_device_locked(f, device_handle);
if (!dev) {
mutex_unlock(&f->lock);
mutex_unlock(&nv_rs_modeset_owner_lock);
if (dmabuf)
dma_buf_put(dmabuf);
if (rm_filp)
fput(rm_filp);
kfree(backing);
return -EINVAL;
}
rm_device_id = dev->rm_device_id;
rc = nv_rs_nvkms_surface_register((u64)(uintptr_t)f, device_handle, rm_device_id,
use_fd, plane0_fd, plane0_offset, plane0_pitch,
plane0_size, width, height, layout, format,
(u64)(uintptr_t)backing, &surface_handle);
mutex_unlock(&f->lock);
mutex_unlock(&nv_rs_modeset_owner_lock);
if (rc) {
if (dmabuf)
dma_buf_put(dmabuf);
if (rm_filp)
fput(rm_filp);
kfree(backing);
return rc;
}
if (copy_to_user((u8 __user *)(uintptr_t)p->address +
NV_RS_KMS_REGISTER_SURFACE_REPLY_OFFSET,
&surface_handle, sizeof(surface_handle))) {
mutex_lock(&nv_rs_modeset_owner_lock);
nv_rs_nvkms_surface_unregister((u64)(uintptr_t)f, device_handle, surface_handle, 0);
nv_rs_modeset_drain_reaped_backings_locked();
mutex_unlock(&nv_rs_modeset_owner_lock);
return -EFAULT;
}
return 0;
}
static long nv_rs_modeset_unregister_surface(struct nv_rs_modeset_file *f,
const struct nv_rs_kms_ioctl_params *p)
{
struct {
u32 device_handle;
u32 surface_handle;
u8 skip_sync;
} req;
u32 zero = 0;
int rc;
if (!p->address || p->size != NV_RS_KMS_UNREGISTER_SURFACE_SIZE)
return -EINVAL;
if (copy_from_user(&req, (const void __user *)(uintptr_t)p->address, sizeof(req)))
return -EFAULT;
mutex_lock(&nv_rs_modeset_owner_lock);
mutex_lock(&f->lock);
if (!nv_rs_modeset_find_device_locked(f, req.device_handle)) {
mutex_unlock(&f->lock);
mutex_unlock(&nv_rs_modeset_owner_lock);
return -EINVAL;
}
rc = nv_rs_nvkms_surface_unregister((u64)(uintptr_t)f, req.device_handle,
req.surface_handle, req.skip_sync);
if (rc == 0)
nv_rs_modeset_drain_reaped_backings_locked();
mutex_unlock(&f->lock);
mutex_unlock(&nv_rs_modeset_owner_lock);
if (rc)
return rc;
if (copy_to_user((u8 __user *)(uintptr_t)p->address + 12u, &zero, sizeof(zero)))
return -EFAULT;
return 0;
}
static long nv_rs_modeset_grant_surface(struct nv_rs_modeset_file *f,
const struct nv_rs_kms_ioctl_params *p)
{
struct {
u32 device_handle;
u32 surface_handle;
s32 fd;
} req;
u32 zero = 0;
struct file *grant_filp;
struct nv_rs_modeset_file *grant_f;
int rc;
if (!p->address || p->size != NV_RS_KMS_GRANT_SURFACE_SIZE)
return -EINVAL;
if (copy_from_user(&req, (const void __user *)(uintptr_t)p->address, sizeof(req)))
return -EFAULT;
if (req.fd < 0)
return -EBADF;
grant_filp = fget(req.fd);
if (!grant_filp)
return -EBADF;
if (grant_filp->f_op != &nv_rs_modeset_fops || !grant_filp->private_data) {
fput(grant_filp);
return -EINVAL;
}
grant_f = grant_filp->private_data;
/* Stock nvkms-api.h:2689-2693: grant fd must be fresh (never used for ioctl or prior grant). */
if (atomic_cmpxchg(&grant_f->fd_role, NV_RS_FD_ROLE_FRESH, NV_RS_FD_ROLE_GRANT) !=
NV_RS_FD_ROLE_FRESH) {
fput(grant_filp);
return -EINVAL;
}
mutex_lock(&nv_rs_modeset_owner_lock);
mutex_lock(&f->lock);
if (!nv_rs_modeset_find_device_locked(f, req.device_handle)) {
mutex_unlock(&f->lock);
mutex_unlock(&nv_rs_modeset_owner_lock);
atomic_set(&grant_f->fd_role, NV_RS_FD_ROLE_FRESH);
fput(grant_filp);
return -EINVAL;
}
rc = nv_rs_nvkms_surface_grant((u64)(uintptr_t)f, req.device_handle, req.surface_handle,
(u64)(uintptr_t)grant_f);
mutex_unlock(&f->lock);
mutex_unlock(&nv_rs_modeset_owner_lock);
if (rc) {
atomic_set(&grant_f->fd_role, NV_RS_FD_ROLE_FRESH);
fput(grant_filp);
return rc;
}
fput(grant_filp);
if (copy_to_user((u8 __user *)(uintptr_t)p->address + 12u, &zero, sizeof(zero)))
return -EFAULT;
return 0;
}
static long nv_rs_modeset_acquire_surface(struct nv_rs_modeset_file *f,
const struct nv_rs_kms_ioctl_params *p)
{
s32 grant_fd = -1;
struct file *grant_filp;
struct nv_rs_modeset_file *grant_f;
u32 rm_device_id = 0;
u32 reply[2] = { 0, 0 }; /* deviceHandle, surfaceHandle */
u32 i;
int rc;
if (!p->address || p->size != NV_RS_KMS_ACQUIRE_SURFACE_SIZE)
return -EINVAL;
if (copy_from_user(&grant_fd, (const void __user *)(uintptr_t)p->address, sizeof(grant_fd)))
return -EFAULT;
if (grant_fd < 0)
return -EBADF;
grant_filp = fget(grant_fd);
if (!grant_filp)
return -EBADF;
if (grant_filp->f_op != &nv_rs_modeset_fops || !grant_filp->private_data) {
fput(grant_filp);
return -EINVAL;
}
grant_f = grant_filp->private_data;
mutex_lock(&nv_rs_modeset_owner_lock);
rc = nv_rs_nvkms_surface_grant_rm_device((u64)(uintptr_t)grant_f, &rm_device_id);
if (rc) {
mutex_unlock(&nv_rs_modeset_owner_lock);
fput(grant_filp);
return rc;
}
mutex_lock(&f->lock);
for (i = 0; i < NV_RS_KMS_MAX_DEVICES_PER_FILE; i++) {
if (f->devices[i].in_use && f->devices[i].rm_device_id == rm_device_id) {
reply[0] = f->devices[i].handle;
break;
}
}
if (reply[0] == 0) {
mutex_unlock(&f->lock);
mutex_unlock(&nv_rs_modeset_owner_lock);
fput(grant_filp);
return -EINVAL;
}
rc = nv_rs_nvkms_surface_acquire((u64)(uintptr_t)f, reply[0], rm_device_id,
(u64)(uintptr_t)grant_f, &reply[1]);
mutex_unlock(&f->lock);
mutex_unlock(&nv_rs_modeset_owner_lock);
fput(grant_filp);
if (rc)
return rc;
if (copy_to_user((u8 __user *)(uintptr_t)p->address + 4u, reply, sizeof(reply))) {
mutex_lock(&nv_rs_modeset_owner_lock);
nv_rs_nvkms_surface_release((u64)(uintptr_t)f, reply[0], reply[1]);
nv_rs_modeset_drain_reaped_backings_locked();
mutex_unlock(&nv_rs_modeset_owner_lock);
return -EFAULT;
}
return 0;
}
static long nv_rs_modeset_release_surface(struct nv_rs_modeset_file *f,
const struct nv_rs_kms_ioctl_params *p)
{
u32 req[2] = { 0, 0 }; /* deviceHandle, surfaceHandle */
u32 zero = 0;
int rc;
if (!p->address || p->size != NV_RS_KMS_RELEASE_SURFACE_SIZE)
return -EINVAL;
if (copy_from_user(req, (const void __user *)(uintptr_t)p->address, sizeof(req)))
return -EFAULT;
mutex_lock(&nv_rs_modeset_owner_lock);
mutex_lock(&f->lock);
if (!nv_rs_modeset_find_device_locked(f, req[0])) {
mutex_unlock(&f->lock);
mutex_unlock(&nv_rs_modeset_owner_lock);
return -EINVAL;
}
rc = nv_rs_nvkms_surface_release((u64)(uintptr_t)f, req[0], req[1]);
if (rc == 0)
nv_rs_modeset_drain_reaped_backings_locked();
mutex_unlock(&f->lock);
mutex_unlock(&nv_rs_modeset_owner_lock);
if (rc)
return rc;
if (copy_to_user((u8 __user *)(uintptr_t)p->address + 8u, &zero, sizeof(zero)))
return -EFAULT;
return 0;
}
static long nv_rs_modeset_query_disp(struct nv_rs_modeset_file *f,
@ -683,6 +1032,9 @@ static long nv_rs_modeset_ioctl(struct file *file, unsigned int cmd, unsigned lo
if (!f)
return -EINVAL;
if (atomic_cmpxchg(&f->fd_role, NV_RS_FD_ROLE_FRESH, NV_RS_FD_ROLE_CLIENT) ==
NV_RS_FD_ROLE_GRANT)
return -EINVAL;
if (cmd != NV_RS_KMS_IOCTL_IOWR)
return -ENOTTY;
if (copy_from_user(&p, (void __user *)arg, sizeof(p)))
@ -700,6 +1052,14 @@ static long nv_rs_modeset_ioctl(struct file *file, unsigned int cmd, unsigned lo
return nv_rs_modeset_query_framelock(&p);
case NV_RS_KMS_CMD_REGISTER_SURFACE:
return nv_rs_modeset_register_surface(f, &p);
case NV_RS_KMS_CMD_UNREGISTER_SURFACE:
return nv_rs_modeset_unregister_surface(f, &p);
case NV_RS_KMS_CMD_GRANT_SURFACE:
return nv_rs_modeset_grant_surface(f, &p);
case NV_RS_KMS_CMD_ACQUIRE_SURFACE:
return nv_rs_modeset_acquire_surface(f, &p);
case NV_RS_KMS_CMD_RELEASE_SURFACE:
return nv_rs_modeset_release_surface(f, &p);
case NV_RS_KMS_CMD_GET_NEXT_EVENT:
return nv_rs_modeset_get_next_event(&p);
case NV_RS_KMS_CMD_DECLARE_EVENT_INTEREST:
@ -797,3 +1157,8 @@ module_exit(nv_rs_modeset_exit);
MODULE_LICENSE("Dual MIT/GPL");
MODULE_DESCRIPTION("nvdriver clean-room Rust modeset bridge module");
MODULE_VERSION("0.1");
#if defined(NV_RS_HAVE_MODULE_IMPORT_NS_STR) || LINUX_VERSION_CODE >= KERNEL_VERSION(6, 13, 0)
MODULE_IMPORT_NS("DMA_BUF");
#elif LINUX_VERSION_CODE >= KERNEL_VERSION(5, 16, 0) || defined(RHEL_RELEASE_CODE)
MODULE_IMPORT_NS(DMA_BUF);
#endif

View File

@ -35,6 +35,23 @@ extern int nv_rs_nvkms_ownership_release(u32 rm_device_id, u64 file_id, u32 devi
extern u8 nv_rs_nvkms_ownership_is_owner(u32 rm_device_id, u64 file_id, u32 device_handle);
extern void nv_rs_nvkms_ownership_release_device(u64 file_id, u32 device_handle);
extern void nv_rs_nvkms_ownership_release_file(u64 file_id);
extern int nv_rs_nvkms_surface_register(u64 file_id, u32 device_handle, u32 rm_device_id,
u8 use_fd, s32 plane0_fd, u64 plane0_offset,
u32 plane0_pitch, u64 plane0_size, u32 width,
u32 height, u32 layout, u32 format,
u64 backing_token, u32 *out_surface_handle);
extern int nv_rs_nvkms_surface_unregister(u64 file_id, u32 device_handle, u32 surface_handle,
u8 skip_sync);
extern int nv_rs_nvkms_surface_grant(u64 owner_file_id, u32 device_handle, u32 surface_handle,
u64 grant_file_id);
extern int nv_rs_nvkms_surface_grant_rm_device(u64 grant_file_id, u32 *out_rm_device_id);
extern int nv_rs_nvkms_surface_acquire(u64 acquirer_file_id, u32 acquirer_device_handle,
u32 acquirer_rm_device_id, u64 grant_file_id,
u32 *out_surface_handle);
extern int nv_rs_nvkms_surface_release(u64 acquirer_file_id, u32 device_handle, u32 surface_handle);
extern void nv_rs_nvkms_surface_release_device(u64 file_id, u32 device_handle);
extern void nv_rs_nvkms_surface_release_file(u64 file_id);
extern u64 nv_rs_nvkms_surface_pop_reaped_backing(void);
extern int nv_rs_nvkms_validate_fbcon_disabled_userspace(u64 address, u32 size, u8 device_exists);
extern int nv_rs_drm_validate_gem_alloc_nvkms(u8 modeset_enabled, u16 pad0, u32 pad1,
u64 memory_size, u64 page_size,
@ -64,6 +81,15 @@ EXPORT_SYMBOL(nv_rs_nvkms_ownership_release);
EXPORT_SYMBOL(nv_rs_nvkms_ownership_is_owner);
EXPORT_SYMBOL(nv_rs_nvkms_ownership_release_device);
EXPORT_SYMBOL(nv_rs_nvkms_ownership_release_file);
EXPORT_SYMBOL(nv_rs_nvkms_surface_register);
EXPORT_SYMBOL(nv_rs_nvkms_surface_unregister);
EXPORT_SYMBOL(nv_rs_nvkms_surface_grant);
EXPORT_SYMBOL(nv_rs_nvkms_surface_grant_rm_device);
EXPORT_SYMBOL(nv_rs_nvkms_surface_acquire);
EXPORT_SYMBOL(nv_rs_nvkms_surface_release);
EXPORT_SYMBOL(nv_rs_nvkms_surface_release_device);
EXPORT_SYMBOL(nv_rs_nvkms_surface_release_file);
EXPORT_SYMBOL(nv_rs_nvkms_surface_pop_reaped_backing);
EXPORT_SYMBOL(nv_rs_nvkms_validate_fbcon_disabled_userspace);
EXPORT_SYMBOL(nv_rs_drm_validate_gem_alloc_nvkms);
EXPORT_SYMBOL(nv_rs_drm_validate_gem_import_userspace);

File diff suppressed because one or more lines are too long

View File

@ -720,6 +720,163 @@ pub unsafe extern "C" fn nv_rs_nvkms_ownership_release_file(file_id: u64) {
tbl.release_all_for_file(file_id);
}
static mut NVKMS_SURFACES: nv_rs_core::nvkms::SurfaceRegistry =
nv_rs_core::nvkms::SurfaceRegistry::new();
/// FFI entry point for `nvidia_rs_modeset.ko`: registers a surface (`NVKMS_IOCTL_REGISTER_SURFACE`).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn nv_rs_nvkms_surface_register(
file_id: u64,
device_handle: u32,
rm_device_id: u32,
use_fd: u8,
plane0_fd: i32,
plane0_offset: u64,
plane0_pitch: u32,
plane0_size: u64,
width: u32,
height: u32,
layout: u32,
format: u32,
backing_token: u64,
out_surface_handle: *mut u32,
) -> i32 {
let reg = unsafe { &mut *core::ptr::addr_of_mut!(NVKMS_SURFACES) };
match reg.register_with_backing(
file_id,
device_handle,
rm_device_id,
use_fd != 0,
plane0_fd,
plane0_offset,
plane0_pitch,
plane0_size,
width,
height,
layout,
format,
backing_token,
) {
Ok(h) => {
if !out_surface_handle.is_null() {
unsafe { *out_surface_handle = h };
}
0
}
Err(e) => e,
}
}
/// FFI entry point for `nvidia_rs_modeset.ko`: unregisters a surface (`NVKMS_IOCTL_UNREGISTER_SURFACE`).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn nv_rs_nvkms_surface_unregister(
file_id: u64,
device_handle: u32,
surface_handle: u32,
skip_sync: u8,
) -> i32 {
let reg = unsafe { &mut *core::ptr::addr_of_mut!(NVKMS_SURFACES) };
match reg.unregister(file_id, device_handle, surface_handle, skip_sync != 0) {
Ok(()) => 0,
Err(e) => e,
}
}
/// FFI entry point for `nvidia_rs_modeset.ko`: binds a surface grant fd (`NVKMS_IOCTL_GRANT_SURFACE`).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn nv_rs_nvkms_surface_grant(
owner_file_id: u64,
device_handle: u32,
surface_handle: u32,
grant_file_id: u64,
) -> i32 {
let reg = unsafe { &mut *core::ptr::addr_of_mut!(NVKMS_SURFACES) };
match reg.grant(owner_file_id, device_handle, surface_handle, grant_file_id) {
Ok(()) => 0,
Err(e) => e,
}
}
/// FFI entry point for `nvidia_rs_modeset.ko`: queries the `rm_device_id` of a grant fd.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn nv_rs_nvkms_surface_grant_rm_device(
grant_file_id: u64,
out_rm_device_id: *mut u32,
) -> i32 {
let reg = unsafe { &*core::ptr::addr_of!(NVKMS_SURFACES) };
match reg.grant_target_rm_device_id(grant_file_id) {
Some(rm_id) => {
if !out_rm_device_id.is_null() {
unsafe { *out_rm_device_id = rm_id };
}
0
}
None => nv_rs_core::nvkms::EINVAL,
}
}
/// FFI entry point for `nvidia_rs_modeset.ko`: acquires a granted surface (`NVKMS_IOCTL_ACQUIRE_SURFACE`).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn nv_rs_nvkms_surface_acquire(
acquirer_file_id: u64,
acquirer_device_handle: u32,
acquirer_rm_device_id: u32,
grant_file_id: u64,
out_surface_handle: *mut u32,
) -> i32 {
let reg = unsafe { &mut *core::ptr::addr_of_mut!(NVKMS_SURFACES) };
match reg.acquire(
acquirer_file_id,
acquirer_device_handle,
acquirer_rm_device_id,
grant_file_id,
) {
Ok(h) => {
if !out_surface_handle.is_null() {
unsafe { *out_surface_handle = h };
}
0
}
Err(e) => e,
}
}
/// FFI entry point for `nvidia_rs_modeset.ko`: releases an acquired surface (`NVKMS_IOCTL_RELEASE_SURFACE`).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn nv_rs_nvkms_surface_release(
acquirer_file_id: u64,
device_handle: u32,
surface_handle: u32,
) -> i32 {
let reg = unsafe { &mut *core::ptr::addr_of_mut!(NVKMS_SURFACES) };
match reg.release(acquirer_file_id, device_handle, surface_handle) {
Ok(()) => 0,
Err(e) => e,
}
}
/// FFI entry point for `nvidia_rs_modeset.ko`: releases all surfaces for one device handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn nv_rs_nvkms_surface_release_device(file_id: u64, device_handle: u32) {
let reg = unsafe { &mut *core::ptr::addr_of_mut!(NVKMS_SURFACES) };
reg.release_device(file_id, device_handle);
}
/// FFI entry point for `nvidia_rs_modeset.ko`: releases all surfaces/grants/acquires for a closed file.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn nv_rs_nvkms_surface_release_file(file_id: u64) {
let reg = unsafe { &mut *core::ptr::addr_of_mut!(NVKMS_SURFACES) };
reg.release_file(file_id);
}
/// FFI entry point for `nvidia_rs_modeset.ko`: pops the next backing token for a
/// fully reaped surface (0 when none remain).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn nv_rs_nvkms_surface_pop_reaped_backing() -> u64 {
let reg = unsafe { &mut *core::ptr::addr_of_mut!(NVKMS_SURFACES) };
reg.pop_reaped_backing()
}
/// FFI entry point for `nvidia_rs_modeset.ko`: validates `NVKMS_IOCTL_FRAMEBUFFER_CONSOLE_DISABLED`.
#[unsafe(no_mangle)]
pub extern "C" fn nv_rs_nvkms_validate_fbcon_disabled_userspace(

View File

@ -258,6 +258,659 @@ impl OwnershipTable {
}
}
/// Maximum simultaneously registered NVKMS surfaces in `SurfaceRegistry`.
pub const MAX_SURFACES: usize = 64;
/// Maximum simultaneous fd-bound surface grants.
pub const MAX_SURFACE_GRANTS: usize = 64;
/// Maximum simultaneous acquired client surface handles.
pub const MAX_SURFACE_ACQUIRES: usize = 128;
/// Maximum NVKMS surface width/height in pixels.
pub const MAX_SURFACE_DIM_PX: u32 = 32768;
/// Stock 580.178.04 `NvKmsSurfaceMemoryFormatMax` (`NvKmsSurfaceMemoryFormatRF16GF16BF16XF16 = 35`).
pub const MAX_SURFACE_FORMAT: u32 = 35;
/// Returns `(plane_count, bytes_per_pixel_plane0)` for stock 580.178.04
/// `enum NvKmsSurfaceMemoryFormat` (`nvkms-format.h:53-92`).
pub const fn format_plane_count_and_bpp(format: u32) -> Option<(u8, u8)> {
match format {
0 => Some((1, 1)), // I8
1..=3 => Some((1, 2)), // A1R5G5B5, X1R5G5B5, R5G6B5
4..=9 => Some((1, 4)), // A8R8G8B8 .. X8B8G8R8
10 | 11 | 35 => Some((1, 8)), // RF16GF16BF16AF16, R16G16B16A16, RF16GF16BF16XF16
12 => Some((1, 16)), // RF32GF32BF32AF32
13 | 14 => Some((1, 2)), // Y8_U8__Y8_V8_N422, U8_Y8__V8_Y8_N422
15..=20 => Some((2, 1)), // 8-bit YUV semi-planar (2 planes)
21..=32 => Some((2, 2)), // 10/12-bit YUV semi-planar (2 planes)
33 | 34 => Some((3, 1)), // 8-bit YUV planar (3 planes)
_ => None,
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct SurfaceEntry {
in_use: bool,
orphaned: bool,
surface_id: u32,
owner_file_id: u64,
owner_device_handle: u32,
rm_device_id: u32,
owner_surface_handle: u32,
backing_token: u64,
acquire_count: u16,
grant_count: u16,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct SurfaceGrantEntry {
in_use: bool,
grant_file_id: u64,
surface_id: u32,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct SurfaceAcquireEntry {
in_use: bool,
acquirer_file_id: u64,
acquirer_device_handle: u32,
acquirer_surface_handle: u32,
surface_id: u32,
}
/// `#![no_std]` NVKMS surface lifecycle registry implementing stock 580.178.04
/// `REGISTER_SURFACE` / `UNREGISTER_SURFACE` / `GRANT_SURFACE` /
/// `ACQUIRE_SURFACE` / `RELEASE_SURFACE` semantics, including orphaned-surface
/// lifetime preservation (`nvkms-api.h:2680-2708`).
#[derive(Debug, Clone, Copy)]
pub struct SurfaceRegistry {
next_id: u32,
next_handle: u32,
surfaces: [SurfaceEntry; MAX_SURFACES],
grants: [SurfaceGrantEntry; MAX_SURFACE_GRANTS],
acquires: [SurfaceAcquireEntry; MAX_SURFACE_ACQUIRES],
reaped_tokens: [u64; MAX_SURFACES],
reaped_len: usize,
}
impl Default for SurfaceRegistry {
fn default() -> Self {
Self::new()
}
}
impl SurfaceRegistry {
pub const fn new() -> Self {
Self {
next_id: 1,
next_handle: 1,
surfaces: [SurfaceEntry {
in_use: false,
orphaned: false,
surface_id: 0,
owner_file_id: 0,
owner_device_handle: 0,
rm_device_id: 0,
owner_surface_handle: 0,
backing_token: 0,
acquire_count: 0,
grant_count: 0,
}; MAX_SURFACES],
grants: [SurfaceGrantEntry {
in_use: false,
grant_file_id: 0,
surface_id: 0,
}; MAX_SURFACE_GRANTS],
acquires: [SurfaceAcquireEntry {
in_use: false,
acquirer_file_id: 0,
acquirer_device_handle: 0,
acquirer_surface_handle: 0,
surface_id: 0,
}; MAX_SURFACE_ACQUIRES],
reaped_tokens: [0; MAX_SURFACES],
reaped_len: 0,
}
}
fn id_in_use(&self, id: u32) -> bool {
let mut i = 0;
while i < MAX_SURFACES {
if self.surfaces[i].in_use && self.surfaces[i].surface_id == id {
return true;
}
i += 1;
}
false
}
fn handle_in_use(&self, h: u32) -> bool {
let mut i = 0;
while i < MAX_SURFACES {
if self.surfaces[i].in_use && self.surfaces[i].owner_surface_handle == h {
return true;
}
i += 1;
}
let mut a = 0;
while a < MAX_SURFACE_ACQUIRES {
if self.acquires[a].in_use && self.acquires[a].acquirer_surface_handle == h {
return true;
}
a += 1;
}
false
}
fn alloc_id(&mut self) -> u32 {
loop {
let id = self.next_id;
self.next_id = self.next_id.wrapping_add(1);
if id != 0 && !self.id_in_use(id) {
return id;
}
}
}
fn alloc_handle(&mut self) -> u32 {
loop {
let h = self.next_handle;
self.next_handle = self.next_handle.wrapping_add(1);
if h != 0 && !self.handle_in_use(h) {
return h;
}
}
}
fn reap_if_unused(&mut self, idx: usize) {
let s = &mut self.surfaces[idx];
if s.in_use && s.orphaned && s.acquire_count == 0 && s.grant_count == 0 {
let tok = s.backing_token;
*s = SurfaceEntry::default();
if tok != 0 && self.reaped_len < MAX_SURFACES {
self.reaped_tokens[self.reaped_len] = tok;
self.reaped_len += 1;
}
}
}
/// Pops the next opaque backing token for a surface that has been fully
/// reaped (orphaned with zero remaining acquires and grants). Returns `0`
/// when no reaped backings are pending.
pub fn pop_reaped_backing(&mut self) -> u64 {
if self.reaped_len == 0 {
return 0;
}
self.reaped_len -= 1;
let tok = self.reaped_tokens[self.reaped_len];
self.reaped_tokens[self.reaped_len] = 0;
tok
}
/// Registers a surface for `(file_id, device_handle)` on `rm_device_id` with
/// an optional opaque kernel `backing_token` retained until the surface is reaped.
#[allow(clippy::too_many_arguments)]
pub fn register_with_backing(
&mut self,
file_id: u64,
device_handle: u32,
rm_device_id: u32,
use_fd: bool,
plane0_fd: i32,
plane0_offset: u64,
plane0_pitch: u32,
plane0_size: u64,
width: u32,
height: u32,
layout: u32,
format: u32,
backing_token: u64,
) -> Result<u32, i32> {
if file_id == 0 || device_handle == 0 || rm_device_id >= MAX_RM_DEVICES {
return Err(EINVAL);
}
if !use_fd || plane0_fd < 0 {
return Err(EINVAL);
}
if width == 0 || width > MAX_SURFACE_DIM_PX || height == 0 || height > MAX_SURFACE_DIM_PX {
return Err(EINVAL);
}
if layout > 1 {
return Err(EINVAL);
}
let (plane_count, bpp) = match format_plane_count_and_bpp(format) {
Some(v) => v,
None => return Err(EINVAL),
};
// Only single-plane surface registration is wired; reject multi-plane formats explicitly.
if plane_count != 1 {
return Err(EOPNOTSUPP);
}
if plane0_size == 0 || (plane0_offset & 1023) != 0 || plane0_offset >= plane0_size {
return Err(EINVAL);
}
if plane0_pitch == 0 || (layout == 1 && (plane0_pitch & 255) != 0) {
return Err(EINVAL);
}
// Validate pixel row fits byte pitch and complete plane extent fits plane0_size.
let row_bytes = if layout == 1 {
u64::from(plane0_pitch)
} else {
match u64::from(plane0_pitch).checked_mul(64) {
Some(v) => v,
None => return Err(EINVAL),
}
};
let min_row_bytes = match u64::from(width).checked_mul(u64::from(bpp)) {
Some(v) => v,
None => return Err(EINVAL),
};
if row_bytes < min_row_bytes {
return Err(EINVAL);
}
let plane_bytes = match row_bytes.checked_mul(u64::from(height)) {
Some(v) => v,
None => return Err(EINVAL),
};
let plane_end = match plane0_offset.checked_add(plane_bytes) {
Some(v) => v,
None => return Err(EINVAL),
};
if plane_end > plane0_size {
return Err(EINVAL);
}
let mut free_idx = None;
let mut i = 0;
while i < MAX_SURFACES {
if !self.surfaces[i].in_use {
free_idx = Some(i);
break;
}
i += 1;
}
let idx = match free_idx {
Some(v) => v,
None => return Err(ENOSPC),
};
let id = self.alloc_id();
let handle = self.alloc_handle();
self.surfaces[idx] = SurfaceEntry {
in_use: true,
orphaned: false,
surface_id: id,
owner_file_id: file_id,
owner_device_handle: device_handle,
rm_device_id,
owner_surface_handle: handle,
backing_token,
acquire_count: 0,
grant_count: 0,
};
Ok(handle)
}
/// Convenience wrapper around [`Self::register_with_backing`] with `backing_token = 0`.
#[allow(clippy::too_many_arguments)]
pub fn register(
&mut self,
file_id: u64,
device_handle: u32,
rm_device_id: u32,
use_fd: bool,
plane0_fd: i32,
plane0_offset: u64,
plane0_pitch: u32,
plane0_size: u64,
width: u32,
height: u32,
layout: u32,
format: u32,
) -> Result<u32, i32> {
self.register_with_backing(
file_id,
device_handle,
rm_device_id,
use_fd,
plane0_fd,
plane0_offset,
plane0_pitch,
plane0_size,
width,
height,
layout,
format,
0,
)
}
/// Unregisters a surface owned by `(file_id, device_handle, surface_handle)`.
/// Rejects userspace `skip_sync == true` with `EINVAL`. For a valid device,
/// unregistering an absent surface handle is a successful no-op matching stock
/// `nvkms.c`. If acquiring clients or grant fds still reference the surface,
/// marks it orphaned until all references are released (`nvkms-api.h:2680-2708`).
pub fn unregister(
&mut self,
file_id: u64,
device_handle: u32,
surface_handle: u32,
skip_sync: bool,
) -> Result<(), i32> {
if file_id == 0 || device_handle == 0 || skip_sync {
return Err(EINVAL);
}
if surface_handle == 0 {
return Ok(());
}
let mut i = 0;
while i < MAX_SURFACES {
let s = &mut self.surfaces[i];
if s.in_use
&& !s.orphaned
&& s.owner_file_id == file_id
&& s.owner_device_handle == device_handle
&& s.owner_surface_handle == surface_handle
{
s.orphaned = true;
s.owner_file_id = 0;
s.owner_device_handle = 0;
s.owner_surface_handle = 0;
self.reap_if_unused(i);
return Ok(());
}
i += 1;
}
Ok(())
}
/// Associates a fresh `/dev/nvidia-modeset` fd (`grant_file_id`) with an
/// active registered surface (`NVKMS_IOCTL_GRANT_SURFACE`).
pub fn grant(
&mut self,
owner_file_id: u64,
device_handle: u32,
surface_handle: u32,
grant_file_id: u64,
) -> Result<(), i32> {
if owner_file_id == 0
|| device_handle == 0
|| surface_handle == 0
|| grant_file_id == 0
|| grant_file_id == owner_file_id
{
return Err(EINVAL);
}
// Reject duplicate grant on the same fd.
let mut g = 0;
while g < MAX_SURFACE_GRANTS {
if self.grants[g].in_use && self.grants[g].grant_file_id == grant_file_id {
return Err(EINVAL);
}
g += 1;
}
let mut surf_idx = None;
let mut i = 0;
while i < MAX_SURFACES {
let s = &self.surfaces[i];
if s.in_use
&& !s.orphaned
&& s.owner_file_id == owner_file_id
&& s.owner_device_handle == device_handle
&& s.owner_surface_handle == surface_handle
{
surf_idx = Some(i);
break;
}
i += 1;
}
let sidx = match surf_idx {
Some(v) => v,
None => return Err(EINVAL),
};
let mut free_g = None;
g = 0;
while g < MAX_SURFACE_GRANTS {
if !self.grants[g].in_use {
free_g = Some(g);
break;
}
g += 1;
}
let gidx = match free_g {
Some(v) => v,
None => return Err(ENOSPC),
};
let sid = self.surfaces[sidx].surface_id;
self.surfaces[sidx].grant_count = self.surfaces[sidx].grant_count.saturating_add(1);
self.grants[gidx] = SurfaceGrantEntry {
in_use: true,
grant_file_id,
surface_id: sid,
};
Ok(())
}
/// Returns the `rm_device_id` of the non-orphaned surface bound to `grant_file_id`.
pub fn grant_target_rm_device_id(&self, grant_file_id: u64) -> Option<u32> {
let mut g = 0;
while g < MAX_SURFACE_GRANTS {
if self.grants[g].in_use && self.grants[g].grant_file_id == grant_file_id {
let sid = self.grants[g].surface_id;
let mut i = 0;
while i < MAX_SURFACES {
let s = &self.surfaces[i];
if s.in_use && !s.orphaned && s.surface_id == sid {
return Some(s.rm_device_id);
}
i += 1;
}
return None;
}
g += 1;
}
None
}
/// Acquires a granted surface into `(acquirer_file_id, acquirer_device_handle)`'s
/// handle namespace (`NVKMS_IOCTL_ACQUIRE_SURFACE`).
pub fn acquire(
&mut self,
acquirer_file_id: u64,
acquirer_device_handle: u32,
acquirer_rm_device_id: u32,
grant_file_id: u64,
) -> Result<u32, i32> {
if acquirer_file_id == 0 || acquirer_device_handle == 0 || grant_file_id == 0 {
return Err(EINVAL);
}
let mut sid = 0u32;
let mut g = 0;
while g < MAX_SURFACE_GRANTS {
if self.grants[g].in_use && self.grants[g].grant_file_id == grant_file_id {
sid = self.grants[g].surface_id;
break;
}
g += 1;
}
if sid == 0 {
return Err(EINVAL);
}
let mut surf_idx = None;
let mut i = 0;
while i < MAX_SURFACES {
let s = &self.surfaces[i];
if s.in_use
&& !s.orphaned
&& s.surface_id == sid
&& s.rm_device_id == acquirer_rm_device_id
{
surf_idx = Some(i);
break;
}
i += 1;
}
let sidx = match surf_idx {
Some(v) => v,
None => return Err(EINVAL),
};
let mut free_a = None;
let mut a = 0;
while a < MAX_SURFACE_ACQUIRES {
if !self.acquires[a].in_use {
free_a = Some(a);
break;
}
a += 1;
}
let aidx = match free_a {
Some(v) => v,
None => return Err(ENOSPC),
};
let handle = self.alloc_handle();
self.surfaces[sidx].acquire_count = self.surfaces[sidx].acquire_count.saturating_add(1);
self.acquires[aidx] = SurfaceAcquireEntry {
in_use: true,
acquirer_file_id,
acquirer_device_handle,
acquirer_surface_handle: handle,
surface_id: sid,
};
Ok(handle)
}
/// Releases an acquired surface handle (`NVKMS_IOCTL_RELEASE_SURFACE`).
/// For a valid device, releasing an absent acquired handle is a successful
/// no-op matching stock `nvkms.c`.
pub fn release(
&mut self,
acquirer_file_id: u64,
device_handle: u32,
surface_handle: u32,
) -> Result<(), i32> {
if acquirer_file_id == 0 || device_handle == 0 {
return Err(EINVAL);
}
if surface_handle == 0 {
return Ok(());
}
let mut a = 0;
while a < MAX_SURFACE_ACQUIRES {
if self.acquires[a].in_use
&& self.acquires[a].acquirer_file_id == acquirer_file_id
&& self.acquires[a].acquirer_device_handle == device_handle
&& self.acquires[a].acquirer_surface_handle == surface_handle
{
let sid = self.acquires[a].surface_id;
self.acquires[a] = SurfaceAcquireEntry::default();
let mut i = 0;
while i < MAX_SURFACES {
if self.surfaces[i].in_use && self.surfaces[i].surface_id == sid {
self.surfaces[i].acquire_count =
self.surfaces[i].acquire_count.saturating_sub(1);
self.reap_if_unused(i);
break;
}
i += 1;
}
return Ok(());
}
a += 1;
}
Ok(())
}
/// Cleans up all surfaces owned by or acquired under `(file_id, device_handle)`.
pub fn release_device(&mut self, file_id: u64, device_handle: u32) {
let mut a = 0;
while a < MAX_SURFACE_ACQUIRES {
if self.acquires[a].in_use
&& self.acquires[a].acquirer_file_id == file_id
&& self.acquires[a].acquirer_device_handle == device_handle
{
let sid = self.acquires[a].surface_id;
self.acquires[a] = SurfaceAcquireEntry::default();
let mut i = 0;
while i < MAX_SURFACES {
if self.surfaces[i].in_use && self.surfaces[i].surface_id == sid {
self.surfaces[i].acquire_count =
self.surfaces[i].acquire_count.saturating_sub(1);
self.reap_if_unused(i);
break;
}
i += 1;
}
}
a += 1;
}
let mut i = 0;
while i < MAX_SURFACES {
if self.surfaces[i].in_use
&& !self.surfaces[i].orphaned
&& self.surfaces[i].owner_file_id == file_id
&& self.surfaces[i].owner_device_handle == device_handle
{
self.surfaces[i].orphaned = true;
self.surfaces[i].owner_file_id = 0;
self.surfaces[i].owner_device_handle = 0;
self.surfaces[i].owner_surface_handle = 0;
self.reap_if_unused(i);
}
i += 1;
}
}
/// Cleans up all registrations, acquisitions, and grants associated with `file_id`.
pub fn release_file(&mut self, file_id: u64) {
let mut g = 0;
while g < MAX_SURFACE_GRANTS {
if self.grants[g].in_use && self.grants[g].grant_file_id == file_id {
let sid = self.grants[g].surface_id;
self.grants[g] = SurfaceGrantEntry::default();
let mut i = 0;
while i < MAX_SURFACES {
if self.surfaces[i].in_use && self.surfaces[i].surface_id == sid {
self.surfaces[i].grant_count =
self.surfaces[i].grant_count.saturating_sub(1);
self.reap_if_unused(i);
break;
}
i += 1;
}
}
g += 1;
}
let mut a = 0;
while a < MAX_SURFACE_ACQUIRES {
if self.acquires[a].in_use && self.acquires[a].acquirer_file_id == file_id {
let sid = self.acquires[a].surface_id;
self.acquires[a] = SurfaceAcquireEntry::default();
let mut i = 0;
while i < MAX_SURFACES {
if self.surfaces[i].in_use && self.surfaces[i].surface_id == sid {
self.surfaces[i].acquire_count =
self.surfaces[i].acquire_count.saturating_sub(1);
self.reap_if_unused(i);
break;
}
i += 1;
}
}
a += 1;
}
let mut i = 0;
while i < MAX_SURFACES {
if self.surfaces[i].in_use
&& !self.surfaces[i].orphaned
&& self.surfaces[i].owner_file_id == file_id
{
self.surfaces[i].orphaned = true;
self.surfaces[i].owner_file_id = 0;
self.surfaces[i].owner_device_handle = 0;
self.surfaces[i].owner_surface_handle = 0;
self.reap_if_unused(i);
}
i += 1;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@ -390,4 +1043,121 @@ mod tests {
tbl.release_all_for_file(2);
assert!(!tbl.is_owner(0, 2, 9));
}
#[test]
fn test_register_surface() {
let mut reg = SurfaceRegistry::new();
// Reject use_fd == false, bad alignment, bad pitch, bad format, undersized extent
assert_eq!(
reg.register(1, 10, 0, false, 3, 0, 256, 16384, 64, 64, 1, 4),
Err(EINVAL)
);
assert_eq!(
reg.register(1, 10, 0, true, 3, 512, 256, 16384, 64, 64, 1, 4),
Err(EINVAL)
);
assert_eq!(
reg.register(1, 10, 0, true, 3, 0, 128, 16384, 64, 64, 1, 4),
Err(EINVAL)
);
assert_eq!(
reg.register(1, 10, 0, true, 3, 0, 256, 16384, 64, 64, 1, 0xffff_ffff),
Err(EINVAL)
);
// Pitch=256 * height=64 = 16384 > 4096 -> must fail
assert_eq!(
reg.register(1, 10, 0, true, 3, 0, 256, 4096, 64, 64, 1, 4),
Err(EINVAL)
);
// Multi-plane format 19 (Y8___U8V8_N420) must be rejected until multi-plane is wired
assert_eq!(
reg.register(1, 10, 0, true, 3, 0, 256, 16384, 64, 64, 1, 19),
Err(EOPNOTSUPP)
);
// Width 256 * 4 Bpp = 1024 B/row; pitch=4 blocks (256 B) is too narrow -> must fail
assert_eq!(
reg.register(1, 10, 0, true, 4, 1024, 4, 66560, 256, 256, 0, 4),
Err(EINVAL)
);
// Valid pitch (256 B/row * 64 = 16384 B) and block-linear (16 blocks = 1024 B/row * 256 + 1024)
let h1 = reg
.register(1, 10, 0, true, 3, 0, 256, 16384, 64, 64, 1, 4)
.expect("valid pitch surface");
let h2 = reg
.register(1, 10, 0, true, 4, 1024, 16, 263168, 256, 256, 0, 4)
.expect("valid block-linear surface");
assert_ne!(h1, 0);
assert_ne!(h2, h1);
}
#[test]
fn test_unregister_surface() {
let mut reg = SurfaceRegistry::new();
let h = reg
.register(1, 10, 0, true, 3, 0, 256, 16384, 64, 64, 1, 4)
.unwrap();
// Userspace skipSync=1 is rejected
assert_eq!(reg.unregister(1, 10, h, true), Err(EINVAL));
// Wrong file does not unregister owner's surface (no-op success)
assert_eq!(reg.unregister(2, 10, h, false), Ok(()));
// Owner can still grant and unregister it
assert_eq!(reg.grant(1, 10, h, 99), Ok(()));
assert_eq!(reg.unregister(1, 10, h, false), Ok(()));
// Repeat unregister on valid device is an idempotent no-op
assert_eq!(reg.unregister(1, 10, h, false), Ok(()));
}
#[test]
fn test_grant_surface() {
let mut reg = SurfaceRegistry::new();
let h = reg
.register(1, 10, 0, true, 3, 0, 256, 16384, 64, 64, 1, 4)
.unwrap();
// Cannot grant to self or twice on same fd
assert_eq!(reg.grant(1, 10, h, 1), Err(EINVAL));
assert_eq!(reg.grant(1, 10, h, 99), Ok(()));
assert_eq!(reg.grant(1, 10, h, 99), Err(EINVAL));
assert_eq!(reg.grant_target_rm_device_id(99), Some(0));
}
#[test]
fn test_acquire_surface() {
let mut reg = SurfaceRegistry::new();
let h = reg
.register(1, 10, 2, true, 3, 0, 256, 16384, 64, 64, 1, 4)
.unwrap();
reg.grant(1, 10, h, 99).unwrap();
// Wrong rm_device_id fails
assert_eq!(reg.acquire(2, 20, 0, 99), Err(EINVAL));
// Matching rm_device_id succeeds
let ah = reg.acquire(2, 20, 2, 99).expect("valid acquire");
assert_ne!(ah, 0);
// After owner unregisters, new acquires fail on the orphaned surface
reg.unregister(1, 10, h, false).unwrap();
assert_eq!(reg.acquire(3, 30, 2, 99), Err(EINVAL));
}
#[test]
fn test_release_surface() {
let mut reg = SurfaceRegistry::new();
let h = reg
.register_with_backing(1, 10, 0, true, 3, 0, 256, 16384, 64, 64, 1, 4, 0xdead_beef)
.unwrap();
reg.grant(1, 10, h, 99).unwrap();
let ah = reg.acquire(2, 20, 0, 99).unwrap();
// Owner unregisters -> orphaned while acquirer + grant hold references; backing NOT reaped yet
reg.unregister(1, 10, h, false).unwrap();
assert_eq!(reg.pop_reaped_backing(), 0);
// Wrong file release is a no-op and does not release file 2's handle
assert_eq!(reg.release(3, 20, ah), Ok(()));
assert_eq!(reg.release(2, 20, ah), Ok(()));
// Grant fd still alive -> backing still retained
assert_eq!(reg.pop_reaped_backing(), 0);
// Repeat release on valid device is an idempotent no-op
assert_eq!(reg.release(2, 20, ah), Ok(()));
// Closing grant fd drops last reference -> backing reaped now
reg.release_file(99);
assert_eq!(reg.pop_reaped_backing(), 0xdead_beef);
assert_eq!(reg.pop_reaped_backing(), 0);
}
}

View File

@ -567,7 +567,6 @@ def audit_nvkms(stock_dir: pathlib.Path, open_gpu_root: pathlib.Path) -> list[di
for m_case in re.finditer(r"case\s+(NV_RS_KMS_CMD_[A-Z0-9_]+)\s*:\s*return\s+(\w+)\(", our_ms):
macro, fn_name = m_case.group(1), m_case.group(2)
if macro in cmd_macros and fn_name not in (
"nv_rs_modeset_register_surface",
"nv_rs_modeset_clear_unicast_event",
):
ported_idxs.add(cmd_macros[macro])
@ -581,6 +580,11 @@ def audit_nvkms(stock_dir: pathlib.Path, open_gpu_root: pathlib.Path) -> list[di
verified_ffi_tests: dict[int, tuple[str, str]] = {
0: ("nv_rs_nvkms_validate_alloc_device(", "test_alloc_device"),
1: ("nv_rs_nvkms_validate_free_device(", "test_free_device"),
17: ("nv_rs_nvkms_surface_register(", "test_register_surface"),
18: ("nv_rs_nvkms_surface_unregister(", "test_unregister_surface"),
19: ("nv_rs_nvkms_surface_grant(", "test_grant_surface"),
20: ("nv_rs_nvkms_surface_acquire(", "test_acquire_surface"),
21: ("nv_rs_nvkms_surface_release(", "test_release_surface"),
32: ("nv_rs_nvkms_validate_get_next_event(", "test_get_next_event"),
33: ("nv_rs_nvkms_validate_event_interest(", "test_declare_event_interest"),
38: ("nv_rs_nvkms_ownership_grab(", "test_grab_ownership"),