Files
nvdriver/kernel-open/nvidia/rmapi_node.c
ThingsCouldGetDicey 3e1bf7b8c8 perf(rmapi/uvm/pcie): batch sysmem pool reuse & UVM DMA drain, roll back PCIe target on retrain failure (#516)
* fix(pcie): restore link target after retrain register failures

Reuse the existing best-effort timeout rollback for every failure after the endpoint target write succeeds, preserving the original error. Fault injection exposes three failing tests on master; all eight targeted tests, workspace tests, clippy and offline codegen checks pass with the correction. No changes to link policy, capability gates or success path.

* perf(uvm): batch DMA mapping cleanup at node exit

Drain up to 16 live records per leaf-mutex acquisition, preserving bucket order and leaving DMA unmap/page/device releases outside the lock. No changes to insert/lookup/device detach, per-page unmap or mapping permissions. Seven paired CPU-only samples from 1 to 262144 records show 1.30x to 20.85x faster ledger cleanup. Workspace 1409 passed, 150 ignored; clippy, formatting, native codegen and Rust kernel object build pass. Full kernel module and physical/guest testing pending.

* perf(rmapi): batch hot system-page pool reuse

Take up to 32 hot pages per pool mutex acquisition, publish the count once, and clear all reused pages outside the mutex. Preserve LIFO order, partial/empty fallback, admission and cache policy, and allocation failure cleanup. Seven paired host benchmarks show up to 4.72x faster bookkeeping and 4.92x p99 improvement for 16384 fully pooled pages, with single-page and empty-pool parity. 1409 workspace tests pass, 150 ignored; strict clippy, codegen audit, Rust kernel object and offline kernel gates pass. Full C module/guest/physical validation pending.

---------

Co-authored-by: Nick <your-email@example.com>
2026-12-05 14:19:17 -08:00

5746 lines
224 KiB
C

// SPDX-License-Identifier: MIT
/* Character-device adapter of the Rust RM API nodes: one control node and one device node
* per GPU. User memory is copied here; every rule of the protocol lives in Rust
* (src/nvidia/src/rmapi). */
#include <linux/bitops.h>
#include <linux/cache.h>
#include <linux/capability.h>
#include <linux/cdev.h>
#include <linux/cpumask.h>
#include <linux/cred.h>
#include <linux/ctype.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/fdtable.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/highmem.h>
#include <linux/io.h>
#include <linux/miscdevice.h>
#include <linux/version.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/namei.h>
#include <linux/pci.h>
#include <linux/pid.h>
#include <linux/pid_namespace.h>
#include <linux/poll.h>
#include <linux/proc_fs.h>
#include <linux/rcupdate.h>
#include <linux/scatterlist.h>
#include <linux/sched.h>
#include <linux/sched/signal.h>
#include <linux/sched/task.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/topology.h>
#include <linux/uaccess.h>
#include <linux/workqueue.h>
#include <linux/vmalloc.h>
#ifdef CONFIG_X86
#include <asm/cpufeature.h>
#include <asm/processor.h>
#include <asm/set_memory.h>
#include <asm/tsc.h>
#endif
#ifdef CONFIG_COMPAT
#include <linux/compat.h>
#endif
#include "dmabuf_p2p.h"
#include "gpu_owner.h"
#include "ioctl_policy.h"
#include "pci_adapter.h"
#include "registry_adapter.h"
#include "rmapi_node.h"
#include "uvm_node.h"
#ifdef CONFIG_PROC_FS
#ifdef __has_include
#if __has_include(<generated/compile.h>)
#include <generated/compile.h>
#endif
#endif
#endif
struct nv_rs_rmapi_gpu {
u32 domain;
u8 bus, slot, function, reserved;
u16 vendor, device;
u32 irq;
u64 bar0, bar0_size, bar1, bar1_size, bar2, bar2_size;
u16 subsystem_vendor, subsystem;
u8 revision;
u32 boot0;
u32 pci_class;
};
struct nv_rs_rmapi_write { u64 address; const u8 *data; size_t length; u8 inline_data[64]; bool use_inline; };
extern size_t nv_rs_rmapi_state_size(void);
extern size_t nv_rs_rmapi_state_align(void);
extern int nv_rs_rmapi_init(void *node);
extern int nv_rs_rmapi_gpu_add(void *node, const struct nv_rs_rmapi_gpu *gpu);
extern int nv_rs_rmapi_gpu_remove(void *node, u32 domain, u8 bus, u8 slot);
extern int nv_rs_rmapi_gpu_minor(void *node, u32 domain, u8 bus, u8 slot);
extern int nv_rs_rmapi_gpu_uuid(void *node, u32 gpu_id, u8 *out_uuid);
extern int nv_rs_rmapi_prepare(void *node, u64 owner, u64 file_owner, bool admin, bool control_node,
u32 gpu_access, u32 escape, u8 *top, size_t top_length,
u64 *address, size_t *length, int *result);
extern int nv_rs_rmapi_prepare_alloc(bool control_node, const u8 *top, size_t top_length,
u64 *address, size_t *length);
extern int nv_rs_rmapi_nested_plan(const u8 *top, size_t top_length, const u8 *params,
size_t params_length, u64 *input, u64 *output, size_t *length);
extern int nv_rs_rmapi_execute(void *node, u64 owner, u64 file_owner, bool admin, bool control_node,
u32 gpu_access, u32 escape, u8 *top, size_t top_length,
u8 *params, size_t params_length, u8 *nested, size_t nested_length,
struct nv_rs_rmapi_write *writes, u32 *write_count);
extern int nv_rs_rmapi_gpu_open(void *node, u32 minor);
extern u32 nv_rs_rmapi_attach_register_count(void);
extern u32 nv_rs_rmapi_attach_register(u32 index);
extern bool nv_rs_rmapi_gpu_needs_registers(void *node, u32 minor);
extern int nv_rs_rmapi_gpu_attach_registers(void *node, u32 minor, const u32 *values, u32 count);
struct nv_rs_rmapi_cpu_info {
u32 cpu_type;
u32 capabilities;
u32 clock_mhz;
u32 l1_data_cache_kb;
u32 l2_data_cache_kb;
u32 data_cache_line_bytes;
u32 num_logical_cpus;
u32 num_physical_cpus;
u8 name[52];
u32 family;
u32 model;
u8 stepping;
u32 cores_on_die;
};
extern int nv_rs_rmapi_set_cpu_info(void *node, const struct nv_rs_rmapi_cpu_info *info);
extern int nv_rs_rmapi_set_host_bridge(void *node, u16 vendor, u16 device);
extern int nv_rs_rmapi_set_force_p2p(void *node, u32 force_p2p_mask);
extern bool nv_rs_rmapi_set_gsp_abi(u32 gsp_abi_ver);
extern void nv_rs_rmapi_set_strict_version_check(bool strict);
extern size_t nv_rs_rmapi_get_driver_version(char *version, size_t len);
extern void nv_rs_rmapi_set_driver_version(const char *version, size_t len);
extern int nv_rs_rmapi_gpu_release(void *node, u32 minor);
extern u32 nv_rs_rmapi_register_fd(bool caller_registered, bool target_control,
bool target_registered, bool same_file);
/* the Rust DmabufResolved and DmabufRange */
struct nv_rs_dmabuf_resolved {
u32 gpu_minor;
u32 gpu_id;
u64 client_owner;
u32 num_ranges;
u32 reserved;
};
struct nv_rs_dmabuf_range {
u64 bar1_offset;
u64 size;
};
extern u32 nv_rs_rmapi_resolve_dmabuf_object(void *node, u64 owner, u64 control_owner,
bool admin, u32 h_client,
u32 h_memory, u64 offset, u64 size,
struct nv_rs_dmabuf_resolved *out,
struct nv_rs_dmabuf_range *ranges, u32 max_ranges,
struct nv_rs_dmabuf_pin *pin);
extern void nv_rs_rmapi_dmabuf_unpin(void *node, const struct nv_rs_dmabuf_pin *pin);
extern int nv_rs_rmapi_copy_fault(u32 escape, u8 *top, size_t top_length, bool output);
extern int nv_rs_rmapi_close(void *node, u64 owner);
extern u32 nv_rs_rmapi_rc_recover_fault(u32 gpu_id, u64 inst_ptr, u32 xid_code,
u32 *ch_out, u32 *tsg_out, u32 *diag_out);
extern bool nv_rs_modeset_register_gpu(u32 gpu_id, u32 domain, u8 bus, u8 slot, u8 function,
void *os_device_ptr);
extern bool nv_rs_modeset_unregister_gpu(u32 gpu_id);
extern u8 nv_rs_uvm_dma_bits_for_boot0(u32 boot0);
struct nv_rs_gpu_nice_row {
u32 pid;
u32 uid;
s32 linux_nice;
s32 gpu_nice;
u64 timeslice_us;
u64 start_time;
u16 gr_tsgs;
u16 ce_tsgs;
u16 other_tsgs;
u8 has_override;
u8 is_desktop;
u8 class_id;
u8 interleave;
u8 gfx_preempt;
u8 compute_preempt;
char comm[16];
u8 interleave_fallback;
u8 ambiguous_pid;
u8 pad[2];
};
extern int nv_rs_gpu_nice_set_policy(void *node, int auto_nice, int desktop_boost,
int preempt_policy, bool drain);
extern void nv_rs_gpu_nice_get_policy(void *node, u32 *auto_out, u32 *desktop_out, u32 *preempt_out,
u32 *pids_out, u32 *tsgs_out);
extern void nv_rs_gpu_nice_refresh_fallbacks(void *node);
extern int nv_rs_gpu_nice_get_row(void *node, u32 index, struct nv_rs_gpu_nice_row *out);
extern u32 nv_rs_gpu_nice_active_count(void *node);
extern bool nv_rs_gpu_nice_has_tracked(void *node);
extern u32 nv_rs_gpu_nice_list_pids(void *node, u32 *out_pids, u32 cap);
extern int nv_rs_gpu_nice_query_pid(void *node, u32 pid, u64 live_start_time, u32 *uid_out,
s32 *eff_nice_out, s32 *linux_nice_out, u8 *has_override_out);
extern s32 nv_rs_gpu_nice_preview_nice(void *node, u32 pid, u64 live_start_time, s32 live_nice,
const u8 *comm, size_t comm_len,
bool live_has_desktop_cap, bool ignore_override);
extern int nv_rs_gpu_nice_set_pid(void *node, u32 pid, u64 start_time, u32 uid, const u8 *comm,
size_t comm_len, int has_desktop_cap, s32 linux_nice,
s32 override_nice, bool clear_override, int admin_desktop);
extern int nv_rs_gpu_nice_sync_pid(void *node, u32 pid, u64 start_time, u32 uid, s32 linux_nice,
const u8 *comm, size_t comm_len, int has_desktop_cap,
bool alive, bool drain);
extern void nv_rs_gpu_nice_drain(void *node, bool tick_backoff);
extern int nv_rs_gpu_nice_desktop_comm(void *node, bool add, const u8 *name, size_t name_len);
extern size_t nv_rs_gpu_nice_copy_custom_comms(void *node, u8 *out, size_t cap);
/* One lock for the whole node: it stands in for the original's RM API lock. User copies
* are made outside it. */
static DEFINE_MUTEX(nv_rs_rmapi_lock);
/* The UVM node (uvm_node.c) and the GA10x code (src/nvidia/kernel/ga10x.rs) take this lock too where they change GPU
* state: the object tables, GSP-RM's RPC channel, video memory through the BAR0 window. Order: this lock, then the UVM
* lock. This lock is held across pin_user_pages (mmap_lock) and the UVM lock is taken under mmap_lock (the UVM .mmap
* and vm_ops->close), so the UVM-first order closed a cycle through mmap_lock (see uvm_node.c). */
void nv_rs_rmapi_node_lock(void);
void nv_rs_rmapi_node_lock(void)
{
mutex_lock(&nv_rs_rmapi_lock);
}
int nv_rs_rmapi_node_trylock(void);
int nv_rs_rmapi_node_trylock(void)
{
return mutex_trylock(&nv_rs_rmapi_lock);
}
void nv_rs_rmapi_node_unlock(void);
void nv_rs_rmapi_node_unlock(void)
{
mutex_unlock(&nv_rs_rmapi_lock);
}
/* Leaf mutex serializing GLOBAL_VERSION_STORE reads/writes so preemptible and PREEMPT_RT
* kernels cannot livelock a same-CPU reader against a preempted writer. Zero inner locks. */
static DEFINE_MUTEX(nv_rs_version_lock_mtx);
void nv_rs_version_lock(void);
void nv_rs_version_lock(void)
{
mutex_lock(&nv_rs_version_lock_mtx);
}
void nv_rs_version_unlock(void);
void nv_rs_version_unlock(void)
{
mutex_unlock(&nv_rs_version_lock_mtx);
}
static void *nv_rs_rmapi_state;
static DEFINE_SPINLOCK(nv_rs_gpu_nice_sched_lock);
static atomic_t nv_rs_gpu_nice_stopping = ATOMIC_INIT(0);
static void nv_rs_gpu_nice_work_fn(struct work_struct *work);
static DECLARE_DELAYED_WORK(nv_rs_gpu_nice_work, nv_rs_gpu_nice_work_fn);
static int gpu_nice_auto = 1;
static int gpu_desktop_boost = 1;
static void nv_rs_gpu_nice_apply_params_locked(bool drain)
{
if (!nv_rs_rmapi_state)
return;
(void)nv_rs_gpu_nice_set_policy(nv_rs_rmapi_state,
READ_ONCE(gpu_nice_auto) ? 1 : 0,
READ_ONCE(gpu_desktop_boost) ? 1 : 0,
-1,
drain);
}
static void nv_rs_gpu_nice_schedule_if_active(bool has_tracked)
{
unsigned long flags;
if (!has_tracked)
return;
spin_lock_irqsave(&nv_rs_gpu_nice_sched_lock, flags);
if (!atomic_read(&nv_rs_gpu_nice_stopping))
schedule_delayed_work(&nv_rs_gpu_nice_work, msecs_to_jiffies(250));
spin_unlock_irqrestore(&nv_rs_gpu_nice_sched_lock, flags);
}
static int nv_rs_gpu_nice_param_set(const char *val, const struct kernel_param *kp)
{
int v = 0;
int rc = kstrtoint(val, 0, &v);
if (rc)
return rc;
if (v != 0 && v != 1)
return -EINVAL;
if (nv_rs_rmapi_state && !atomic_read(&nv_rs_gpu_nice_stopping)) {
bool has_tracked = false;
if (mutex_lock_interruptible(&nv_rs_rmapi_lock))
return -ERESTARTSYS;
WRITE_ONCE(*(int *)kp->arg, v);
if (nv_rs_rmapi_state && !atomic_read(&nv_rs_gpu_nice_stopping)) {
nv_rs_gpu_nice_apply_params_locked(true);
has_tracked = nv_rs_gpu_nice_has_tracked(nv_rs_rmapi_state);
}
mutex_unlock(&nv_rs_rmapi_lock);
nv_rs_gpu_nice_schedule_if_active(has_tracked);
} else {
WRITE_ONCE(*(int *)kp->arg, v);
}
return 0;
}
static const struct kernel_param_ops nv_rs_gpu_nice_param_ops = {
.set = nv_rs_gpu_nice_param_set,
.get = param_get_int,
};
module_param_cb(gpu_nice_auto, &nv_rs_gpu_nice_param_ops, &gpu_nice_auto, 0644);
MODULE_PARM_DESC(gpu_nice_auto,
"Automatically map Linux process nice (-20..+19) to GPU TSG priority (1=on, 0=off)");
module_param_cb(gpu_desktop_boost, &nv_rs_gpu_nice_param_ops, &gpu_desktop_boost, 0644);
MODULE_PARM_DESC(gpu_desktop_boost,
"Protect interactive desktop/compositor GPU workloads with HIGH interleave (1=on, 0=off)");
/* Caller holds rcu_read_lock(). Returns a live thread in `leader`'s thread group,
* or NULL when the entire thread group has exited (including unreaped zombies). */
static struct task_struct *nv_rs_live_tg_thread(struct task_struct *leader)
{
struct signal_struct *sig;
struct task_struct *t;
if (!leader || !pid_alive(leader))
return NULL;
if (!READ_ONCE(leader->exit_state))
return leader;
sig = READ_ONCE(leader->signal);
if (!sig)
return NULL;
__for_each_thread(sig, t) {
if (!READ_ONCE(t->exit_state))
return t;
}
return NULL;
}
/* Caller holds rcu_read_lock(). Resolves TGID-instance start time from `leader` and
* derives live task metadata (nice, uid, euid, desktop capability, comm) from the same
* `nv_rs_live_tg_thread(leader)` selector used by polling and ioctl paths. */
static bool nv_rs_sample_tg_meta_rcu(struct task_struct *leader,
u64 *start_time_out,
s32 *nice_out,
u32 *uid_out,
u32 *euid_out,
u8 *comm_out,
size_t comm_len,
bool *trusted_cap_out)
{
struct task_struct *live = nv_rs_live_tg_thread(leader);
const struct cred *cred;
if (!live)
return false;
cred = __task_cred(live);
if (start_time_out)
*start_time_out = leader->start_boottime;
if (nice_out)
*nice_out = task_nice(live);
if (uid_out)
*uid_out = cred ? from_kuid_munged(&init_user_ns, cred->uid) : (u32)-1;
if (euid_out)
*euid_out = cred ? from_kuid_munged(&init_user_ns, cred->euid) : (u32)-1;
if (trusted_cap_out) {
*trusted_cap_out = cred && cred->user_ns == &init_user_ns &&
(cap_raised(cred->cap_effective, CAP_SYS_NICE) ||
cap_raised(cred->cap_effective, CAP_SYS_ADMIN));
}
if (comm_out && comm_len) {
size_t n = min_t(size_t, comm_len - 1, TASK_COMM_LEN - 1);
task_lock(live);
memcpy(comm_out, live->comm, n);
task_unlock(live);
comm_out[n] = '\0';
}
return true;
}
static struct task_struct *nv_rs_current_tg_leader_rcu(void)
{
struct task_struct *leader = READ_ONCE(current->group_leader);
return leader ? leader : current;
}
static int nv_rs_pid_info(u32 init_pid, u64 *start_time_out, s32 *nice_out, u32 *uid_out,
u32 *euid_out, u8 *comm_out, size_t comm_len, bool *trusted_cap_out)
{
struct pid *p;
struct task_struct *leader;
int rc = -ESRCH;
if (!init_pid)
return -EINVAL;
rcu_read_lock();
p = find_pid_ns((pid_t)init_pid, &init_pid_ns);
leader = p ? pid_task(p, PIDTYPE_TGID) : NULL;
if (nv_rs_sample_tg_meta_rcu(leader, start_time_out, nice_out, uid_out, euid_out,
comm_out, comm_len, trusted_cap_out))
rc = 0;
rcu_read_unlock();
return rc;
}
static void nv_rs_gpu_nice_reap_dead_locked(void)
{
u32 pids[64];
u32 count, i;
if (!nv_rs_rmapi_state)
return;
count = nv_rs_gpu_nice_list_pids(nv_rs_rmapi_state, pids, ARRAY_SIZE(pids));
for (i = 0; i < count; i++) {
u64 st = 0;
if (nv_rs_pid_info(pids[i], &st, NULL, NULL, NULL, NULL, 0, NULL) != 0) {
(void)nv_rs_gpu_nice_sync_pid(nv_rs_rmapi_state, pids[i], 0, 0, 0, NULL, 0,
-1, false, false);
} else {
(void)nv_rs_gpu_nice_query_pid(nv_rs_rmapi_state, pids[i], st, NULL, NULL, NULL,
NULL);
}
}
}
static void nv_rs_gpu_nice_sync_all_locked(bool tick_backoff)
{
u32 pids[64];
u32 count, i;
if (!nv_rs_rmapi_state)
return;
nv_rs_gpu_nice_apply_params_locked(false);
count = nv_rs_gpu_nice_list_pids(nv_rs_rmapi_state, pids, ARRAY_SIZE(pids));
for (i = 0; i < count; i++) {
u64 start_time = 0;
s32 lnice = 0;
u32 uid = 0;
bool trusted_cap = false;
u8 comm[16] = { 0 };
int rc = nv_rs_pid_info(pids[i], &start_time, &lnice, &uid, NULL, comm, sizeof(comm),
&trusted_cap);
(void)nv_rs_gpu_nice_sync_pid(nv_rs_rmapi_state, pids[i], start_time, uid, lnice,
(rc == 0) ? comm : NULL,
(rc == 0) ? strnlen((const char *)comm, sizeof(comm)) : 0,
(rc == 0) ? (trusted_cap ? 1 : 0) : -1,
rc == 0, false);
}
nv_rs_gpu_nice_drain(nv_rs_rmapi_state, tick_backoff);
}
static void nv_rs_gpu_nice_work_fn(struct work_struct *work)
{
bool has_tracked = false;
(void)work;
if (atomic_read(&nv_rs_gpu_nice_stopping))
return;
mutex_lock(&nv_rs_rmapi_lock);
if (nv_rs_rmapi_state && !atomic_read(&nv_rs_gpu_nice_stopping)) {
nv_rs_gpu_nice_sync_all_locked(true);
has_tracked = nv_rs_gpu_nice_has_tracked(nv_rs_rmapi_state);
}
mutex_unlock(&nv_rs_rmapi_lock);
nv_rs_gpu_nice_schedule_if_active(has_tracked);
}
#define NV_RS_RMAPI_MAX_GPUS 32
#define NV_RS_ESC_RM_GET_EVENT_DATA 0x52
#define NV_RS_ESC_REGISTER_FD 0xc9
#define NV_RS_ESC_ALLOC_OS_EVENT 0xce
#define NV_RS_ESC_FREE_OS_EVENT 0xcf
#define NV_RS_ESC_QUERY_DEVICE_INTR 0xd5
#define NV_RS_ESC_SET_NUMA_STATUS 0xd8
#define NV_RS_ESC_EXPORT_TO_DMABUF_FD 0xd9
#define NV_RS_DMABUF_EXPORT_IOCTL_SIZE 2608U
struct nv_rs_file_map_record {
u64 owner;
void *alloc_ptr;
u64 page_index;
u64 io_phys;
u64 io_bytes;
u32 protection;
u32 caching;
bool is_io;
};
struct nv_rs_io_scatter_seg {
u64 io_phys;
u64 io_bytes;
};
struct nv_rs_io_scatter {
u32 count;
u32 pad;
struct nv_rs_io_scatter_seg segs[];
};
struct nv_rs_extent {
u64 base;
u64 last;
};
extern int nv_rs_file_map_insert_alloc(u64 owner, void *alloc_ptr, u64 page_index,
u32 protection, u32 caching);
extern int nv_rs_file_map_insert_io(u64 owner, u64 io_phys, u64 io_bytes,
u32 protection, u32 caching);
extern int nv_rs_file_map_insert_io_scatter(u64 owner, void *scatter_ptr, u64 io_bytes,
u32 protection, u32 caching);
extern bool nv_rs_file_map_get(u64 owner, struct nv_rs_file_map_record *out);
extern bool nv_rs_file_map_take(u64 owner, struct nv_rs_file_map_record *out);
extern void *nv_rs_file_map_remove(u64 owner);
extern u32 nv_rs_gpu_slot_activate(u32 minor, u32 gpu_id, u64 bar0, u64 bar0_size,
u64 bar1, u64 bar1_size);
extern u32 nv_rs_gpu_slot_deactivate(u32 minor);
extern bool nv_rs_gpu_slot_is_live_gen(u32 minor, u32 generation);
extern bool nv_rs_gpu_slot_set_numa(u32 minor, s32 status);
extern bool nv_rs_gpu_slot_validate_bar0(u32 minor, u32 generation, u64 offset, u64 length,
u64 *out_phys);
extern bool nv_rs_gpu_slot_validate_bar1(u32 minor, u32 generation, u64 aligned_off,
u64 aligned_len, u64 raw_off, u64 *out_io_phys,
u64 *out_user_addr);
/* The opened file is the owner of the clients allocated through it. `gpu` is the device
* node's minor number in the Rust GPU table, or -1 for the control node. `control` is the
* control file NV_ESC_REGISTER_FD associated with this file; the reference is held until
* release, as the original holds the control file's reference. Per-file mmap contexts live
* in Rust's `FileMappingLedger` (`src/nvidia/src/rmapi/alloc_registry.rs`). */
struct nv_rs_rmapi_file {
u64 owner;
int gpu;
/* Generation of the device node the file was opened on: a file that outlives its GPU
* must not count for a later GPU that reuses the minor number. */
unsigned int generation;
struct file *control;
struct file *file;
struct file *userd_control;
unsigned long userd_pgoff;
bool userd_file;
u32 userd_gpu_id;
u32 userd_block;
/* One reference per successful RM map, protected by the USERD lock. */
u32 userd_map_refs;
struct list_head userd_link;
wait_queue_head_t wait;
/* bit 0 = a dataless OS event was posted to this file (nv_rs_rmapi_file_post) */
unsigned long events;
};
struct nv_rs_rmapi_gpu_node {
struct miscdevice misc;
char name[32];
char bdf[32];
bool live;
bool pascal_userd_gpu;
bool userd_runtime_live;
bool userd_pm_lost;
unsigned int generation;
/* Register access of the GPU (nv_rs_rmapi_node_gpu_reader); NULL without one. */
int (*read32)(void *cookie, u64 offset, u32 *value);
void (*release)(void *cookie);
void *cookie;
struct nv_rs_gpu_owner *owner;
struct device *dev;
struct pci_dev *pdev;
u32 gpu_id;
u32 boot0;
u8 dma_bits;
u16 device_id;
u32 irq;
bool is_platform;
atomic_t runtime_start_users;
atomic_t idle_pstate_mode;
atomic64_t idle_pstate_transitions;
atomic64_t idle_pstate_total_secs;
atomic64_t power_cap_mw;
atomic_t tensor_fp32_rate;
int minor_index;
#ifdef CONFIG_PROC_FS
struct proc_dir_entry *proc_dir;
struct proc_dir_entry *caps_dir;
#endif
};
static DECLARE_WAIT_QUEUE_HEAD(nv_rs_rmapi_owner_wq);
#define NV_RS_RMAPI_ATTACH_REGISTERS 32
/* Indexed by the minor number the Rust table gave the GPU; guarded by nv_rs_rmapi_lock. */
static struct nv_rs_rmapi_gpu_node nv_rs_rmapi_gpu_nodes[NV_RS_RMAPI_MAX_GPUS];
static DEFINE_SPINLOCK(nv_rs_rmapi_gpu_dev_lock);
static DEFINE_MUTEX(nv_rs_rmapi_alloc_lock);
/* Revoke serializes zaps and keeps file contexts alive across the unlocked zap.
* mmap/fault take only USERD then allocation lock, never the revoke or RM lock. */
static DEFINE_MUTEX(nv_rs_rmapi_userd_revoke_lock);
static DEFINE_MUTEX(nv_rs_rmapi_userd_lock);
static LIST_HEAD(nv_rs_rmapi_userd_files);
static unsigned long nv_rs_rmapi_userd_last_pgoff;
static const struct file_operations nv_rs_rmapi_operations;
static const struct file_operations nv_rs_rmapi_gpu_operations;
static struct nv_rs_rmapi_file *nv_rs_rmapi_context(struct file *file, int gpu)
{
struct nv_rs_rmapi_file *context = kzalloc(sizeof(*context), GFP_KERNEL);
if (!context)
return NULL;
context->owner = (u64)(unsigned long)context;
context->gpu = gpu;
context->file = file;
INIT_LIST_HEAD(&context->userd_link);
init_waitqueue_head(&context->wait);
return context;
}
/* System memory of the RM API (class 0x3e): the operating-system side the Rust provider
* src/nvidia/kernel/rmapi_memory.rs calls. Every function below runs under
* nv_rs_rmapi_lock, from an ioctl or a release of one of this driver's RM API nodes; none
* touches a device. The pages are ordinary kernel pages. On x86 an allocation of the
* uncached or write-combined cache type gets an uncached kernel mapping and user mappings
* of its type, as the original's (nv_set_memory_type, nv_encode_caching); elsewhere it
* stays cached. Pinned user pages (0x71) whose range lies wholly in uncached user mappings of
* such allocations get uncached kernel and user mappings, those wholly in write-combined ones
* write-combined mappings; any other range that lies partly in them is refused
* (NV_ERR_INVALID_ADDRESS).
*
* An allocation lives while it has users: the RM object (until nv_rs_rmapi_os_free_pages)
* and every file that carries a mapping context of it (until the file is released; the
* original defers its nv_free_pages the same way), and every pinned-user-pages record whose
* range was pinned through a user mapping of it (until that record is destroyed). User
* mappings do not count: the page references vm_insert_page took keep their pages after the
* record is gone. */
#define NV_RS_RMAPI_MEMORY_MAX_PAGES ((256ull << 20) >> PAGE_SHIFT)
static u64 nv_rs_rmapi_memory_max_pages(void)
{
u64 live_gpus = 0;
u64 base_pages;
int i;
for (i = 0; i < NV_RS_RMAPI_MAX_GPUS; i++) {
if (nv_rs_rmapi_gpu_nodes[i].live)
live_gpus++;
}
if (live_gpus == 0)
live_gpus = 1;
base_pages = live_gpus * NV_RS_RMAPI_MEMORY_MAX_PAGES;
if (nv_rs_runtime_engines()) {
u64 ram_half = (u64)totalram_pages() / 2;
if (ram_half > base_pages)
return ram_half;
}
return base_pages;
}
/* Ceiling for every page this file holds, allocated or pinned user memory together: 7/8 of
* RAM, so the two budgets cannot add up past what the host has. */
static u64 nv_rs_rmapi_total_max_pages(void)
{
u64 ram = (u64)totalram_pages();
return ram - ram / 8;
}
#define NV_RS_STATUS_INSUFFICIENT_RESOURCES 0x1a
#define NV_RS_STATUS_INVALID_ADDRESS 0x1e
#define NV_RS_STATUS_INVALID_ARGUMENT 0x1f
#define NV_RS_STATUS_NO_MEMORY 0x51
#define NV_RS_STATUS_NOT_SUPPORTED 0x56
#define NV_RS_STATUS_OBJECT_NOT_FOUND 0x57
#define NV_RS_STATUS_STATE_IN_USE 0x63
/* Rust-owned allocation/refcount/budget registry (src/nvidia/kernel/rmapi_memory.rs). */
bool nv_rs_alloc_reg_can_admit(u64 count, bool user_pinned, u64 pool_pages,
u64 total_max, u64 mem_max);
bool nv_rs_alloc_reg_insert(void *alloc_ptr, u64 count, bool user_pinned, u64 *out_token);
void *nv_rs_alloc_reg_find(u64 token);
void *nv_rs_alloc_reg_retain(u64 token);
bool nv_rs_alloc_reg_retain_ptr(void *alloc_ptr);
/* The cache type of a range pinned for class 0x71 (PinnedRangeCache in src/nvidia/src/rmapi/alloc_registry.rs):
* NV_MEMORY_* 0, 1 or 2, or NV_RS_PINNED_RANGE_REFUSED. */
#define NV_RS_PINNED_RANGE_REFUSED 0xffffffffu
u64 nv_rs_pinned_area_bytes(u64 start, u64 end, u64 vm_start, u64 vm_end);
u32 nv_rs_pinned_range_cache(u64 range_bytes, u64 uncached_bytes, u64 write_combined_bytes);
/* The most allocations a range pinned for class 0x71 may lie in user mappings of, and the most it holds
* (PinnedSources in alloc_registry.rs); past it the range is refused with NV_ERR_INSUFFICIENT_RESOURCES. */
#define NV_RS_PINNED_SOURCES_MAX 1024u
bool nv_rs_pinned_sources_add(void **owners, u64 *owner_count, void **sources, u64 *source_count, u64 capacity,
void *owner, void *const *held, u64 held_count);
bool nv_rs_alloc_reg_mark_freed_and_put(u64 token, void **out_ptr);
bool nv_rs_alloc_reg_put_ptr(void *alloc_ptr);
void nv_rs_alloc_reg_for_each(void (*cb)(void *alloc_ptr, void *ctx), void *ctx);
u64 nv_rs_alloc_reg_total_pages(void);
void *nv_rs_alloc_reg_pop_any(void);
void nv_rs_alloc_reg_release_storage(void);
void *nv_rs_dma_reg_find(void *alloc_ptr, u32 gpu_id, void *dev_ptr);
bool nv_rs_dma_reg_insert(void *alloc_ptr, u32 gpu_id, void *dev_ptr, void *dm_ptr);
void *nv_rs_dma_reg_pop_for_alloc(void *alloc_ptr);
void *nv_rs_dma_reg_pop_for_dev(void *dev_ptr);
struct nv_rs_rmapi_dma_map {
struct device *dev;
u32 gpu_id;
bool contiguous;
u64 count;
/* The whole allocation mapped in one scatterlist (`sg_mapped`), as the original maps every allocation of more
* than one page (nv_dma_map_pages -> nv_dma_map_scatterlist). Otherwise each page is mapped on its own as it is
* first asked for. */
struct sg_table sgt;
bool sg_mapped;
u64 encoded[]; /* 0 = unmapped; otherwise (u64)dma_addr + 1 */
};
struct nv_rs_ext_release_work {
struct work_struct work;
void (*release_fn)(void *priv);
void *release_priv;
struct module *release_owner;
};
static struct workqueue_struct *nv_rs_ext_release_wq;
static void nv_rs_ext_release_work_fn(struct work_struct *work)
{
struct nv_rs_ext_release_work *rel =
container_of(work, struct nv_rs_ext_release_work, work);
void (*fn)(void *) = rel->release_fn;
void *priv = rel->release_priv;
struct module *owner = rel->release_owner;
kfree(rel);
if (fn)
fn(priv);
if (owner)
module_put(owner);
}
struct nv_rs_rmapi_alloc {
u64 token, count;
u32 cache;
bool contiguous;
bool user_pinned;
bool writable;
/* Pre-mapped DMA addresses owned externally (e.g. imported PRIME DMA-BUF sg_table
* exported via DRM_IOCTL_NVIDIA_GEM_EXPORT_DMABUF_MEMORY). `pages[]` has 0 entries;
* GPU DMA lookups read `external_dma_addrs[]` directly and final teardown defers
* `external_rel_work` onto `nv_rs_ext_release_wq` outside `nv_rs_rmapi_lock`. */
bool external_dma;
/* `cache` is uncached or write-combined and the kernel mapping of the pages was made uncached
* (nv_rs_sysmem_make_uncached): user mappings carry `cache`, the kernel mapping (vmap) is uncached as the
* original's for either type, and the pages get their write-back attribute back before they are freed or
* pooled. For pinned user pages (`user_pinned`, nv_rs_rmapi_os_lock_user_pages): every page of the range lies in
* a user mapping of such allocations, all of one type, which is `cache`; kernel and user mappings follow it and
* the pages' attribute stays their allocation's. */
bool kernel_uc;
/* Pinned user pages: the allocations of this node whose user mappings the range was pinned through, each once
* however many areas of the range map it and holding one use until this record is destroyed, so none restores
* write-back, pools or frees its pages while this record still pins and maps them. Never another pinned record
* (nv_rs_rmapi_pin_scan). */
struct nv_rs_rmapi_alloc **sources;
u64 source_count;
u32 external_gpu_id;
u64 *external_dma_addrs;
struct nv_rs_ext_release_work *external_rel_work;
void *kernel;
struct page *pages[];
};
/* The user mappings of system memory (nv_rs_rmapi_mmap); vm_private_data is the allocation. */
static const struct vm_operations_struct nv_rs_rmapi_vm_operations;
static unsigned long nv_rs_rmapi_gpu_cache_flushes;
static atomic64_t nv_rs_rmapi_kvalloc_live = ATOMIC64_INIT(0);
/*
* System memory page pool with client-close trimming (ported from
* NVreg_SystemMemoryPoolRetainMB).
*
* Pooled pages are subtracted from MemAvailable until reclaimed, so on
* unified-memory systems (where every GPU allocation is system memory) a
* large pool left behind after a CUDA process exits looks like a leak.
* 0 (default): return all pooled pages to the OS immediately / on client close.
* -1: disable trimming on client close (pool grows for reuse until unload).
* >0: retain up to this many MiB across client closes.
*/
static int system_memory_pool_retain_mb;
module_param(system_memory_pool_retain_mb, int, 0644);
MODULE_PARM_DESC(system_memory_pool_retain_mb,
"MiB of freed system memory pages to retain in pool on client close (0=trim all, -1=disable trim)");
module_param_named(NVreg_SystemMemoryPoolRetainMB, system_memory_pool_retain_mb, int, 0644);
/*
* Configurable PCIe P2P override bitmask (default 0x11 = PCIe BAR1 P2P Read+Write
* unlocked; pass 0x211 to also opt into PCIe P2P Atomics).
*/
static unsigned int force_p2p = 0x11;
module_param(force_p2p, uint, 0444);
MODULE_PARM_DESC(force_p2p,
"PCIe P2P override bitmask (default 0x11 = Read+Write; 0x211 = Read+Write+Atomics)");
module_param_named(NVreg_ForceP2P, force_p2p, uint, 0444);
/*
* GSP-RM wire protocol ABI version for Turing-Blackwell-Rubin GPUs:
* 620 (default) = 620.70.06 MCTP+NVDM+GMCAPI framing & firmware paths
* 580 = 580.178.04 legacy 0x30 XOR-checksum framing & firmware paths
*/
static unsigned int gsp_abi = 620;
module_param(gsp_abi, uint, 0444);
MODULE_PARM_DESC(gsp_abi,
"GSP-RM wire protocol ABI for Turing-Blackwell-Rubin (620=620.70.06/620.73.04 MCTP+NVDM default, 580=580.178.04); independent of driver_version");
#ifdef NV_RS_PCI_TEST_EDU
static char *driver_version = "580.178.04";
static bool strict_version_check = true;
module_param(driver_version, charp, 0444);
MODULE_PARM_DESC(driver_version,
"Reported NVIDIA userspace driver version string (NV_RS_PCI_TEST_EDU default \"580.178.04\"; set \"auto\" to derive from gsp_abi and adopt valid client versions when strict_version_check=0)");
module_param(strict_version_check, bool, 0444);
MODULE_PARM_DESC(strict_version_check,
"Enforce strict stock NV_ESC_CHECK_VERSION_STR matching against driver_version (NV_RS_PCI_TEST_EDU default 1=strict stock, 0=permissive auto-negotiation)");
#else
static char *driver_version = "auto";
static bool strict_version_check;
module_param(driver_version, charp, 0444);
MODULE_PARM_DESC(driver_version,
"Reported NVIDIA userspace driver version string (default \"auto\": derives 620.73.04/580.178.04 from gsp_abi, and adopts valid client versions when strict_version_check=0; or set an explicit string)");
module_param(strict_version_check, bool, 0444);
MODULE_PARM_DESC(strict_version_check,
"Enforce strict stock NV_ESC_CHECK_VERSION_STR matching against driver_version (0=permissive auto-negotiation default, 1=strict stock)");
#endif
extern bool nv_rs_sysmem_pool_push(void *page);
extern u32 nv_rs_sysmem_pool_pop_batch(struct page **out, u32 limit);
extern void *nv_rs_sysmem_pool_pop_for_trim(u64 retain_pages);
extern u64 nv_rs_sysmem_pool_len(void);
extern void nv_rs_sysmem_pool_release_storage(void);
/*
* Optional stock major-195 character devices (/dev/nvidiactl = 195:255, /dev/nvidia<N> = 195:N).
* Default off so dual-GPU side-by-side runs with stock nvidia.ko never collide on major 195.
* Enable for standalone desktop boots and Stage 1 (stock nvidia-modeset.ko's
* nvkms_fd_is_nvidia_chardev requires MAJOR(rdev) == 195); minor 254 stays free for modeset.
*/
static bool compat_chardev_major;
module_param(compat_chardev_major, bool, 0444);
MODULE_PARM_DESC(compat_chardev_major,
"Register stock major-195 /dev/nvidiactl (195:255) and /dev/nvidia<N> (195:N) nodes (default 0)");
#define NV_RS_COMPAT_MAJOR 195U
#define NV_RS_COMPAT_CTL_MINOR 255U
static struct class *nv_rs_compat_class;
static struct cdev nv_rs_compat_ctl_cdev;
static struct cdev nv_rs_compat_gpu_cdev;
static bool nv_rs_compat_ctl_registered;
static bool nv_rs_compat_gpu_registered;
#if defined(NV_RS_CLASS_DEVNODE_CONST_DEV) || (!defined(NV_RS_KBUILD_PROBED) && LINUX_VERSION_CODE >= KERNEL_VERSION(6, 2, 0))
static char *nv_rs_compat_devnode(const struct device *dev, umode_t *mode)
#else
static char *nv_rs_compat_devnode(struct device *dev, umode_t *mode)
#endif
{
(void)dev;
if (mode)
*mode = 0666;
return NULL;
}
static DEFINE_MUTEX(nv_rs_sysmem_pool_lock);
#ifdef CONFIG_PROC_FS
#ifndef NV_RS_PCI_TEST_EDU
extern bool nv_rs_ga10x_gsp_enabled(void);
#endif
#ifdef LINUX_COMPILER
#define NV_RS_COMPILER_STRING LINUX_COMPILER
#else
#define NV_RS_COMPILER_STRING "gcc version " __VERSION__
#endif
static struct proc_dir_entry *nv_rs_proc_nvidia;
static struct proc_dir_entry *nv_rs_proc_gpus;
static struct proc_dir_entry *nv_rs_proc_caps;
static struct proc_dir_entry *nv_rs_proc_caps_mig;
static struct proc_dir_entry *nv_rs_proc_nvidia_caps;
/* Minimal "nvidia-caps" character device matching NVIDIA 580.178.04 nv-caps.c.
* NVML reads /proc/driver/nvidia/capabilities/mig/{config,monitor} and looks up
* the "nvidia-caps" major in /proc/devices; exposing the procfs capability files
* without registering this chrdev causes NVML to abort with "GPU access blocked". */
#define NV_RS_CAPS_MINOR_COUNT 8192u
#define NV_RS_CAP_MINOR_NVLINK_FABRIC_MGMT 0u
#define NV_RS_CAP_MINOR_MIG_CONFIG 1u
#define NV_RS_CAP_MINOR_MIG_MONITOR 2u
#define NV_RS_CAP_MIG_MAX_GPUS 32u
#define NV_RS_CAP_MIG_MAX_GIS 15u
#define NV_RS_CAP_MIG_MAX_CIS 8u
#define NV_RS_CAP_MINOR_MIG_GPU_BASE 3u
#define NV_RS_CAP_MINOR_FABRIC_IMEX_MGMT \
(NV_RS_CAP_MINOR_MIG_GPU_BASE + \
NV_RS_CAP_MIG_MAX_GPUS * NV_RS_CAP_MIG_MAX_GIS * (1u + NV_RS_CAP_MIG_MAX_CIS))
static struct cdev nv_rs_caps_cdev;
static dev_t nv_rs_caps_devno;
static bool nv_rs_caps_registered;
static int nv_rs_caps_open(struct inode *inode, struct file *file)
{
(void)inode;
(void)file;
return 0;
}
static int nv_rs_caps_release(struct inode *inode, struct file *file)
{
(void)inode;
(void)file;
return 0;
}
static const struct file_operations nv_rs_caps_fops = {
.owner = THIS_MODULE,
.open = nv_rs_caps_open,
.release = nv_rs_caps_release,
};
static int nv_rs_caps_chrdev_init(void)
{
int rc;
BUILD_BUG_ON(NV_RS_CAP_MINOR_FABRIC_IMEX_MGMT != 4323u);
BUILD_BUG_ON(NV_RS_CAP_MINOR_FABRIC_IMEX_MGMT >= NV_RS_CAPS_MINOR_COUNT);
if (nv_rs_caps_registered)
return 0;
rc = alloc_chrdev_region(&nv_rs_caps_devno, 0, NV_RS_CAPS_MINOR_COUNT, "nvidia-caps");
if (rc < 0)
return rc;
cdev_init(&nv_rs_caps_cdev, &nv_rs_caps_fops);
nv_rs_caps_cdev.owner = THIS_MODULE;
rc = cdev_add(&nv_rs_caps_cdev, nv_rs_caps_devno, NV_RS_CAPS_MINOR_COUNT);
if (rc < 0) {
unregister_chrdev_region(nv_rs_caps_devno, NV_RS_CAPS_MINOR_COUNT);
return rc;
}
nv_rs_caps_registered = true;
return 0;
}
static void nv_rs_caps_chrdev_exit(void)
{
if (!nv_rs_caps_registered)
return;
cdev_del(&nv_rs_caps_cdev);
unregister_chrdev_region(nv_rs_caps_devno, NV_RS_CAPS_MINOR_COUNT);
nv_rs_caps_registered = false;
}
static int nv_rs_proc_params_show(struct seq_file *m, void *v)
{
const char *reg_dwords = NULL;
const char *reg_dwords_per_dev = NULL;
u32 enable_msi = nv_rs_registry_msi_options(&reg_dwords, &reg_dwords_per_dev);
#ifndef NV_RS_PCI_TEST_EDU
u32 enable_gpu_fw = nv_rs_ga10x_gsp_enabled() ? 1u : 0u;
#else
u32 enable_gpu_fw = 1u;
#endif
(void)v;
seq_printf(m,
"ResmanDebugLevel: 4294967295\n"
"RmLogonRC: 1\n"
"ModifyDeviceFiles: 0\n"
"DeviceFileUID: 0\n"
"DeviceFileGID: 0\n"
"DeviceFileMode: 438\n"
"InitializeSystemMemoryAllocations: 1\n"
"UsePageAttributeTable: 4294967295\n"
"EnableMSI: %u\n"
"EnablePCIeGen3: 0\n"
"EnableStreamMemOPs: 0\n"
"EnableUserNUMAManagement: 1\n"
"RmProfilingAdminOnly: %u\n"
"PreserveVideoMemoryAllocations: 0\n"
"EnableS0ixPowerManagement: 0\n"
"S0ixPowerManagementVideoMemoryThreshold: 256\n"
"DynamicPowerManagement: 3\n"
"DynamicPowerManagementVideoMemoryThreshold: 200\n"
"RegisterPCIDriver: 1\n"
"EnableResizableBar: 1\n"
"EnableGpuFirmware: %u\n"
"EnableGpuFirmwareLogs: 2\n"
"OpenRmEnableUnsupportedGpus: 1\n"
"DmaRemapPeerMmio: 1\n"
"CoherentGPUMemoryMode: \"\"\n"
"RegistryDwords: \"%s\"\n"
"RegistryDwordsPerDevice: \"%s\"\n"
"RmMsg: \"\"\n"
"GpuBlacklist: \"\"\n"
"TemporaryFilePath: \"\"\n"
"ExcludedGpus: \"\"\n",
enable_msi,
nv_rs_unpriv_profiling() ? 0u : 1u,
enable_gpu_fw,
reg_dwords ? reg_dwords : "",
reg_dwords_per_dev ? reg_dwords_per_dev : "");
return 0;
}
static int nv_rs_proc_registry_show(struct seq_file *m, void *v)
{
(void)v;
seq_puts(m, "Binary: \"\"\n");
return 0;
}
static int nv_rs_proc_version_show(struct seq_file *m, void *v)
{
char ver[64];
size_t len = 0;
(void)v;
memset(ver, 0, sizeof(ver));
if (nv_rs_rmapi_state) {
mutex_lock(&nv_rs_rmapi_lock);
len = nv_rs_rmapi_get_driver_version(ver, sizeof(ver));
mutex_unlock(&nv_rs_rmapi_lock);
}
if (len == 0 || ver[0] == '\0')
strscpy(ver, (gsp_abi == 580) ? "580.178.04" : "620.73.04", sizeof(ver));
seq_printf(m, "NVRM version: NVIDIA UNIX Open Kernel Module for x86_64 %s Release Build (nvdriver clean-room Rust)\n", ver);
seq_printf(m, "GCC version: %s\n", NV_RS_COMPILER_STRING);
return 0;
}
/* Stock 580.178.04 also reports the mode nvidia-modprobe must give the node: mig/monitor is
* 292 (0444), every other capability 256 (0400). Without the line the helper falls back to its
* 438 (0666) default. DeviceFileModify stays 0: nvdriver never creates or chmods a device file,
* udev and tools/bind_dev_nodes.sh own the nodes (matching /proc/driver/nvidia/params). */
#define NV_RS_CAP_MODE_DEFAULT 256u
#define NV_RS_CAP_MODE_MONITOR 292u
static int nv_rs_proc_cap_show(struct seq_file *m, void *v)
{
unsigned int minor = (unsigned int)(uintptr_t)m->private;
unsigned int mode = minor == NV_RS_CAP_MINOR_MIG_MONITOR ? NV_RS_CAP_MODE_MONITOR
: NV_RS_CAP_MODE_DEFAULT;
(void)v;
seq_printf(m, "DeviceFileMinor: %u\nDeviceFileMode: %u\nDeviceFileModify: 0\n", minor, mode);
return 0;
}
static int nv_rs_proc_caps_mig_minors_show(struct seq_file *m, void *v)
{
unsigned int gpu, gi, ci;
unsigned int minor = NV_RS_CAP_MINOR_MIG_GPU_BASE;
(void)v;
seq_printf(m, "config %u\nmonitor %u\n",
NV_RS_CAP_MINOR_MIG_CONFIG, NV_RS_CAP_MINOR_MIG_MONITOR);
for (gpu = 0; gpu < NV_RS_CAP_MIG_MAX_GPUS; gpu++) {
for (gi = 0; gi < NV_RS_CAP_MIG_MAX_GIS; gi++) {
seq_printf(m, "gpu%u/gi%u/access %u\n", gpu, gi, minor++);
for (ci = 0; ci < NV_RS_CAP_MIG_MAX_CIS; ci++)
seq_printf(m, "gpu%u/gi%u/ci%u/access %u\n", gpu, gi, ci, minor++);
}
}
return 0;
}
static int nv_rs_proc_caps_nvlink_minors_show(struct seq_file *m, void *v)
{
(void)v;
seq_printf(m, "fabric-mgmt %u\n", NV_RS_CAP_MINOR_NVLINK_FABRIC_MGMT);
return 0;
}
static int nv_rs_proc_caps_sys_minors_show(struct seq_file *m, void *v)
{
(void)v;
seq_printf(m, "fabric-imex-mgmt %u\n", NV_RS_CAP_MINOR_FABRIC_IMEX_MGMT);
return 0;
}
static const char *nv_rs_tensor_fp32_rate_str(int rate)
{
switch (rate) {
case 1:
return "half";
case 2:
return "full";
default:
return "unknown";
}
}
static int nv_rs_proc_gpu_info_show(struct seq_file *m, void *v)
{
struct nv_rs_rmapi_gpu_node *node = m->private;
unsigned long flags;
u16 vid = 0, did = 0, svid = 0, sdid = 0;
u32 irq = 0, gpu_id = 0, boot0 = 0;
u64 dma_mask = 0;
int minor = -1;
int rate = node ? atomic_read(&node->tensor_fp32_rate) : 0;
bool is_pcie = true;
bool is_platform = false;
bool have_pdev = false;
bool have_uuid = false;
u8 uuid[16] = { 0 };
(void)v;
if (node) {
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
if (node->live && node->pdev) {
vid = node->pdev->vendor;
did = node->pdev->device;
svid = node->pdev->subsystem_vendor;
sdid = node->pdev->subsystem_device;
irq = node->pdev->irq;
dma_mask = node->pdev->dma_mask;
is_pcie = pci_is_pcie(node->pdev);
have_pdev = true;
} else if (node->live && node->is_platform) {
u8 dma_bits = (node->dma_bits > 0 && node->dma_bits <= 64) ? node->dma_bits : 47;
did = node->device_id;
irq = node->irq;
dma_mask = (dma_bits == 64) ? ~0ULL : ((1ULL << dma_bits) - 1ULL);
is_pcie = false;
is_platform = true;
}
gpu_id = node->gpu_id;
boot0 = node->boot0;
minor = node->minor_index;
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
}
if (have_pdev && nv_rs_rmapi_state) {
mutex_lock(&nv_rs_rmapi_lock);
if (nv_rs_rmapi_state &&
nv_rs_rmapi_gpu_uuid(nv_rs_rmapi_state, gpu_id, uuid) == 1)
have_uuid = true;
mutex_unlock(&nv_rs_rmapi_lock);
}
seq_printf(m, "Model: \t\t NVIDIA GPU (0x%04x)\n", did);
seq_printf(m, "IRQ: \t\t %u\n", irq);
if (have_pdev) {
if (!have_uuid) {
u32 pci_dev_id = ((u32)did << 16) | (u32)vid;
u32 pci_sub_id = ((u32)sdid << 16) | (u32)svid;
u32 w0 = pci_dev_id ^ 0x56313030u;
u32 w1 = pci_sub_id ^ boot0;
u32 w2 = gpu_id ^ 0x4e565253u;
u32 w3 = ((boot0 << 13) | (boot0 >> 19)) ^ ((gpu_id >> 5) | (gpu_id << 27));
uuid[0] = (u8)w0;
uuid[1] = (u8)(w0 >> 8);
uuid[2] = (u8)(w0 >> 16);
uuid[3] = (u8)(w0 >> 24);
uuid[4] = (u8)w1;
uuid[5] = (u8)(w1 >> 8);
uuid[6] = (u8)(w1 >> 16);
uuid[7] = (u8)(w1 >> 24);
uuid[8] = (u8)w2;
uuid[9] = (u8)(w2 >> 8);
uuid[10] = (u8)(w2 >> 16);
uuid[11] = (u8)(w2 >> 24);
uuid[12] = (u8)w3;
uuid[13] = (u8)(w3 >> 8);
uuid[14] = (u8)(w3 >> 16);
uuid[15] = (u8)(w3 >> 24);
}
seq_printf(m, "GPU UUID: \t GPU-%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
uuid[0], uuid[1], uuid[2], uuid[3],
uuid[4], uuid[5], uuid[6], uuid[7],
uuid[8], uuid[9], uuid[10], uuid[11],
uuid[12], uuid[13], uuid[14], uuid[15]);
} else {
seq_puts(m, "GPU UUID: \t GPU-????????-????-????-????-????????????\n");
}
seq_puts(m, "Video BIOS: \t ??.??.??.??.??\n");
seq_printf(m, "Bus Type: \t %s\n", is_platform ? "Platform" : (is_pcie ? "PCIe" : "PCI"));
seq_printf(m, "DMA Size: \t %u bits\n", (unsigned int)hweight64(dma_mask));
seq_printf(m, "DMA Mask: \t 0x%llx\n", (unsigned long long)dma_mask);
seq_printf(m, "Bus Location: \t %s\n", node ? node->bdf : "unknown");
seq_printf(m, "Device Minor: \t %d\n", minor);
seq_puts(m, "GPU Excluded:\t No\n");
seq_printf(m, "Live PCI IRQ: \t %s\n", nv_rs_live_pci_irq() ? "Enabled" : "Disabled");
seq_printf(m, "Tensor FP32-Acc Rate: \t %s\n", nv_rs_tensor_fp32_rate_str(rate));
return 0;
}
static const char *nv_rs_idle_pstate_mode_str(int mode)
{
if (!nv_rs_idle_pstate())
return "disabled";
return mode == 1 ? "low-power" : "active";
}
static int nv_rs_proc_gpu_power_show(struct seq_file *m, void *v)
{
struct nv_rs_rmapi_gpu_node *node = m->private;
int mode = node ? atomic_read(&node->idle_pstate_mode) : 0;
s64 transitions = node ? atomic64_read(&node->idle_pstate_transitions) : 0;
s64 idle_secs = node ? atomic64_read(&node->idle_pstate_total_secs) : 0;
s64 cap_mw = node ? atomic64_read(&node->power_cap_mw) : 0;
(void)v;
seq_puts(m, "Runtime D3 status: Not supported\n");
seq_puts(m, "Video Memory: Active\n");
seq_printf(m, "Idle P-State Governor: %s\n", nv_rs_idle_pstate_mode_str(mode));
seq_printf(m, "Idle P-State Transitions: %lld\n", (long long)transitions);
seq_printf(m, "Idle P-State Total Seconds: %lld\n", (long long)idle_secs);
if (cap_mw > 0)
seq_printf(m, "Power Limit Override: %llu.%03llu W (%lld mW)\n\n",
(unsigned long long)cap_mw / 1000ULL,
(unsigned long long)cap_mw % 1000ULL, (long long)cap_mw);
else
seq_puts(m, "Power Limit Override: Default\n\n");
seq_puts(m, "GPU Hardware Support:\n");
seq_puts(m, " Video Memory Self Refresh: Supported\n");
seq_puts(m, " Video Memory Off: Supported\n");
return 0;
}
static int nv_rs_proc_gpu_registry_show(struct seq_file *m, void *v)
{
(void)v;
seq_printf(m, "RuntimeEngines=%u\nLivePciIrq=%u\nDynBar1P2P=%u\nUnlockAdaTensor=%u\nDisableEcc=%u\nUnprivProfiling=%u\nIdlePstate=%u\nIdlePstateDelayS=%u\nIdlePstateGpcKhz=%u\n",
nv_rs_runtime_engines() ? 1u : 0u,
nv_rs_live_pci_irq() ? 1u : 0u,
nv_rs_dyn_bar1_p2p() ? 1u : 0u,
nv_rs_unlock_ada_tensor() ? 1u : 0u,
nv_rs_disable_ecc() ? 1u : 0u,
nv_rs_unpriv_profiling() ? 1u : 0u,
nv_rs_idle_pstate() ? 1u : 0u,
nv_rs_idle_pstate_delay_s(),
nv_rs_idle_pstate_gpc_khz());
return 0;
}
static const char *nv_rs_gpu_prio_class_name(u8 cls)
{
switch (cls) {
case 0: return "rt";
case 1: return "desktop";
case 2: return "normal";
case 3: return "bg";
case 4: return "idle";
default: return "unknown";
}
}
static const char *nv_rs_gpu_prio_interleave_name(u8 lvl, u8 fallback)
{
if (fallback) {
switch (lvl) {
case 0: return "LOW/unif";
case 1: return "MED/unif";
case 2: return "HIGH/unif";
default: return "?/unif";
}
}
switch (lvl) {
case 0: return "LOW";
case 1: return "MED";
case 2: return "HIGH";
default: return "?";
}
}
static const char *nv_rs_gpu_prio_preempt_name(u8 gfx, u8 compute)
{
if (gfx == 0 && compute == 0)
return "WFI";
if (gfx != 0 && compute == 2)
return "GFXP/CILP";
if (gfx != 0 && compute == 1)
return "GFXP/CTA";
if (gfx != 0)
return "GFXP/WFI";
if (compute == 2)
return "WFI/CILP";
return "WFI/CTA";
}
static void nv_rs_escape_comm(const u8 *src, size_t src_len, char *dst, size_t dst_cap)
{
static const char hex[] = "0123456789abcdef";
size_t i = 0, pos = 0;
if (!dst || !dst_cap)
return;
while (i < src_len && src[i] != '\0') {
u8 c = src[i++];
if (c == '\\') {
if (pos + 2 >= dst_cap)
break;
dst[pos++] = '\\';
dst[pos++] = '\\';
} else if (c <= 0x20 || c >= 0x7f) {
if (pos + 4 >= dst_cap)
break;
dst[pos++] = '\\';
dst[pos++] = 'x';
dst[pos++] = hex[(c >> 4) & 0xf];
dst[pos++] = hex[c & 0xf];
} else {
if (pos + 1 >= dst_cap)
break;
dst[pos++] = (char)c;
}
}
dst[pos] = '\0';
}
static int nv_rs_proc_gpu_prio_show(struct seq_file *m, void *v)
{
u32 auto_on = 1, desktop_on = 1, preempt_on = 1, pids = 0, tsgs = 0;
char custom_comms[280];
struct nv_rs_gpu_nice_row row;
u32 idx = 0;
bool in_init_ns;
(void)v;
if (!nv_rs_rmapi_state) {
seq_puts(m, "# unavailable\n");
return 0;
}
BUILD_BUG_ON(sizeof(struct nv_rs_gpu_nice_row) != 64);
memset(custom_comms, 0, sizeof(custom_comms));
in_init_ns = (task_active_pid_ns(current) == &init_pid_ns);
mutex_lock(&nv_rs_rmapi_lock);
nv_rs_gpu_nice_refresh_fallbacks(nv_rs_rmapi_state);
nv_rs_gpu_nice_get_policy(nv_rs_rmapi_state, &auto_on, &desktop_on, &preempt_on, &pids, &tsgs);
(void)nv_rs_gpu_nice_copy_custom_comms(nv_rs_rmapi_state, (u8 *)custom_comms, sizeof(custom_comms));
seq_printf(m, "# policy: auto=%u desktop_boost=%u preempt=%u tracked_pids=%u active_tsgs=%u\n",
auto_on, desktop_on, preempt_on, pids, tsgs);
seq_printf(m, "# desktop_comms: builtin=kwin_wayland,kwin_x11,gnome-shell,mutter,Hyprland,sway,Xorg,Xwayland,gamescope,weston,niri,river,labwc,wayfire,picom,compiz,cage,cosmic-comp%s%s\n",
custom_comms[0] ? " custom=" : "",
custom_comms[0] ? custom_comms : "");
seq_puts(m, "PID UID COMM LINUX_NICE GPU_NICE OVERRIDE CLASS INTERLEAVE TIMESLICE_US TSGS_GR TSGS_CE TSGS_OTH PREEMPT DESKTOP\n");
while (nv_rs_gpu_nice_get_row(nv_rs_rmapi_state, idx, &row) == 1) {
char comm_esc[64];
char pid_col[16];
u32 disp_pid = row.pid;
bool has_live = false;
if (!in_init_ns || row.start_time != 0 || row.ambiguous_pid) {
struct pid *p;
struct task_struct *leader = NULL;
pid_t vnr = 0;
bool reused = false;
rcu_read_lock();
p = find_pid_ns((pid_t)row.pid, &init_pid_ns);
if (p) {
leader = pid_task(p, PIDTYPE_TGID);
if (leader) {
if (row.start_time != 0 && leader->start_boottime != row.start_time) {
reused = true;
} else {
has_live = nv_rs_live_tg_thread(leader) != NULL;
if (!in_init_ns)
vnr = pid_vnr(p);
}
} else {
struct task_struct *tid_task = pid_task(p, PIDTYPE_PID);
if (tid_task && !READ_ONCE(tid_task->exit_state))
reused = true;
}
}
rcu_read_unlock();
if (reused || (!in_init_ns && vnr <= 0)) {
idx++;
continue;
}
if (!in_init_ns)
disp_pid = (u32)vnr;
}
if (row.ambiguous_pid && !has_live)
snprintf(pid_col, sizeof(pid_col), "retired");
else
snprintf(pid_col, sizeof(pid_col), "%u", disp_pid);
nv_rs_escape_comm((const u8 *)row.comm, sizeof(row.comm), comm_esc, sizeof(comm_esc));
seq_printf(m, "%-7s %-7u %-16s %-10d %-8d %-8s %-8s %-10s %-12llu %-7u %-7u %-7u %-10s %s\n",
pid_col,
row.uid,
comm_esc[0] ? comm_esc : "?",
row.linux_nice,
row.gpu_nice,
row.has_override ? "override" : "auto",
nv_rs_gpu_prio_class_name(row.class_id),
nv_rs_gpu_prio_interleave_name(row.interleave, row.interleave_fallback),
(unsigned long long)row.timeslice_us,
row.gr_tsgs,
row.ce_tsgs,
row.other_tsgs,
nv_rs_gpu_prio_preempt_name(row.gfx_preempt, row.compute_preempt),
row.is_desktop ? "yes" : "no");
idx++;
}
mutex_unlock(&nv_rs_rmapi_lock);
return 0;
}
static int nv_rs_proc_gpu_prio_open(struct inode *inode, struct file *file)
{
(void)inode;
return single_open(file, nv_rs_proc_gpu_prio_show, NULL);
}
static ssize_t nv_rs_proc_gpu_prio_write(struct file *file, const char __user *ubuf,
size_t count, loff_t *ppos)
{
char buf[256];
char *p, *cmd, *arg1, *arg2;
size_t len;
int rc = 0;
bool has_active = false;
(void)file;
(void)ppos;
if (!nv_rs_rmapi_state)
return -ENODEV;
if (count == 0)
return 0;
if (count >= sizeof(buf))
return -EINVAL;
if (copy_from_user(buf, ubuf, count))
return -EFAULT;
if (memchr(buf, '\0', count) != NULL)
return -EINVAL;
buf[count] = '\0';
len = count;
while (len > 0 && isspace((unsigned char)buf[len - 1]))
buf[--len] = '\0';
p = skip_spaces(buf);
if (*p == '\0' || *p == '#')
return (ssize_t)count;
cmd = strsep(&p, " \t");
if (!cmd)
return -EINVAL;
if (strcmp(cmd, "pid") == 0) {
u32 vpid = 0;
u32 init_pid = 0;
u64 live_start_time = 0;
bool clear_ov = false;
int admin_desktop = -1;
s32 val = 0;
s32 live_nice = 0;
u32 live_uid = 0;
u32 live_euid = 0;
bool live_cap = false;
u8 live_comm[16] = { 0 };
int live_rc = -ESRCH;
bool in_init_ns;
struct pid *p_vpid;
struct task_struct *task;
u32 tracked_uid = 0;
s32 cur_eff = 0, cur_lnice = 0;
u8 has_ov = 0;
int tracked;
u32 target_uid, caller_uid;
bool has_cap;
arg1 = p ? strsep(&p, " \t") : NULL;
arg2 = p ? strsep(&p, " \t") : NULL;
if (!arg1 || !arg2 || *arg1 == '\0' || *arg2 == '\0' ||
(p && *skip_spaces(p) != '\0'))
return -EINVAL;
if (kstrtou32(arg1, 10, &vpid) || vpid == 0)
return -EINVAL;
if (strcmp(arg2, "auto") == 0) {
clear_ov = true;
admin_desktop = 0;
} else if (strcmp(arg2, "desktop") == 0) {
clear_ov = true;
admin_desktop = 1;
} else {
if (kstrtos32(arg2, 10, &val) || val < -20 || val > 19)
return -EINVAL;
}
rcu_read_lock();
in_init_ns = (task_active_pid_ns(current) == &init_pid_ns);
p_vpid = find_vpid((pid_t)vpid);
task = p_vpid ? pid_task(p_vpid, PIDTYPE_TGID) : NULL;
if (task) {
if (nv_rs_sample_tg_meta_rcu(task, &live_start_time, &live_nice, &live_uid,
&live_euid, live_comm, sizeof(live_comm), &live_cap)) {
init_pid = (u32)task_tgid_nr(task);
live_rc = 0;
}
} else if (p_vpid) {
task = pid_task(p_vpid, PIDTYPE_PID);
if (task && !READ_ONCE(task->exit_state)) {
struct task_struct *leader = READ_ONCE(task->group_leader);
const struct cred *cred = __task_cred(task);
size_t n;
if (!leader || !pid_alive(leader))
leader = task;
init_pid = (u32)task_tgid_nr(leader);
live_start_time = leader->start_boottime;
live_nice = task_nice(task);
live_uid = cred ? from_kuid_munged(&init_user_ns, cred->uid) : (u32)-1;
live_euid = cred ? from_kuid_munged(&init_user_ns, cred->euid) : (u32)-1;
live_cap = cred && cred->user_ns == &init_user_ns &&
(cap_raised(cred->cap_effective, CAP_SYS_NICE) ||
cap_raised(cred->cap_effective, CAP_SYS_ADMIN));
n = min_t(size_t, sizeof(live_comm) - 1, TASK_COMM_LEN - 1);
task_lock(task);
memcpy(live_comm, task->comm, n);
task_unlock(task);
live_comm[n] = '\0';
live_rc = 0;
}
}
rcu_read_unlock();
if (live_rc != 0) {
if (!in_init_ns)
return -ESRCH;
init_pid = vpid;
}
caller_uid = from_kuid_munged(&init_user_ns, current_euid());
has_cap = capable(CAP_SYS_NICE) || capable(CAP_SYS_ADMIN);
if (admin_desktop == 1 && !has_cap)
return -EPERM;
if (mutex_lock_interruptible(&nv_rs_rmapi_lock))
return -ERESTARTSYS;
{
u64 re_start_time = 0;
s32 re_nice = 0;
u32 re_uid = 0;
u32 re_euid = 0;
bool re_cap = false;
u8 re_comm[16] = { 0 };
int re_rc = nv_rs_pid_info(init_pid, &re_start_time, &re_nice, &re_uid, &re_euid,
re_comm, sizeof(re_comm), &re_cap);
if (live_rc == 0) {
if (re_rc != 0 || re_start_time != live_start_time) {
mutex_unlock(&nv_rs_rmapi_lock);
return -ESRCH;
}
if (re_uid != live_uid || re_euid != live_euid) {
mutex_unlock(&nv_rs_rmapi_lock);
return -EPERM;
}
live_nice = re_nice;
live_cap = re_cap;
memcpy(live_comm, re_comm, sizeof(live_comm));
} else if (re_rc == 0) {
/* PID was recycled while waiting for the lock; reject stale override. */
mutex_unlock(&nv_rs_rmapi_lock);
return -ESRCH;
}
}
nv_rs_gpu_nice_apply_params_locked(false);
tracked = nv_rs_gpu_nice_query_pid(nv_rs_rmapi_state, init_pid, live_start_time,
&tracked_uid, &cur_eff, &cur_lnice, &has_ov);
if (live_rc != 0 && !tracked) {
mutex_unlock(&nv_rs_rmapi_lock);
return -ESRCH;
}
target_uid = (live_rc == 0) ? live_uid : tracked_uid;
{
const u8 *comm_ptr = (live_rc == 0) ? live_comm : NULL;
size_t comm_n = (live_rc == 0) ? strnlen((const char *)live_comm, sizeof(live_comm)) : 0;
int cap_arg = (live_rc == 0) ? (live_cap ? 1 : 0) : -1;
if (!has_cap) {
s32 cur_eff_pol = nv_rs_gpu_nice_preview_nice(nv_rs_rmapi_state, init_pid,
live_start_time,
(live_rc == 0) ? live_nice : cur_lnice,
comm_ptr, comm_n, live_cap, false);
if (caller_uid != target_uid && (live_rc != 0 || caller_uid != live_euid)) {
mutex_unlock(&nv_rs_rmapi_lock);
return -EPERM;
}
if (!clear_ov) {
if (val < cur_eff_pol) {
mutex_unlock(&nv_rs_rmapi_lock);
return -EACCES;
}
} else if (tracked) {
s32 after_eff = nv_rs_gpu_nice_preview_nice(nv_rs_rmapi_state, init_pid,
live_start_time,
(live_rc == 0) ? live_nice : cur_lnice,
comm_ptr, comm_n, live_cap, true);
if (after_eff < cur_eff_pol) {
mutex_unlock(&nv_rs_rmapi_lock);
return -EACCES;
}
}
}
rc = nv_rs_gpu_nice_set_pid(nv_rs_rmapi_state, init_pid, live_start_time, target_uid,
comm_ptr, comm_n, cap_arg,
(live_rc == 0) ? live_nice : cur_lnice,
val, clear_ov, admin_desktop);
if (rc == -ENOMEM) {
nv_rs_gpu_nice_reap_dead_locked();
rc = nv_rs_gpu_nice_set_pid(nv_rs_rmapi_state, init_pid, live_start_time, target_uid,
comm_ptr, comm_n, cap_arg,
(live_rc == 0) ? live_nice : cur_lnice,
val, clear_ov, admin_desktop);
}
}
has_active = nv_rs_gpu_nice_has_tracked(nv_rs_rmapi_state);
mutex_unlock(&nv_rs_rmapi_lock);
nv_rs_gpu_nice_schedule_if_active(has_active);
return rc ? rc : (ssize_t)count;
}
if (!capable(CAP_SYS_NICE) && !capable(CAP_SYS_ADMIN))
return -EPERM;
if (strcmp(cmd, "auto") == 0 || strcmp(cmd, "desktop_boost") == 0 ||
strcmp(cmd, "preempt") == 0) {
u32 v = 0;
arg1 = p ? strsep(&p, " \t") : NULL;
if (!arg1 || *arg1 == '\0' || (p && *skip_spaces(p) != '\0') ||
kstrtou32(arg1, 10, &v) || v > 1)
return -EINVAL;
if (mutex_lock_interruptible(&nv_rs_rmapi_lock))
return -ERESTARTSYS;
if (strcmp(cmd, "auto") == 0) {
WRITE_ONCE(gpu_nice_auto, (int)v);
rc = nv_rs_gpu_nice_set_policy(nv_rs_rmapi_state, (int)v, -1, -1, true);
} else if (strcmp(cmd, "desktop_boost") == 0) {
WRITE_ONCE(gpu_desktop_boost, (int)v);
rc = nv_rs_gpu_nice_set_policy(nv_rs_rmapi_state, -1, (int)v, -1, true);
} else {
rc = nv_rs_gpu_nice_set_policy(nv_rs_rmapi_state, -1, -1, (int)v, true);
}
has_active = nv_rs_gpu_nice_has_tracked(nv_rs_rmapi_state);
mutex_unlock(&nv_rs_rmapi_lock);
nv_rs_gpu_nice_schedule_if_active(has_active);
return rc ? rc : (ssize_t)count;
}
if (strcmp(cmd, "desktop_comm") == 0) {
bool add;
arg1 = p ? strsep(&p, " \t") : NULL;
arg2 = p ? strsep(&p, " \t") : NULL;
if (!arg1 || !arg2 || *arg2 == '\0' || (p && *skip_spaces(p) != '\0'))
return -EINVAL;
if (strcmp(arg1, "add") == 0)
add = true;
else if (strcmp(arg1, "del") == 0)
add = false;
else
return -EINVAL;
if (mutex_lock_interruptible(&nv_rs_rmapi_lock))
return -ERESTARTSYS;
rc = nv_rs_gpu_nice_desktop_comm(nv_rs_rmapi_state, add,
(const u8 *)arg2, strlen(arg2));
has_active = nv_rs_gpu_nice_has_tracked(nv_rs_rmapi_state);
mutex_unlock(&nv_rs_rmapi_lock);
nv_rs_gpu_nice_schedule_if_active(has_active);
return rc ? rc : (ssize_t)count;
}
if (strcmp(cmd, "sync") == 0) {
if (p && *skip_spaces(p) != '\0')
return -EINVAL;
if (mutex_lock_interruptible(&nv_rs_rmapi_lock))
return -ERESTARTSYS;
nv_rs_gpu_nice_sync_all_locked(false);
has_active = nv_rs_gpu_nice_has_tracked(nv_rs_rmapi_state);
mutex_unlock(&nv_rs_rmapi_lock);
nv_rs_gpu_nice_schedule_if_active(has_active);
return (ssize_t)count;
}
return -EINVAL;
}
static const struct proc_ops nv_rs_proc_gpu_prio_ops = {
.proc_open = nv_rs_proc_gpu_prio_open,
.proc_read = seq_read,
.proc_write = nv_rs_proc_gpu_prio_write,
.proc_lseek = seq_lseek,
.proc_release = single_release,
};
static void nv_rs_proc_init(void)
{
struct path existing;
if (!nv_rs_runtime_engines())
return;
if (kern_path("/proc/driver/nvidia", LOOKUP_FOLLOW, &existing) == 0) {
path_put(&existing);
pr_info("nvidia_rs: /proc/driver/nvidia already exists; skipping procfs tree\n");
return;
}
nv_rs_proc_nvidia = proc_mkdir("driver/nvidia", NULL);
if (!nv_rs_proc_nvidia)
return;
proc_create_single("params", 0444, nv_rs_proc_nvidia, nv_rs_proc_params_show);
proc_create_single("registry", 0444, nv_rs_proc_nvidia, nv_rs_proc_registry_show);
proc_create_single("version", 0444, nv_rs_proc_nvidia, nv_rs_proc_version_show);
proc_create("gpu-prio", 0666, nv_rs_proc_nvidia, &nv_rs_proc_gpu_prio_ops);
nv_rs_proc_gpus = proc_mkdir("gpus", nv_rs_proc_nvidia);
if (kern_path("/proc/driver/nvidia-caps", LOOKUP_FOLLOW, &existing) == 0) {
path_put(&existing);
pr_info("nvidia_rs: /proc/driver/nvidia-caps already exists; skipping nvidia-caps chrdev\n");
} else if (nv_rs_caps_chrdev_init() == 0) {
nv_rs_proc_caps = proc_mkdir("capabilities", nv_rs_proc_nvidia);
if (nv_rs_proc_caps) {
proc_create_single_data("fabric-imex-mgmt", 0444, nv_rs_proc_caps,
nv_rs_proc_cap_show,
(void *)(uintptr_t)NV_RS_CAP_MINOR_FABRIC_IMEX_MGMT);
nv_rs_proc_caps_mig = proc_mkdir("mig", nv_rs_proc_caps);
if (nv_rs_proc_caps_mig) {
proc_create_single_data("config", 0444, nv_rs_proc_caps_mig,
nv_rs_proc_cap_show,
(void *)(uintptr_t)NV_RS_CAP_MINOR_MIG_CONFIG);
proc_create_single_data("monitor", 0444, nv_rs_proc_caps_mig,
nv_rs_proc_cap_show,
(void *)(uintptr_t)NV_RS_CAP_MINOR_MIG_MONITOR);
}
}
nv_rs_proc_nvidia_caps = proc_mkdir("driver/nvidia-caps", NULL);
if (nv_rs_proc_nvidia_caps) {
proc_create_single("mig-minors", 0444, nv_rs_proc_nvidia_caps,
nv_rs_proc_caps_mig_minors_show);
proc_create_single("nvlink-minors", 0444, nv_rs_proc_nvidia_caps,
nv_rs_proc_caps_nvlink_minors_show);
proc_create_single("sys-minors", 0444, nv_rs_proc_nvidia_caps,
nv_rs_proc_caps_sys_minors_show);
}
} else {
pr_warn("nvidia_rs: failed to register nvidia-caps chrdev; skipping capabilities procfs\n");
}
}
static void nv_rs_proc_exit(void)
{
if (nv_rs_proc_nvidia_caps) {
proc_remove(nv_rs_proc_nvidia_caps);
nv_rs_proc_nvidia_caps = NULL;
}
if (nv_rs_proc_nvidia) {
proc_remove(nv_rs_proc_nvidia);
nv_rs_proc_nvidia = NULL;
nv_rs_proc_gpus = NULL;
nv_rs_proc_caps = NULL;
nv_rs_proc_caps_mig = NULL;
}
nv_rs_caps_chrdev_exit();
}
#else
static inline void nv_rs_proc_init(void) {}
static inline void nv_rs_proc_exit(void) {}
#endif
static u32 nv_rs_sysmem_pool_pop_pages(struct page **pages, u32 limit)
{
u32 count, i;
mutex_lock(&nv_rs_sysmem_pool_lock);
count = nv_rs_sysmem_pool_pop_batch(pages, limit);
mutex_unlock(&nv_rs_sysmem_pool_lock);
for (i = 0; i < count; i++)
clear_highpage(pages[i]);
return count;
}
static void nv_rs_sysmem_pool_push_page(struct page *page)
{
bool pooled;
mutex_lock(&nv_rs_sysmem_pool_lock);
pooled = nv_rs_sysmem_pool_push(page);
mutex_unlock(&nv_rs_sysmem_pool_lock);
if (!pooled)
__free_page(page);
}
/*
* Trim pooled system memory pages down to at most retain_pages order-0 pages.
* Runs outside nv_rs_rmapi_lock in a sleepable context; pool ordering lives in
* Rust (`SysmemPagePool` in `src/nvidia/src/rmapi/alloc_registry.rs`).
*/
static void nv_rs_rmapi_trim_page_pools(unsigned long retain_pages)
{
for (;;) {
struct page *page;
mutex_lock(&nv_rs_sysmem_pool_lock);
page = (struct page *)nv_rs_sysmem_pool_pop_for_trim((u64)retain_pages);
mutex_unlock(&nv_rs_sysmem_pool_lock);
if (!page)
break;
__free_page(page);
}
}
/*
* Called on both control-fd and per-GPU device-fd close after nv_rs_rmapi_lock
* is dropped, returning pooled system pages to the OS per
* system_memory_pool_retain_mb.
*/
static void nv_rs_rmapi_trim_page_pools_on_client_close(void)
{
int retain_mb = READ_ONCE(system_memory_pool_retain_mb);
u64 retain_pages;
if (retain_mb < 0)
return;
retain_pages = ((u64)(unsigned int)retain_mb << 20) >> PAGE_SHIFT;
nv_rs_rmapi_trim_page_pools((unsigned long)retain_pages);
}
/* The page-attribute changes of the original's nv_set_pages_array_type (580.178.04 nv-vm.c:106-128), which it has
* on x86 only (conftest-guarded set_pages_array_*). nv_rs_sysmem_make_uncached and nv_rs_sysmem_may_release
* (src/nvidia/kernel/rmapi_memory.rs) call them and decide what a failure means. set_pages_array_* take an int count:
* a larger allocation is never changed, so it has nothing to restore. */
int nv_rs_sysmem_make_uncached(struct page **pages, u64 count);
bool nv_rs_sysmem_may_release(struct page **pages, u64 count, bool kernel_uc);
bool nv_rs_rmapi_os_pages_uc(struct page **pages, u64 count);
bool nv_rs_rmapi_os_pages_wb(struct page **pages, u64 count);
bool nv_rs_rmapi_os_pages_uc(struct page **pages, u64 count)
{
#ifdef CONFIG_X86
return count <= INT_MAX && set_pages_array_uc(pages, (int)count) == 0;
#else
return false;
#endif
}
bool nv_rs_rmapi_os_pages_wb(struct page **pages, u64 count)
{
#ifdef CONFIG_X86
return count > INT_MAX || set_pages_array_wb(pages, (int)count) == 0;
#else
return true;
#endif
}
void *nv_rs_rmapi_kvzalloc(size_t size);
void nv_rs_rmapi_kvfree(void *ptr);
void *nv_rs_rmapi_kvzalloc(size_t size)
{
void *ptr = kvzalloc(size, GFP_KERNEL);
if (ptr)
atomic64_inc(&nv_rs_rmapi_kvalloc_live);
return ptr;
}
void nv_rs_rmapi_kvfree(void *ptr)
{
if (!ptr)
return;
atomic64_dec(&nv_rs_rmapi_kvalloc_live);
kvfree(ptr);
}
u32 nv_rs_rmapi_os_alloc_pages(u64 count, u64 page, bool contiguous, u32 cache, u64 *token);
void nv_rs_rmapi_os_free_pages(u64 token);
u32 nv_rs_rmapi_os_lock_user_pages(u64 address, u64 count, bool writable, u64 *token);
void nv_rs_rmapi_os_unlock_user_pages(u64 token);
u32 nv_rs_rmapi_os_kernel_map(u64 token, u64 size);
void nv_rs_rmapi_os_kernel_unmap(u64 token);
u32 nv_rs_rmapi_os_user_map(u64 token, u64 page_index, u32 page_offset, u64 *address);
u32 nv_rs_rmapi_os_match_offset(u64 token, u64 address, u64 *page_index);
u32 nv_rs_rmapi_os_map_pascal_userd(u32 gpu_id, u64 offset, u64 length, s32 descriptor,
u64 owner, u32 block, u64 *address, u64 *cookie);
void nv_rs_rmapi_os_unmap_pascal_userd(u64 cookie);
bool nv_rs_rmapi_userd_block_available(u32 gpu_id, u32 block, u64 owner);
u32 nv_rs_rmapi_os_add_context(s32 descriptor, u32 protection, u64 token, u64 page_index,
u32 caching);
u32 nv_rs_rmapi_os_map_register(u32 gpu_id, u64 offset, u64 length, bool write_only,
s32 descriptor, u64 *address);
u32 nv_rs_rmapi_os_map_doorbell(u32 gpu_id, u64 offset, u64 length, s32 descriptor, u64 *address);
u32 nv_rs_rmapi_os_map_video(u32 gpu_id, u64 offset, u64 length, s32 descriptor,
u64 *address);
u32 nv_rs_rmapi_os_map_video_scatter(u32 gpu_id, u64 bar1_base,
const struct nv_rs_extent *extents, size_t count,
s32 descriptor, u64 *address);
u32 nv_rs_rmapi_os_kernel_map_va(u64 token, u64 offset, u64 length, u64 *address);
u32 nv_rs_rmapi_os_kernel_map_register(u32 gpu_id, u64 offset, u64 length, u64 *address);
u32 nv_rs_rmapi_os_kernel_map_video(u32 gpu_id, u64 offset, u64 length, u64 *address);
u32 nv_rs_rmapi_os_kernel_video_phys(u32 gpu_id, u64 offset, u64 length, u64 *phys_out);
u32 nv_rs_rmapi_os_kernel_read_u64(u64 token, u64 offset, u64 *val_out);
void nv_rs_rmapi_os_kernel_unmap_io(u64 address);
u32 nv_rs_rmapi_os_kernel_write(u64 token, u64 offset, const u8 *bytes, size_t length);
u32 nv_rs_rmapi_os_page_phys(u64 token, u64 page_index, u64 *phys);
u32 nv_rs_rmapi_os_page_dma(u32 gpu_id, u64 token, u64 page_index, u64 *dma_out);
u32 nv_rs_rmapi_os_page_dma_batch(u32 gpu_id, u64 token, u64 start_page, u64 count, u64 *dmas_out);
void nv_rs_rmapi_os_flush_gpu_cache(void);
struct device *nv_rs_rmapi_gpu_device_get(u32 gpu_id)
{
unsigned long flags;
struct device *dev = NULL;
int i;
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
for (i = 0; i < NV_RS_RMAPI_MAX_GPUS; i++) {
if (nv_rs_rmapi_gpu_nodes[i].live &&
nv_rs_rmapi_gpu_nodes[i].gpu_id == gpu_id &&
nv_rs_rmapi_gpu_nodes[i].dev) {
dev = get_device(nv_rs_rmapi_gpu_nodes[i].dev);
break;
}
}
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
return dev;
}
static bool nv_rs_rmapi_gpu_device_live(u32 gpu_id, struct device *dev)
{
unsigned long flags;
bool live = false;
int i;
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
for (i = 0; i < NV_RS_RMAPI_MAX_GPUS; i++) {
if (nv_rs_rmapi_gpu_nodes[i].live &&
nv_rs_rmapi_gpu_nodes[i].gpu_id == gpu_id &&
nv_rs_rmapi_gpu_nodes[i].dev == dev) {
live = true;
break;
}
}
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
return live;
}
unsigned int nv_rs_rmapi_gpu_dma_bits(u32 gpu_id)
{
unsigned long flags;
unsigned int bits = 47;
int i;
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
for (i = 0; i < NV_RS_RMAPI_MAX_GPUS; i++) {
if (nv_rs_rmapi_gpu_nodes[i].live && nv_rs_rmapi_gpu_nodes[i].gpu_id == gpu_id) {
if (nv_rs_rmapi_gpu_nodes[i].dma_bits)
bits = nv_rs_rmapi_gpu_nodes[i].dma_bits;
break;
}
}
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
return bits;
}
/* Raise the device's streaming DMA mask through the PCI adapter's access lock;
* the leases, their width (`dma_bits`) and the coherent mask stay as they are.
* The GPU's probe holds a 32-bit lease for its lifetime, so a plain
* renegotiation fails, and every page above 4 GiB that the DMA API then maps for
* the GPU is bounced through swiotlb (the GPU's writes never reach the page the
* CPU reads: libcuda waits forever at context creation). */
void nv_rs_rmapi_gpu_negotiate_dma(u32 gpu_id, unsigned int bits)
{
unsigned long flags;
struct nv_rs_pci *pci = NULL;
unsigned int max_bits = 0;
int i;
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
for (i = 0; i < NV_RS_RMAPI_MAX_GPUS; i++) {
if (nv_rs_rmapi_gpu_nodes[i].live &&
nv_rs_rmapi_gpu_nodes[i].gpu_id == gpu_id) {
max_bits = nv_rs_rmapi_gpu_nodes[i].dma_bits;
if (nv_rs_rmapi_gpu_nodes[i].owner)
pci = nv_rs_gpu_owner_pci_get(nv_rs_rmapi_gpu_nodes[i].owner);
break;
}
}
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
if (max_bits && bits > max_bits)
bits = max_bits;
if (pci) {
(void)nv_rs_pci_widen_dma(pci, bits);
nv_rs_pci_put(pci);
}
}
static void nv_rs_rmapi_dma_map_destroy(struct nv_rs_rmapi_dma_map *dm)
{
u64 i;
if (dm->sg_mapped) {
dma_unmap_sgtable(dm->dev, &dm->sgt, DMA_BIDIRECTIONAL, 0);
sg_free_table(&dm->sgt);
} else if (dm->contiguous) {
if (dm->count > 0 && dm->encoded[0]) {
dma_unmap_page(dm->dev, (dma_addr_t)(dm->encoded[0] - 1),
dm->count << PAGE_SHIFT, DMA_BIDIRECTIONAL);
}
} else {
for (i = 0; i < dm->count; i++) {
if (dm->encoded[i]) {
dma_unmap_page(dm->dev, (dma_addr_t)(dm->encoded[i] - 1),
PAGE_SIZE, DMA_BIDIRECTIONAL);
}
}
}
put_device(dm->dev);
kvfree(dm);
}
/* NV_DMA_MAX_SEGMENT_SIZE (620.73.04 nv-linux.h:1059) */
#define NV_RS_DMA_MAX_SEGMENT_SIZE 0x80000000u
/* nv_dma_map_scatterlist (620.73.04 nv-dma.c:356-399): every page of the allocation in one scatterlist
* (NV_ALLOC_DMA_SUBMAP_SCATTERLIST, nv-linux.h:1060-1068), mapped with one dma_map_sg, and each page's DMA address
* read back from the DMA segments, which the mapping may have merged (nv_load_dma_map_scatterlist, nv-dma.c:327-354).
* Behind an IOMMU the allocation gets one IOVA range instead of one per page. False leaves nothing mapped and the
* caller maps page by page. Called with nv_rs_rmapi_alloc_lock held, on a record nobody else can see yet. */
static bool nv_rs_rmapi_dma_map_whole(struct nv_rs_rmapi_dma_map *dm, struct page **pages)
{
struct scatterlist *sg;
unsigned int i;
u64 off, page = 0;
/* nv_dma_map_pages (nv-dma.c:486-559) maps a single page without a scatterlist */
if (dm->count < 2 || dm->count > UINT_MAX)
return false;
if (sg_alloc_table_from_pages_segment(&dm->sgt, pages, (unsigned int)dm->count, 0,
(unsigned long)dm->count << PAGE_SHIFT,
NV_RS_DMA_MAX_SEGMENT_SIZE, GFP_KERNEL))
return false;
if (dma_map_sgtable(dm->dev, &dm->sgt, DMA_BIDIRECTIONAL, 0)) {
sg_free_table(&dm->sgt);
return false;
}
for_each_sgtable_dma_sg(&dm->sgt, sg, i) {
for (off = 0; off < sg_dma_len(sg) && page < dm->count; off += PAGE_SIZE)
dm->encoded[page++] = (u64)sg_dma_address(sg) + off + 1;
}
if (page != dm->count) {
/* page-aligned segments cover every page; a table that does not is never used */
dma_unmap_sgtable(dm->dev, &dm->sgt, DMA_BIDIRECTIONAL, 0);
sg_free_table(&dm->sgt);
memset(dm->encoded, 0, dm->count * sizeof(dm->encoded[0]));
return false;
}
dm->sg_mapped = true;
pr_debug("nvidia_rs: DMA map of %llu pages: %u CPU segments, %u DMA segments\n",
dm->count, dm->sgt.orig_nents, dm->sgt.nents);
return true;
}
static void nv_rs_rmapi_alloc_unmap_dma(struct nv_rs_rmapi_alloc *alloc)
{
struct nv_rs_rmapi_dma_map *dm;
for (;;) {
mutex_lock(&nv_rs_rmapi_alloc_lock);
dm = nv_rs_dma_reg_pop_for_alloc(alloc);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (!dm)
break;
nv_rs_rmapi_dma_map_destroy(dm);
}
}
/* Unmap all retained per-GPU DMA records for `dev` before its PCI driver
* tears down the device's DMA context on removal. */
static void nv_rs_rmapi_allocs_unmap_dev(struct device *dev)
{
struct nv_rs_rmapi_dma_map *dm;
if (!dev)
return;
for (;;) {
mutex_lock(&nv_rs_rmapi_alloc_lock);
dm = nv_rs_dma_reg_pop_for_dev(dev);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (!dm)
break;
nv_rs_rmapi_dma_map_destroy(dm);
}
}
static struct nv_rs_rmapi_alloc *nv_rs_rmapi_alloc_find(u64 token)
{
return nv_rs_alloc_reg_find(token);
}
/* The kernel mapping of an allocation of this node is the page's own linear address for one page, as
* nv_alloc_kernel_mapping returns at->page_table[pageIndex].virt_addr for it (580.178.04 nv.c:3730-3737), and a vmap
* otherwise. Pinned user pages are always vmapped, as the original vmaps user memory of any size (isUserAllocatedMem,
* nv.c:3722-3732): their kernel mapping carries the record's cache type, not the linear map's attribute. */
static bool nv_rs_rmapi_kernel_is_vmap(const struct nv_rs_rmapi_alloc *alloc)
{
return alloc->count > 1 || alloc->user_pinned;
}
static void nv_rs_rmapi_alloc_unmap(struct nv_rs_rmapi_alloc *alloc)
{
if (alloc->kernel && nv_rs_rmapi_kernel_is_vmap(alloc))
vunmap(alloc->kernel);
alloc->kernel = NULL;
}
static void nv_rs_rmapi_put_sources(struct nv_rs_rmapi_alloc **sources, u64 count);
/* Releases DMA maps, kernel mapping, OS page references, and the record itself
* after Rust's AllocLedger has dropped its final reference. */
static void nv_rs_rmapi_alloc_destroy(struct nv_rs_rmapi_alloc *alloc)
{
u64 index;
if (alloc->external_dma) {
struct nv_rs_ext_release_work *rel = alloc->external_rel_work;
alloc->external_rel_work = NULL;
kvfree(alloc->external_dma_addrs);
alloc->external_dma_addrs = NULL;
kvfree(alloc);
if (rel) {
if (nv_rs_ext_release_wq)
queue_work(nv_rs_ext_release_wq, &rel->work);
else
nv_rs_ext_release_work_fn(&rel->work);
}
return;
}
nv_rs_rmapi_alloc_unmap_dma(alloc);
nv_rs_rmapi_alloc_unmap(alloc);
if (alloc->user_pinned) {
unpin_user_pages_dirty_lock(alloc->pages, alloc->count, alloc->writable);
/* Only now may the allocations the range was pinned through restore write-back, pool or free their pages.
* They are never pinned records themselves, so this does not recurse further. */
nv_rs_rmapi_put_sources(alloc->sources, alloc->source_count);
} else if (!nv_rs_sysmem_may_release(alloc->pages, alloc->count, alloc->kernel_uc)) {
/* nv_free_system_pages restores write-back first (580.178.04 nv-vm.c:619-620). Pages that may still be
* uncached are leaked: never pooled, never handed back to the page allocator. */
pr_warn_ratelimited("nvidia_rs: leaking %llu pages whose cached attribute could not be restored\n",
alloc->count);
} else {
int retain_mb = READ_ONCE(system_memory_pool_retain_mb);
for (index = 0; index < alloc->count; index++) {
if (retain_mb != 0)
nv_rs_sysmem_pool_push_page(alloc->pages[index]);
else
__free_page(alloc->pages[index]);
}
}
kvfree(alloc);
}
static void nv_rs_rmapi_alloc_put(struct nv_rs_rmapi_alloc *alloc)
{
bool destroy;
mutex_lock(&nv_rs_rmapi_alloc_lock);
destroy = nv_rs_alloc_reg_put_ptr(alloc);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (destroy)
nv_rs_rmapi_alloc_destroy(alloc);
}
/* NV_PIN_USER_PAGES (580.178.04 nv-mm.h:53-59): pin_user_pages lost its vmas argument in 6.5. */
#if defined(NV_RS_PIN_USER_PAGES_HAS_VMAS)
#define nv_rs_pin_user_pages(start, nr_pages, gup_flags, pages) \
pin_user_pages(start, nr_pages, gup_flags, pages, NULL)
#else
#define nv_rs_pin_user_pages pin_user_pages
#endif
/* Drops the uses a pinned record holds of the allocations its range was pinned through (nv_rs_rmapi_pin_retain) and
* frees the list. */
static void nv_rs_rmapi_put_sources(struct nv_rs_rmapi_alloc **sources, u64 count)
{
while (count)
nv_rs_rmapi_alloc_put(sources[--count]);
kvfree(sources);
}
/* The allocation of this node a user area maps: nv_rs_rmapi_mmap sets vm_private_data, as the original sets
* NV_VMA_PRIVATE(vma) = at (580.178.04 nv-mmap.c:706). NULL for any other area. */
static struct nv_rs_rmapi_alloc *nv_rs_rmapi_area_alloc(const struct vm_area_struct *vma)
{
return vma->vm_ops == &nv_rs_rmapi_vm_operations ? vma->vm_private_data : NULL;
}
/* The NV_MEMORY_* type nv_rs_rmapi_mmap gives the user mappings of `alloc`: its cache type, write-combined (2) or
* uncached (1), when the kernel mapping of its pages was made uncached; cached (0) otherwise. */
static u32 nv_rs_rmapi_user_cache(const struct nv_rs_rmapi_alloc *alloc)
{
if (!alloc->kernel_uc)
return 0;
return alloc->cache == 2 ? 2 : 1;
}
/* The areas of [start, end) of `mm`, under the mmap lock the range was pinned under: they are the areas the pages were
* pinned through, and each area this node mapped holds its file, whose mapping context holds the allocation.
* `uncached` / `write_combined`: the bytes of the range inside uncached / write-combined user mappings of this node
* (nv_rs_rmapi_user_cache), summed over every area. `set`: NULL when no area maps an allocation of this node; else room
* for 2 * NV_RS_PINNED_SOURCES_MAX entries whose first `source_count` are the allocations a record pinned through these
* areas holds, each once (nv_rs_pinned_sources_add; the second half keeps the allocations seen). An allocation counts
* once however many of its areas the range covers (a mapping split by mprotect, a second mmap next to it), and a
* mapping of pinned user pages counts for the allocations that record holds, so a record never holds another record
* and teardown never recurses past one level. Returns 0, NV_RS_STATUS_INSUFFICIENT_RESOURCES when the range lies in
* mappings of more than NV_RS_PINNED_SOURCES_MAX allocations or would hold more, or NV_RS_STATUS_NO_MEMORY. */
static u32 nv_rs_rmapi_pin_scan(struct mm_struct *mm, unsigned long start, unsigned long end, u64 *uncached,
u64 *write_combined, void ***set, u64 *source_count)
{
struct vm_area_struct *vma;
u64 owner_count = 0;
u32 status = 0;
*uncached = 0;
*write_combined = 0;
*set = NULL;
*source_count = 0;
for (vma = find_vma(mm, start); vma && vma->vm_start < end; vma = find_vma(mm, vma->vm_end)) {
struct nv_rs_rmapi_alloc *owner = nv_rs_rmapi_area_alloc(vma);
u32 type;
if (!owner)
continue;
/* the areas do not overlap, so neither sum exceeds the length of the range */
type = nv_rs_rmapi_user_cache(owner);
if (type == 2)
*write_combined += nv_rs_pinned_area_bytes(start, end, vma->vm_start, vma->vm_end);
else if (type == 1)
*uncached += nv_rs_pinned_area_bytes(start, end, vma->vm_start, vma->vm_end);
if (status)
continue;
if (!*set) {
*set = kvcalloc(2 * NV_RS_PINNED_SOURCES_MAX, sizeof(**set), GFP_KERNEL);
if (!*set) {
status = NV_RS_STATUS_NO_MEMORY;
continue;
}
}
if (!nv_rs_pinned_sources_add(*set + NV_RS_PINNED_SOURCES_MAX, &owner_count, *set, source_count,
NV_RS_PINNED_SOURCES_MAX, owner,
owner->user_pinned ? (void *const *)owner->sources : (void *const *)&owner,
owner->user_pinned ? owner->source_count : 1))
status = NV_RS_STATUS_INSUFFICIENT_RESOURCES;
}
return status;
}
/* Takes one use of each of the `count` allocations nv_rs_rmapi_pin_scan gathered in `set`, into `sources` (room for
* `count`), under the same mmap lock, whose areas keep them alive until then. Returns how many it took; fewer than
* `count` only if a use count is saturated. */
static u64 nv_rs_rmapi_pin_retain(void *const *set, struct nv_rs_rmapi_alloc **sources, u64 count)
{
u64 taken;
mutex_lock(&nv_rs_rmapi_alloc_lock);
for (taken = 0; taken < count && nv_rs_alloc_reg_retain_ptr(set[taken]); taken++)
sources[taken] = set[taken];
mutex_unlock(&nv_rs_rmapi_alloc_lock);
return taken;
}
/* Pins `count` user-space 4 KiB pages starting at `address` for class 0x71
* (NV01_MEMORY_SYSTEM_OS_DESCRIPTOR) so UVM/GPU page tables can reference their physical
* addresses directly.
*
* As os_lock_user_pages (580.178.04 os-mlock.c:216-309) the pages are pinned under the mmap lock, and a range that
* cannot be pinned is refused with NV_ERR_INVALID_ADDRESS. The original looks at nothing else and maps every pinned
* range uncached (nv_register_user_pages, nv.c:3390): write-back pages get uncached mappings, and once the
* allocation a range was pinned through is freed (nv_free_system_pages restores write-back, nv-vm.c:619-620;
* 620.73.04 hands freed pages to its pool, nv-vm.c:962-963) the pinned record maps pages that are write-back again
* or belong to another allocation. Here:
* - a range that lies wholly in uncached user mappings of this node's allocations whose kernel mapping was made
* uncached gets uncached kernel and user mappings; one that lies wholly in write-combined user mappings of them gets
* write-combined kernel (vmap) and user mappings, the type of the user mappings it was pinned through; any other
* range cached ones (PinnedRangeCache). The pages' attribute in the linear map stays their allocation's (UC- for
* both types, as the original's nv_set_memory_type makes it, nv-vm.c:583-584);
* - a range that lies partly in such mappings and partly in other memory, or in both uncached and write-combined
* ones, is refused with NV_ERR_INVALID_ADDRESS: no one mapping type fits all its pages;
* - the record holds every allocation of this node it was pinned through until it is destroyed, so none restores
* write-back, pools or frees its pages first. It holds each of them once, however many areas of the range map it
* and through however many mappings of pinned records, and takes one use of each; a range that lies in user
* mappings of more than NV_RS_PINNED_SOURCES_MAX allocations, or would hold more, is refused with
* NV_ERR_INSUFFICIENT_RESOURCES (0x1a; the original has no such list, so no such refusal). */
u32 nv_rs_rmapi_os_lock_user_pages(u64 address, u64 count, bool writable, u64 *token)
{
struct nv_rs_rmapi_alloc *alloc;
struct nv_rs_rmapi_alloc **sources = NULL;
void **set = NULL;
struct mm_struct *mm = current->mm;
unsigned long start = (unsigned long)address, end;
u64 pinned = 0, uncached = 0, write_combined = 0, source_count = 0, taken = 0;
u64 pool;
u64 tok = 0;
u32 cache = NV_RS_PINNED_RANGE_REFUSED, status = NV_RS_STATUS_INVALID_ADDRESS;
bool ok;
unsigned int gup_flags = writable ? FOLL_WRITE : 0;
#ifdef FOLL_LONGTERM
/* Match stock 580.178.04 os-mlock.c: long-term GPU DMA pins must migrate out of CMA/movable zones. */
gup_flags |= FOLL_LONGTERM;
#endif
if (!count || !token || !mm || (address & (PAGE_SIZE - 1)))
return NV_RS_STATUS_INVALID_ARGUMENT;
pool = nv_rs_sysmem_pool_len();
mutex_lock(&nv_rs_rmapi_alloc_lock);
ok = nv_rs_alloc_reg_can_admit(count, true, pool,
nv_rs_rmapi_total_max_pages(),
nv_rs_rmapi_memory_max_pages());
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (!ok)
return NV_RS_STATUS_NO_MEMORY;
alloc = kvzalloc(struct_size(alloc, pages, count), GFP_KERNEL);
if (!alloc)
return NV_RS_STATUS_NO_MEMORY;
/* The mmap lock also keeps the areas the pages were pinned through for the scan below. */
mmap_read_lock(mm);
while (pinned < count) {
u64 remain = count - pinned;
unsigned long chunk = remain > 1024 ? 1024 : (unsigned long)remain;
long got = nv_rs_pin_user_pages((unsigned long)(address + (pinned << PAGE_SHIFT)),
chunk, gup_flags, &alloc->pages[pinned]);
if (got <= 0)
break;
pinned += (u64)got;
}
if (pinned == count) {
/* every page is mapped, so [start, end) is a valid user range */
end = start + (unsigned long)(count << PAGE_SHIFT);
status = nv_rs_rmapi_pin_scan(mm, start, end, &uncached, &write_combined, &set, &source_count);
cache = nv_rs_pinned_range_cache(count << PAGE_SHIFT, uncached, write_combined);
if (cache == NV_RS_PINNED_RANGE_REFUSED)
status = NV_RS_STATUS_INVALID_ADDRESS;
if (!status && source_count) {
sources = kvmalloc_array(source_count, sizeof(*sources), GFP_KERNEL);
if (!sources)
status = NV_RS_STATUS_NO_MEMORY;
else if ((taken = nv_rs_rmapi_pin_retain(set, sources, source_count)) != source_count)
status = NV_RS_STATUS_INVALID_ADDRESS;
}
}
mmap_read_unlock(mm);
kvfree(set);
if (status) {
if (pinned > 0)
unpin_user_pages(alloc->pages, pinned);
nv_rs_rmapi_put_sources(sources, taken);
kvfree(alloc);
return status;
}
alloc->count = count;
alloc->cache = cache;
/* uncached or write-combined: every page lies in user mappings of that type (nv_rs_rmapi_user_cache) */
alloc->kernel_uc = cache != 0;
alloc->user_pinned = true;
alloc->writable = writable;
alloc->sources = sources;
alloc->source_count = source_count;
mutex_lock(&nv_rs_rmapi_alloc_lock);
ok = nv_rs_alloc_reg_insert(alloc, count, true, &tok);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (!ok) {
unpin_user_pages(alloc->pages, count);
nv_rs_rmapi_put_sources(sources, source_count);
kvfree(alloc);
return NV_RS_STATUS_NO_MEMORY;
}
alloc->token = tok;
*token = tok;
return 0;
}
void nv_rs_rmapi_os_unlock_user_pages(u64 token)
{
void *ptr = NULL;
bool destroy;
mutex_lock(&nv_rs_rmapi_alloc_lock);
destroy = nv_rs_alloc_reg_mark_freed_and_put(token, &ptr);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (destroy && ptr)
nv_rs_rmapi_alloc_destroy(ptr);
}
#ifndef NV_RS_PCI_TEST_EDU
extern u32 nv_rs_rmapi_reg_ext_user_pages(u32 client, u32 device, u32 handle,
u32 gpu_id, u64 token, u64 bytes);
/*
* Wraps an already-DMA-mapped scatterlist (e.g. an imported PRIME DMA-BUF from
* `nvidia_rs_drm.ko`) in an RM `0x0071` (`NV01_MEMORY_SYSTEM_OS_DESCRIPTOR`)
* `UserPages` handle so `0x00003d05` / `0x00003d06` (`EXPORT_OBJECT_TO_FD` /
* `IMPORT_OBJECT_FROM_FD`) share its backing and pin its lifetime until the
* export FD and all imported RM handles are released.
*
* Ownership contract:
* - Returns 0: ownership of `(release_fn, release_priv, release_owner)` has
* transferred to the RM memory object; `release_fn(release_priv)` followed
* by `module_put(release_owner)` will run on `nv_rs_ext_release_wq` when
* the last RM reference drops.
* - Returns negative errno: caller retains ownership and must release them.
*/
int nv_rs_rmapi_register_external_sgt(u32 client, u32 device, u32 handle,
u32 gpu_id, const struct sg_table *sgt,
u64 size, void (*release_fn)(void *),
void *release_priv,
struct module *release_owner);
int nv_rs_rmapi_register_external_sgt(u32 client, u32 device, u32 handle,
u32 gpu_id, const struct sg_table *sgt,
u64 size, void (*release_fn)(void *),
void *release_priv,
struct module *release_owner)
{
struct nv_rs_rmapi_alloc *alloc;
struct nv_rs_ext_release_work *rel_work = NULL;
struct scatterlist *sg;
u64 *dma_addrs;
u64 count, page = 0, pool, tok = 0, dma_limit;
unsigned int i;
u32 rm_st;
bool ok;
if (!sgt || !sgt->sgl || size == 0 || (size & (PAGE_SIZE - 1)))
return -EINVAL;
/* The addresses go into GPU PTEs verbatim: anything past the GPU's DMA
* width (40 bits on GV11B) would be truncated by the MMU. */
dma_limit = DMA_BIT_MASK(nv_rs_rmapi_gpu_dma_bits(gpu_id));
count = size >> PAGE_SHIFT;
if (count == 0 || count > (u64)UINT_MAX)
return -EINVAL;
pool = nv_rs_sysmem_pool_len();
mutex_lock(&nv_rs_rmapi_alloc_lock);
ok = nv_rs_alloc_reg_can_admit(count, true, pool,
nv_rs_rmapi_total_max_pages(),
nv_rs_rmapi_memory_max_pages());
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (!ok)
return -ENOMEM;
dma_addrs = kvmalloc_array(count, sizeof(*dma_addrs), GFP_KERNEL);
if (!dma_addrs)
return -ENOMEM;
for_each_sgtable_dma_sg(sgt, sg, i) {
dma_addr_t addr = sg_dma_address(sg);
unsigned int len = sg_dma_len(sg);
u64 off;
if ((addr & (PAGE_SIZE - 1)) || (len & (PAGE_SIZE - 1)) ||
(len && ((u64)addr > dma_limit ||
(u64)len - 1 > dma_limit - (u64)addr))) {
kvfree(dma_addrs);
return -EINVAL;
}
for (off = 0; off < (u64)len; off += PAGE_SIZE) {
if (page >= count) {
kvfree(dma_addrs);
return -EINVAL;
}
dma_addrs[page++] = (u64)addr + off;
}
}
if (page != count) {
kvfree(dma_addrs);
return -EINVAL;
}
if (release_fn || release_owner) {
rel_work = kzalloc(sizeof(*rel_work), GFP_KERNEL);
if (!rel_work) {
kvfree(dma_addrs);
return -ENOMEM;
}
INIT_WORK(&rel_work->work, nv_rs_ext_release_work_fn);
rel_work->release_fn = release_fn;
rel_work->release_priv = release_priv;
rel_work->release_owner = release_owner;
}
alloc = kvzalloc(sizeof(*alloc), GFP_KERNEL);
if (!alloc) {
kfree(rel_work);
kvfree(dma_addrs);
return -ENOMEM;
}
alloc->count = count;
alloc->user_pinned = true;
alloc->writable = true;
alloc->external_dma = true;
alloc->external_gpu_id = gpu_id;
alloc->external_dma_addrs = dma_addrs;
alloc->external_rel_work = rel_work;
mutex_lock(&nv_rs_rmapi_alloc_lock);
ok = nv_rs_alloc_reg_insert(alloc, count, true, &tok);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (!ok) {
kfree(rel_work);
kvfree(dma_addrs);
kvfree(alloc);
return -ENOMEM;
}
alloc->token = tok;
mutex_lock(&nv_rs_rmapi_lock);
rm_st = nv_rs_rmapi_reg_ext_user_pages(client, device, handle, gpu_id,
tok, size);
mutex_unlock(&nv_rs_rmapi_lock);
if (rm_st != 0) {
/* Detach release work before destroying so caller retains ownership. */
mutex_lock(&nv_rs_rmapi_alloc_lock);
alloc->external_rel_work = NULL;
mutex_unlock(&nv_rs_rmapi_alloc_lock);
kfree(rel_work);
nv_rs_rmapi_os_unlock_user_pages(tok);
return (rm_st == NV_RS_STATUS_NO_MEMORY) ? -ENOMEM : -EINVAL;
}
return 0;
}
EXPORT_SYMBOL(nv_rs_rmapi_register_external_sgt);
#endif
/* nv_alloc_pages: `count` zeroed 4 KiB pages. Granules other than 4 KiB and contiguous
* runs of more than one page are not provided. */
u32 nv_rs_rmapi_os_alloc_pages(u64 count, u64 page, bool contiguous, u32 cache, u64 *token)
{
struct nv_rs_rmapi_alloc *alloc;
u64 index;
u64 pool;
u64 tok = 0;
bool ok;
if (!count || cache > 2)
return NV_RS_STATUS_INVALID_ARGUMENT;
if (page != PAGE_SIZE)
return NV_RS_STATUS_NOT_SUPPORTED;
pool = nv_rs_sysmem_pool_len();
mutex_lock(&nv_rs_rmapi_alloc_lock);
ok = nv_rs_alloc_reg_can_admit(count, false, pool,
nv_rs_rmapi_total_max_pages(),
nv_rs_rmapi_memory_max_pages());
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (!ok)
return NV_RS_STATUS_NO_MEMORY;
alloc = kvzalloc(struct_size(alloc, pages, count), GFP_KERNEL);
if (!alloc)
return NV_RS_STATUS_NO_MEMORY;
if (contiguous && count > 1) {
unsigned int order = get_order(count << PAGE_SHIFT);
struct page *head;
u64 total_order_pages;
#if defined(MAX_PAGE_ORDER)
if (order > MAX_PAGE_ORDER) {
#else
if (order >= MAX_ORDER) {
#endif
kvfree(alloc);
return NV_RS_STATUS_NO_MEMORY;
}
head = alloc_pages(GFP_KERNEL | __GFP_ZERO, order);
if (!head) {
kvfree(alloc);
return NV_RS_STATUS_NO_MEMORY;
}
split_page(head, order);
total_order_pages = 1ULL << order;
for (index = 0; index < count; index++)
alloc->pages[index] = head + index;
for (; index < total_order_pages; index++)
__free_page(head + index);
} else {
for (index = 0; index < count;) {
u32 limit = min_t(u64, count - index, 32);
u32 pooled = nv_rs_sysmem_pool_pop_pages(&alloc->pages[index], limit);
index += pooled;
if (pooled == limit)
continue;
/* The pool was exhausted at this acquisition. Allocate one fresh
* zeroed page, then retry the pool (it may refill concurrently). */
alloc->pages[index] = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (!alloc->pages[index]) {
while (index--)
__free_page(alloc->pages[index]);
kvfree(alloc);
return NV_RS_STATUS_NO_MEMORY;
}
index++;
}
}
alloc->count = count;
alloc->cache = cache;
alloc->contiguous = contiguous && count > 1;
/* nv_alloc_system_pages: not cached -> nv_set_memory_type(at, NV_MEMORY_UNCACHED) (580.178.04 nv-vm.c:583-584).
* If that fails the allocation stays cached everywhere, user mappings included. */
if (cache != 0) {
int uc = nv_rs_sysmem_make_uncached(alloc->pages, count);
if (uc < 0) {
pr_warn_ratelimited("nvidia_rs: leaking %llu pages whose cached attribute could not be restored\n",
count);
kvfree(alloc);
return NV_RS_STATUS_NO_MEMORY;
}
alloc->kernel_uc = uc == 0;
}
mutex_lock(&nv_rs_rmapi_alloc_lock);
ok = nv_rs_alloc_reg_insert(alloc, count, false, &tok);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (!ok) {
/* as on free: pages that may still be uncached are leaked */
if (nv_rs_sysmem_may_release(alloc->pages, count, alloc->kernel_uc)) {
for (index = 0; index < count; index++)
__free_page(alloc->pages[index]);
}
kvfree(alloc);
return NV_RS_STATUS_NO_MEMORY;
}
alloc->token = tok;
*token = tok;
return 0;
}
/* nv_free_pages: the RM object is gone; the token names nothing from here on,
* while remaining in the Rust registry until users == 0 so hot-unplug DMA
* teardown never misses a record still held by a file mapping context. */
void nv_rs_rmapi_os_free_pages(u64 token)
{
void *ptr = NULL;
bool destroy;
mutex_lock(&nv_rs_rmapi_alloc_lock);
destroy = nv_rs_alloc_reg_mark_freed_and_put(token, &ptr);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (!ptr)
return;
nv_rs_rmapi_alloc_unmap(ptr);
if (destroy)
nv_rs_rmapi_alloc_destroy(ptr);
}
/* nv_vmap (580.178.04 nv-vm.c:634-656), which nv_alloc_kernel_mapping asks for a cached mapping only for
* NV_MEMORY_CACHED (nv.c:3762-3763): PAGE_KERNEL_NOCACHE for pages whose kernel mapping was made uncached, the
* write-combined allocation's own vmap included (nv_vmap has no write-combined protection). Pinned user pages whose
* range lies wholly in write-combined user mappings are mapped write-combined instead, the type of those mappings;
* the original maps every pinned range PAGE_KERNEL_NOCACHE (nv_register_user_pages, nv.c:3390). */
static pgprot_t nv_rs_rmapi_kernel_prot(const struct nv_rs_rmapi_alloc *alloc)
{
#ifdef CONFIG_X86
if (alloc->kernel_uc)
return alloc->user_pinned && alloc->cache == 2 ? pgprot_writecombine(PAGE_KERNEL) : PAGE_KERNEL_NOCACHE;
#endif
return PAGE_KERNEL;
}
/* The kernel mapping nv_alloc_kernel_mapping makes of the whole allocation (nv_rs_rmapi_kernel_is_vmap). Called with
* nv_rs_rmapi_alloc_lock held. */
static void *nv_rs_rmapi_kernel_map_pages(struct nv_rs_rmapi_alloc *alloc)
{
if (!nv_rs_rmapi_kernel_is_vmap(alloc))
return page_address(alloc->pages[0]);
return vmap(alloc->pages, alloc->count, VM_MAP, nv_rs_rmapi_kernel_prot(alloc));
}
/* nv_alloc_kernel_mapping of the whole allocation: the page's own address for one page,
* vmap for more and for pinned user pages. */
u32 nv_rs_rmapi_os_kernel_map(u64 token, u64 size)
{
struct nv_rs_rmapi_alloc *alloc;
u32 rc = 0;
mutex_lock(&nv_rs_rmapi_alloc_lock);
alloc = nv_rs_rmapi_alloc_find(token);
if (!alloc || alloc->external_dma || size > alloc->count << PAGE_SHIFT) {
rc = NV_RS_STATUS_INVALID_ARGUMENT;
} else if (!alloc->kernel) {
alloc->kernel = nv_rs_rmapi_kernel_map_pages(alloc);
if (!alloc->kernel)
rc = NV_RS_STATUS_NO_MEMORY;
}
mutex_unlock(&nv_rs_rmapi_alloc_lock);
return rc;
}
#ifdef NV_RS_PCI_TEST_EDU
/* EDU guest test only (tests/vm/edu_adapter_test.c): the kernel mapping of an allocation, NULL before one is made,
* so the test can read the cache mode of its page-table entries. */
void *nv_rs_rmapi_os_kernel_address(u64 token);
void *nv_rs_rmapi_os_kernel_address(u64 token)
{
struct nv_rs_rmapi_alloc *alloc;
void *kernel = NULL;
mutex_lock(&nv_rs_rmapi_alloc_lock);
alloc = nv_rs_rmapi_alloc_find(token);
if (alloc)
kernel = alloc->kernel;
mutex_unlock(&nv_rs_rmapi_alloc_lock);
return kernel;
}
/* EDU guest test only: how many entries the list of allocations the pinned record `token` holds has (`sources`,
* nv_rs_rmapi_pin_scan), and in `*of_source` how many of them are the allocation `source`. U64_MAX for a token that
* is no pinned record. */
u64 nv_rs_rmapi_os_pinned_sources(u64 token, u64 source, u64 *of_source);
u64 nv_rs_rmapi_os_pinned_sources(u64 token, u64 source, u64 *of_source)
{
struct nv_rs_rmapi_alloc *alloc, *held;
u64 count = U64_MAX, index;
*of_source = 0;
mutex_lock(&nv_rs_rmapi_alloc_lock);
alloc = nv_rs_rmapi_alloc_find(token);
held = nv_rs_rmapi_alloc_find(source);
if (alloc && alloc->user_pinned) {
count = alloc->source_count;
for (index = 0; index < count; index++)
if (held && alloc->sources[index] == held)
(*of_source)++;
}
mutex_unlock(&nv_rs_rmapi_alloc_lock);
return count;
}
#endif
void nv_rs_rmapi_os_kernel_unmap(u64 token)
{
struct nv_rs_rmapi_alloc *alloc;
mutex_lock(&nv_rs_rmapi_alloc_lock);
alloc = nv_rs_rmapi_alloc_find(token);
if (alloc)
nv_rs_rmapi_alloc_unmap(alloc);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
}
/* Kernel write into a system-memory allocation (e.g. 0xc36f0108 notifier update). */
u32 nv_rs_rmapi_os_kernel_write(u64 token, u64 offset, const u8 *bytes, size_t length)
{
struct nv_rs_rmapi_alloc *alloc;
u64 total;
u32 rc = 0;
if (!bytes)
return NV_RS_STATUS_INVALID_ARGUMENT;
mutex_lock(&nv_rs_rmapi_alloc_lock);
alloc = nv_rs_rmapi_alloc_find(token);
if (!alloc) {
rc = NV_RS_STATUS_INVALID_ARGUMENT;
} else {
total = alloc->count << PAGE_SHIFT;
if (offset > total || length > total - offset) {
rc = NV_RS_STATUS_INVALID_ARGUMENT;
} else {
if (!alloc->kernel) {
alloc->kernel = nv_rs_rmapi_kernel_map_pages(alloc);
if (!alloc->kernel)
rc = NV_RS_STATUS_NO_MEMORY;
}
if (!rc) {
if (length == 4 && (offset & 3) == 0) {
u32 v;
memcpy(&v, bytes, sizeof(v));
smp_wmb();
WRITE_ONCE(*(u32 *)((u8 *)alloc->kernel + offset), v);
} else if (length == 8 && (offset & 7) == 0) {
u64 v;
memcpy(&v, bytes, sizeof(v));
smp_wmb();
WRITE_ONCE(*(u64 *)((u8 *)alloc->kernel + offset), v);
} else {
memcpy((u8 *)alloc->kernel + offset, bytes, length);
}
}
}
}
mutex_unlock(&nv_rs_rmapi_alloc_lock);
return rc;
}
/* Resolves the physical address of one 4 KiB page of a 0x3e system-memory allocation. */
u32 nv_rs_rmapi_os_page_phys(u64 token, u64 page_index, u64 *phys)
{
struct nv_rs_rmapi_alloc *alloc;
u32 rc = 0;
mutex_lock(&nv_rs_rmapi_alloc_lock);
alloc = nv_rs_rmapi_alloc_find(token);
if (!alloc || !phys || page_index >= alloc->count)
rc = NV_RS_STATUS_INVALID_ARGUMENT;
else if (alloc->external_dma)
*phys = alloc->external_dma_addrs[page_index];
else
*phys = (u64)page_to_phys(alloc->pages[page_index]);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
return rc;
}
/* Resolves one 4 KiB page of a system-memory allocation for `gpu_id`. The first request for a GPU DMA-maps the whole
* allocation (nv_rs_rmapi_dma_map_whole); when that fails, each page is mapped as it is first asked for. */
u32 nv_rs_rmapi_os_page_dma(u32 gpu_id, u64 token, u64 page_index, u64 *dma_out)
{
struct nv_rs_rmapi_alloc *alloc;
struct nv_rs_rmapi_dma_map *dm = NULL;
struct device *dev;
dma_addr_t dma;
u32 rc = 0;
if (!dma_out)
return NV_RS_STATUS_INVALID_ARGUMENT;
dev = nv_rs_rmapi_gpu_device_get(gpu_id);
if (dev)
nv_rs_rmapi_gpu_negotiate_dma(gpu_id, nv_rs_rmapi_gpu_dma_bits(gpu_id));
mutex_lock(&nv_rs_rmapi_alloc_lock);
alloc = nv_rs_rmapi_alloc_find(token);
if (!alloc || page_index >= alloc->count) {
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (dev)
put_device(dev);
return NV_RS_STATUS_INVALID_ARGUMENT;
}
if (alloc->external_dma) {
if (gpu_id != alloc->external_gpu_id) {
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (dev)
put_device(dev);
return NV_RS_STATUS_INVALID_ARGUMENT;
}
*dma_out = alloc->external_dma_addrs[page_index];
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (dev)
put_device(dev);
return 0;
}
if (!dev) {
*dma_out = (u64)page_to_phys(alloc->pages[page_index]);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
return 0;
}
if (!nv_rs_rmapi_gpu_device_live(gpu_id, dev)) {
mutex_unlock(&nv_rs_rmapi_alloc_lock);
put_device(dev);
return NV_RS_STATUS_INVALID_ARGUMENT;
}
dm = nv_rs_dma_reg_find(alloc, gpu_id, dev);
if (dm) {
put_device(dev);
} else {
dm = kvzalloc(struct_size(dm, encoded, alloc->count), GFP_KERNEL);
if (!dm) {
mutex_unlock(&nv_rs_rmapi_alloc_lock);
put_device(dev);
return NV_RS_STATUS_NO_MEMORY;
}
dm->dev = dev;
dm->gpu_id = gpu_id;
dm->count = alloc->count;
(void)nv_rs_rmapi_dma_map_whole(dm, alloc->pages);
if (!nv_rs_dma_reg_insert(alloc, gpu_id, dev, dm)) {
mutex_unlock(&nv_rs_rmapi_alloc_lock);
/* drops the mapping and the device reference */
nv_rs_rmapi_dma_map_destroy(dm);
return NV_RS_STATUS_NO_MEMORY;
}
}
if (!dm->encoded[page_index]) {
if (alloc->contiguous) {
dma = dma_map_page(dm->dev, alloc->pages[0], 0,
alloc->count << PAGE_SHIFT, DMA_BIDIRECTIONAL);
if (dma_mapping_error(dm->dev, dma)) {
rc = NV_RS_STATUS_NO_MEMORY;
} else {
u64 idx;
dm->contiguous = true;
for (idx = 0; idx < alloc->count; idx++)
dm->encoded[idx] = (u64)dma + (idx << PAGE_SHIFT) + 1;
*dma_out = (u64)dma + (page_index << PAGE_SHIFT);
}
} else {
dma = dma_map_page(dm->dev, alloc->pages[page_index], 0, PAGE_SIZE, DMA_BIDIRECTIONAL);
if (dma_mapping_error(dm->dev, dma)) {
rc = NV_RS_STATUS_NO_MEMORY;
} else {
dm->encoded[page_index] = (u64)dma + 1;
*dma_out = (u64)dma;
}
}
} else {
*dma_out = dm->encoded[page_index] - 1;
}
mutex_unlock(&nv_rs_rmapi_alloc_lock);
return rc;
}
/* Batched DMA address lookup/mapping for `count` contiguous page indices under a single lock. */
u32 nv_rs_rmapi_os_page_dma_batch(u32 gpu_id, u64 token, u64 start_page, u64 count, u64 *dmas_out)
{
struct nv_rs_rmapi_alloc *alloc;
struct nv_rs_rmapi_dma_map *dm = NULL;
struct device *dev;
u64 i;
u32 rc = 0;
if (!dmas_out || count == 0)
return NV_RS_STATUS_INVALID_ARGUMENT;
dev = nv_rs_rmapi_gpu_device_get(gpu_id);
if (dev)
nv_rs_rmapi_gpu_negotiate_dma(gpu_id, nv_rs_rmapi_gpu_dma_bits(gpu_id));
mutex_lock(&nv_rs_rmapi_alloc_lock);
alloc = nv_rs_rmapi_alloc_find(token);
if (!alloc || start_page >= alloc->count || count > alloc->count - start_page) {
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (dev)
put_device(dev);
return NV_RS_STATUS_INVALID_ARGUMENT;
}
if (alloc->external_dma) {
if (gpu_id != alloc->external_gpu_id) {
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (dev)
put_device(dev);
return NV_RS_STATUS_INVALID_ARGUMENT;
}
for (i = 0; i < count; i++)
dmas_out[i] = alloc->external_dma_addrs[start_page + i];
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (dev)
put_device(dev);
return 0;
}
if (!dev) {
for (i = 0; i < count; i++)
dmas_out[i] = (u64)page_to_phys(alloc->pages[start_page + i]);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
return 0;
}
if (!nv_rs_rmapi_gpu_device_live(gpu_id, dev)) {
mutex_unlock(&nv_rs_rmapi_alloc_lock);
put_device(dev);
return NV_RS_STATUS_INVALID_ARGUMENT;
}
dm = nv_rs_dma_reg_find(alloc, gpu_id, dev);
if (dm) {
put_device(dev);
} else {
dm = kvzalloc(struct_size(dm, encoded, alloc->count), GFP_KERNEL);
if (!dm) {
mutex_unlock(&nv_rs_rmapi_alloc_lock);
put_device(dev);
return NV_RS_STATUS_NO_MEMORY;
}
dm->dev = dev;
dm->gpu_id = gpu_id;
dm->count = alloc->count;
if (!nv_rs_dma_reg_insert(alloc, gpu_id, dev, dm)) {
mutex_unlock(&nv_rs_rmapi_alloc_lock);
put_device(dev);
kvfree(dm);
return NV_RS_STATUS_NO_MEMORY;
}
}
if (alloc->contiguous && !dm->encoded[start_page]) {
dma_addr_t dma = dma_map_page(dm->dev, alloc->pages[0], 0,
alloc->count << PAGE_SHIFT, DMA_BIDIRECTIONAL);
if (dma_mapping_error(dm->dev, dma)) {
rc = NV_RS_STATUS_NO_MEMORY;
} else {
u64 idx;
dm->contiguous = true;
for (idx = 0; idx < alloc->count; idx++)
dm->encoded[idx] = (u64)dma + (idx << PAGE_SHIFT) + 1;
}
}
for (i = 0; rc == 0 && i < count; i++) {
u64 pg = start_page + i;
if (!dm->encoded[pg]) {
dma_addr_t dma = dma_map_page(dm->dev, alloc->pages[pg], 0, PAGE_SIZE, DMA_BIDIRECTIONAL);
if (dma_mapping_error(dm->dev, dma)) {
rc = NV_RS_STATUS_NO_MEMORY;
break;
}
dm->encoded[pg] = (u64)dma + 1;
}
dmas_out[i] = dm->encoded[pg] - 1;
}
mutex_unlock(&nv_rs_rmapi_alloc_lock);
return rc;
}
/* nv_alloc_user_mapping: the physical address of the page plus the offset in it. */
u32 nv_rs_rmapi_os_user_map(u64 token, u64 page_index, u32 page_offset, u64 *address)
{
struct nv_rs_rmapi_alloc *alloc;
u32 rc = 0;
mutex_lock(&nv_rs_rmapi_alloc_lock);
alloc = nv_rs_rmapi_alloc_find(token);
if (!alloc || alloc->external_dma || !address || page_index >= alloc->count || page_offset >= PAGE_SIZE)
rc = NV_RS_STATUS_INVALID_ARGUMENT;
else
*address = (u64)page_to_phys(alloc->pages[page_index]) + page_offset;
mutex_unlock(&nv_rs_rmapi_alloc_lock);
return rc;
}
/* os_match_mmap_offset: the page of the allocation at this physical address. */
u32 nv_rs_rmapi_os_match_offset(u64 token, u64 address, u64 *page_index)
{
struct nv_rs_rmapi_alloc *alloc;
u64 index;
u32 rc = NV_RS_STATUS_OBJECT_NOT_FOUND;
mutex_lock(&nv_rs_rmapi_alloc_lock);
alloc = nv_rs_rmapi_alloc_find(token);
if (alloc && !alloc->external_dma && page_index) {
for (index = 0; index < alloc->count; index++) {
if ((u64)page_to_phys(alloc->pages[index]) == address) {
*page_index = index;
rc = 0;
break;
}
}
}
mutex_unlock(&nv_rs_rmapi_alloc_lock);
return rc;
}
/* nv_add_mapping_context_to_file for system memory: the descriptor must name a file of
* this driver's control node (INVALID_ARGUMENT otherwise, as for a closed descriptor), and
* a file takes one context for its lifetime (STATE_IN_USE). The file is only looked at
* here; fput of a user task defers the final release, which takes nv_rs_rmapi_lock. */
u32 nv_rs_rmapi_os_add_context(s32 descriptor, u32 protection, u64 token, u64 page_index,
u32 caching)
{
struct nv_rs_rmapi_alloc *alloc;
struct nv_rs_rmapi_file *context;
struct file *target = fget(descriptor);
u32 status = 0;
if (!target)
return NV_RS_STATUS_INVALID_ARGUMENT;
context = target->private_data;
if (target->f_op != &nv_rs_rmapi_operations) {
status = NV_RS_STATUS_INVALID_ARGUMENT;
} else {
struct nv_rs_rmapi_alloc *retained = NULL;
int rc = 0;
mutex_lock(&nv_rs_rmapi_alloc_lock);
alloc = nv_rs_rmapi_alloc_find(token);
if (!alloc || alloc->external_dma || page_index >= alloc->count) {
mutex_unlock(&nv_rs_rmapi_alloc_lock);
status = NV_RS_STATUS_INVALID_ARGUMENT;
} else {
retained = nv_rs_alloc_reg_retain(token);
if (!retained) {
mutex_unlock(&nv_rs_rmapi_alloc_lock);
status = NV_RS_STATUS_INVALID_ARGUMENT;
} else {
rc = nv_rs_file_map_insert_alloc(context->owner, retained, page_index,
protection, caching);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (rc == 1) {
nv_rs_rmapi_alloc_put(retained);
status = NV_RS_STATUS_STATE_IN_USE;
} else if (rc < 0) {
nv_rs_rmapi_alloc_put(retained);
status = NV_RS_STATUS_NO_MEMORY;
}
}
}
}
fput(target);
return status;
}
/* The offsets the map functions below receive are relative to the BARs of the GPU that
* owns the object (`gpu_id`), but they are checked against and mapped from the BARs of the
* device node the descriptor names. The open layer's nvidia_mmap checks an absolute
* physical address against the BARs of the file's device, so a descriptor for another
* GPU can never reach a mapping there. Refuse it here the same way. Caller holds
* nv_rs_rmapi_lock, which guards nv_rs_rmapi_gpu_nodes. */
static bool nv_rs_rmapi_context_on_gpu(const struct nv_rs_rmapi_file *context, u32 gpu_id)
{
const struct nv_rs_rmapi_gpu_node *node;
if (context->gpu < 0 || context->gpu >= NV_RS_RMAPI_MAX_GPUS)
return false;
node = &nv_rs_rmapi_gpu_nodes[context->gpu];
return node->live && node->gpu_id == gpu_id;
}
/* An uncached IO mapping of registers in BAR0 or BAR1 for a device-node file. */
static u32 nv_rs_rmapi_map_io(u32 gpu_id, bool bar1, u64 offset, u64 length, bool write_only,
s32 descriptor, u64 *address)
{
struct file *target;
struct nv_rs_rmapi_file *context;
u64 io_phys = 0, user_addr;
u32 status = 0;
if (!address || !length || ((offset | length) & ~PAGE_MASK))
return NV_RS_STATUS_INVALID_ARGUMENT;
target = fget(descriptor);
if (!target)
return NV_RS_STATUS_INVALID_ARGUMENT;
context = target->private_data;
if (target->f_op != &nv_rs_rmapi_gpu_operations || !context || context->gpu < 0 ||
context->gpu >= NV_RS_RMAPI_MAX_GPUS) {
status = NV_RS_STATUS_INVALID_ARGUMENT;
} else if (!nv_rs_rmapi_context_on_gpu(context, gpu_id)) {
status = NV_RS_STATUS_INVALID_ARGUMENT;
} else if (bar1 ? !nv_rs_gpu_slot_validate_bar1((u32)context->gpu, context->generation, offset,
length, offset, &io_phys, &user_addr)
: !nv_rs_gpu_slot_validate_bar0((u32)context->gpu, context->generation, offset,
length, &io_phys)) {
status = NV_RS_STATUS_INVALID_ARGUMENT;
} else {
int rc;
mutex_lock(&nv_rs_rmapi_alloc_lock);
rc = nv_rs_file_map_insert_io(context->owner, io_phys, length,
write_only ? 2 : 1, 6);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (rc == 0)
*address = io_phys;
else if (rc == 1)
status = NV_RS_STATUS_STATE_IN_USE;
else
status = NV_RS_STATUS_NO_MEMORY;
}
fput(target);
return status;
}
/* Attaches a BAR0 IO mapping context (0xc361 VOLTA_USERMODE_A or 0x90e6
* GF100_SUBDEVICE_MASTER) to a device-node file and returns BAR0 + offset. */
u32 nv_rs_rmapi_os_map_register(u32 gpu_id, u64 offset, u64 length, bool write_only,
s32 descriptor, u64 *address)
{
return nv_rs_rmapi_map_io(gpu_id, false, offset, length, write_only, descriptor, address);
}
/* The same for the doorbell page in BAR1 (Hopper and later). */
u32 nv_rs_rmapi_os_map_doorbell(u32 gpu_id, u64 offset, u64 length, s32 descriptor, u64 *address)
{
return nv_rs_rmapi_map_io(gpu_id, true, offset, length, true, descriptor, address);
}
/* Attaches a BAR1 video-memory IO mapping context (0x40 video memory / USERD) to a
* device-node file and returns BAR1 + offset. Sub-page lengths/offsets (e.g. 0x200-byte
* Volta USERD) are rounded to enclosing pages for remap_pfn_range while returning the exact
* BAR1 physical offset to the caller. */
u32 nv_rs_rmapi_os_map_video(u32 gpu_id, u64 offset, u64 length, s32 descriptor,
u64 *address)
{
struct file *target;
struct nv_rs_rmapi_file *context;
u64 aligned_off, aligned_len, io_phys = 0, user_addr = 0;
u32 status = 0;
if (!address || !length)
return NV_RS_STATUS_INVALID_ARGUMENT;
aligned_off = offset & PAGE_MASK;
aligned_len = PAGE_ALIGN((offset & ~PAGE_MASK) + length);
if (!aligned_len)
return NV_RS_STATUS_INVALID_ARGUMENT;
target = fget(descriptor);
if (!target)
return NV_RS_STATUS_INVALID_ARGUMENT;
context = target->private_data;
if (target->f_op != &nv_rs_rmapi_gpu_operations || !context || context->gpu < 0 ||
context->gpu >= NV_RS_RMAPI_MAX_GPUS) {
status = NV_RS_STATUS_INVALID_ARGUMENT;
} else if (!nv_rs_rmapi_context_on_gpu(context, gpu_id)) {
status = NV_RS_STATUS_INVALID_ARGUMENT;
} else if (nv_rs_rmapi_gpu_nodes[context->gpu].pascal_userd_gpu && nv_rs_runtime_engines()) {
/* Do not create an identity-window mapping before or after BAR1 takeover. */
status = 0x56; /* NV_ERR_NOT_SUPPORTED */
} else if (!nv_rs_gpu_slot_validate_bar1((u32)context->gpu, context->generation,
aligned_off, aligned_len, offset,
&io_phys, &user_addr)) {
status = NV_RS_STATUS_INVALID_ARGUMENT;
} else {
int rc;
mutex_lock(&nv_rs_rmapi_alloc_lock);
rc = nv_rs_file_map_insert_io(context->owner, io_phys, aligned_len, 3, 2);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (rc == 0)
*address = user_addr;
else if (rc == 1)
status = NV_RS_STATUS_STATE_IN_USE;
else
status = NV_RS_STATUS_NO_MEMORY;
}
fput(target);
return status;
}
/* Attaches a scatter-gather BAR1 video-memory IO mapping context (multi-segment
* NONCONTIGUOUS/ALLOW_NONCONTIGUOUS 0x40 video memory) so mmap() maps all physical BAR1
* segments contiguously into a single user VMA via per-segment remap_pfn_range(). */
u32 nv_rs_rmapi_os_map_video_scatter(u32 gpu_id, u64 bar1_base,
const struct nv_rs_extent *extents, size_t count,
s32 descriptor, u64 *address)
{
struct file *target;
struct nv_rs_rmapi_file *context;
struct nv_rs_io_scatter *sc = NULL;
u64 total_aligned = 0, first_user_addr = 0;
u32 status = 0;
size_t i;
if (!address || !extents || count == 0 || count > 65536)
return NV_RS_STATUS_INVALID_ARGUMENT;
target = fget(descriptor);
if (!target)
return NV_RS_STATUS_INVALID_ARGUMENT;
context = target->private_data;
if (target->f_op != &nv_rs_rmapi_gpu_operations || !context || context->gpu < 0 ||
context->gpu >= NV_RS_RMAPI_MAX_GPUS || !nv_rs_rmapi_context_on_gpu(context, gpu_id)) {
fput(target);
return NV_RS_STATUS_INVALID_ARGUMENT;
}
sc = kvzalloc(struct_size(sc, segs, count), GFP_KERNEL);
if (!sc) {
fput(target);
return NV_RS_STATUS_NO_MEMORY;
}
sc->count = (u32)count;
for (i = 0; i < count; i++) {
u64 base = extents[i].base;
u64 last = extents[i].last;
u64 seg_len, raw_off, aligned_off, aligned_len, io_phys = 0, user_addr = 0;
if (last < base || (base == 0 && last == U64_MAX)) {
status = NV_RS_STATUS_INVALID_ARGUMENT;
break;
}
seg_len = (last - base) + 1;
if (bar1_base > U64_MAX - base) {
status = NV_RS_STATUS_INVALID_ARGUMENT;
break;
}
raw_off = bar1_base + base;
if (seg_len > U64_MAX - raw_off) {
status = NV_RS_STATUS_INVALID_ARGUMENT;
break;
}
/* Internal segment boundaries must be page-aligned for contiguous remap_pfn_range. */
if (count > 1) {
if (i > 0 && (raw_off & ~PAGE_MASK)) {
status = NV_RS_STATUS_NOT_SUPPORTED;
break;
}
if (i + 1 < count && ((raw_off + seg_len) & ~PAGE_MASK)) {
status = NV_RS_STATUS_NOT_SUPPORTED;
break;
}
}
aligned_off = raw_off & PAGE_MASK;
aligned_len = PAGE_ALIGN((raw_off & ~PAGE_MASK) + seg_len);
if (!aligned_len || aligned_len > U64_MAX - total_aligned) {
status = NV_RS_STATUS_INVALID_ARGUMENT;
break;
}
if (!nv_rs_gpu_slot_validate_bar1((u32)context->gpu, context->generation,
aligned_off, aligned_len, raw_off,
&io_phys, &user_addr)) {
status = NV_RS_STATUS_INVALID_ARGUMENT;
break;
}
sc->segs[i].io_phys = io_phys;
sc->segs[i].io_bytes = aligned_len;
total_aligned += aligned_len;
if (i == 0)
first_user_addr = user_addr;
}
if (status == 0) {
int rc;
mutex_lock(&nv_rs_rmapi_alloc_lock);
rc = nv_rs_file_map_insert_io_scatter(context->owner, sc, total_aligned, 3, 2);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (rc == 0) {
*address = first_user_addr;
sc = NULL; /* ownership transferred to FileMappingLedger */
} else if (rc == 1) {
status = NV_RS_STATUS_STATE_IN_USE;
} else {
status = NV_RS_STATUS_NO_MEMORY;
}
}
if (sc)
kvfree(sc);
fput(target);
return status;
}
static bool nv_rs_userd_block_available_locked(u32 gpu_id, u32 block, u64 owner)
{
const struct nv_rs_rmapi_file *context;
list_for_each_entry(context, &nv_rs_rmapi_userd_files, userd_link) {
if (context->userd_gpu_id == gpu_id && context->userd_block == block &&
(!context->userd_map_refs ||
(u64)(unsigned long)context->userd_control->private_data != owner))
return false;
}
return true;
}
bool nv_rs_rmapi_userd_block_available(u32 gpu_id, u32 block, u64 owner)
{
bool available;
mutex_lock(&nv_rs_rmapi_userd_lock);
available = nv_rs_userd_block_available_locked(gpu_id, block, owner);
mutex_unlock(&nv_rs_rmapi_userd_lock);
return available;
}
static bool nv_rs_rmapi_userd_admitted_locked(struct nv_rs_rmapi_file *context, u32 gpu_id)
{
struct nv_rs_rmapi_gpu_node *node = &nv_rs_rmapi_gpu_nodes[context->gpu];
unsigned long flags;
bool live;
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
live = node->live && node->generation == context->generation &&
node->gpu_id == gpu_id && node->userd_runtime_live;
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
return live;
}
u32 nv_rs_rmapi_os_map_pascal_userd(u32 gpu_id, u64 offset, u64 length, s32 descriptor,
u64 owner, u32 block, u64 *address, u64 *cookie)
{
struct nv_rs_rmapi_file *source = (struct nv_rs_rmapi_file *)(unsigned long)owner;
struct nv_rs_rmapi_file *context;
struct file *target;
u64 io_phys, user_addr;
u32 status = NV_RS_STATUS_INVALID_ARGUMENT;
if (!source || source->gpu != -1 || PAGE_SIZE != 4096 || !address || !cookie ||
!length || length > 0x200 - (offset & 0x1ff) ||
(offset & PAGE_MASK) != 0x200000ULL + (u64)block * PAGE_SIZE)
return status;
target = fget(descriptor);
if (!target)
return status;
if (target->f_op != &nv_rs_rmapi_gpu_operations)
goto put;
context = target->private_data;
/* Libcuda can open a dedicated GPU file without REGISTER_FD. Pin its
* verified RM owner only after validating the GPU, generation and BAR1. */
if (!context || (context->control && context->control != source->file) ||
!nv_rs_rmapi_context_on_gpu(context, gpu_id) ||
!nv_rs_gpu_slot_validate_bar1((u32)context->gpu, context->generation,
offset & PAGE_MASK, PAGE_SIZE, offset,
&io_phys, &user_addr) ||
!IS_ALIGNED(io_phys, PAGE_SIZE))
goto put;
mutex_lock(&nv_rs_rmapi_userd_lock);
if (!nv_rs_rmapi_userd_admitted_locked(context, gpu_id))
goto unlock;
if (context->userd_pgoff) {
/* The same file and live generation were validated above. The whole
* page is shared, so the pinned owner and block must also match.
* A cookie undergoing a zap cannot be reused. */
if (!context->userd_map_refs || context->userd_map_refs == U32_MAX ||
context->userd_control != source->file ||
context->userd_gpu_id != gpu_id || context->userd_block != block) {
goto unlock;
} else {
context->userd_map_refs++;
*address = user_addr;
*cookie = context->userd_pgoff;
status = 0;
}
} else if (nv_rs_rmapi_userd_last_pgoff < (MAX_LFS_FILESIZE >> PAGE_SHIFT) - 1 &&
nv_rs_userd_block_available_locked(gpu_id, block, owner)) {
int rc;
mutex_lock(&nv_rs_rmapi_alloc_lock);
rc = nv_rs_file_map_insert_io(context->owner, io_phys, PAGE_SIZE, 3, 2);
if (!rc) {
/* The GPU file survives all its VMAs. Keep the owner token unique
* until that file goes away, even if its descriptor was closed. */
context->userd_control = get_file(source->file);
context->userd_gpu_id = gpu_id;
context->userd_block = block;
context->userd_map_refs = 1;
context->userd_file = true;
context->userd_pgoff = ++nv_rs_rmapi_userd_last_pgoff;
list_add_tail(&context->userd_link, &nv_rs_rmapi_userd_files);
*address = user_addr;
*cookie = context->userd_pgoff;
status = 0;
}
mutex_unlock(&nv_rs_rmapi_alloc_lock);
}
unlock:
mutex_unlock(&nv_rs_rmapi_userd_lock);
put:
fput(target);
return status;
}
static u32 nv_rs_rmapi_alloc_ensure_kernel_locked(struct nv_rs_rmapi_alloc *alloc)
{
if (!alloc->kernel) {
alloc->kernel = nv_rs_rmapi_kernel_map_pages(alloc);
if (!alloc->kernel)
return NV_RS_STATUS_NO_MEMORY;
}
return 0;
}
static struct pci_dev *nv_rs_rmapi_gpu_pci_get(u32 gpu_id)
{
unsigned long flags;
struct pci_dev *pdev = NULL;
int i;
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
for (i = 0; i < NV_RS_RMAPI_MAX_GPUS; i++) {
if (nv_rs_rmapi_gpu_nodes[i].live &&
nv_rs_rmapi_gpu_nodes[i].gpu_id == gpu_id &&
nv_rs_rmapi_gpu_nodes[i].pdev) {
pdev = pci_dev_get(nv_rs_rmapi_gpu_nodes[i].pdev);
break;
}
}
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
return pdev;
}
/* Kernel-mode NvRmMapMemory (NVOS33, caller.is_kernel()) for system memory:
* lazily vmaps the pages and returns the kernel virtual address + offset.
* Callers must retain an allocation reference while using the returned address. */
u32 nv_rs_rmapi_os_kernel_map_va(u64 token, u64 offset, u64 length, u64 *address)
{
struct nv_rs_rmapi_alloc *alloc;
u64 total;
u32 rc = 0;
if (!address || !length)
return NV_RS_STATUS_INVALID_ARGUMENT;
mutex_lock(&nv_rs_rmapi_alloc_lock);
alloc = nv_rs_rmapi_alloc_find(token);
if (!alloc) {
rc = NV_RS_STATUS_INVALID_ARGUMENT;
} else {
total = alloc->count << PAGE_SHIFT;
if (offset > total || length > total - offset) {
rc = NV_RS_STATUS_INVALID_ARGUMENT;
} else {
rc = nv_rs_rmapi_alloc_ensure_kernel_locked(alloc);
if (!rc)
*address = (u64)(uintptr_t)((u8 *)alloc->kernel + offset);
}
}
mutex_unlock(&nv_rs_rmapi_alloc_lock);
return rc;
}
/* Kernel-mode NvRmMapMemory (NVOS33) for BAR0 register windows (e.g. DispSfUser
* and NvDisplay Core/Window/Cursor channels mapped by stock nvidia-modeset.ko). */
u32 nv_rs_rmapi_os_kernel_map_register(u32 gpu_id, u64 offset, u64 length, u64 *address)
{
struct pci_dev *pdev;
resource_size_t bar0_start, bar0_len;
void __iomem *va;
u32 rc = 0;
if (!address || !length)
return NV_RS_STATUS_INVALID_ARGUMENT;
pdev = nv_rs_rmapi_gpu_pci_get(gpu_id);
if (!pdev)
return NV_RS_STATUS_OBJECT_NOT_FOUND;
bar0_start = pci_resource_start(pdev, 0);
bar0_len = pci_resource_len(pdev, 0);
if (!bar0_start || offset > (u64)bar0_len || length > (u64)bar0_len - offset) {
rc = NV_RS_STATUS_INVALID_ARGUMENT;
goto out_put;
}
va = ioremap(bar0_start + offset, length);
if (!va) {
rc = NV_RS_STATUS_NO_MEMORY;
goto out_put;
}
*address = (u64)(uintptr_t)va;
out_put:
pci_dev_put(pdev);
return rc;
}
/* Kernel-mode NvRmMapMemory (NVOS33) for BAR1 video memory (ioremap_wc). */
u32 nv_rs_rmapi_os_kernel_map_video(u32 gpu_id, u64 offset, u64 length, u64 *address)
{
struct pci_dev *pdev;
resource_size_t bar1_start, bar1_len;
void __iomem *va;
u32 rc = 0;
if (!address || !length)
return NV_RS_STATUS_INVALID_ARGUMENT;
pdev = nv_rs_rmapi_gpu_pci_get(gpu_id);
if (!pdev)
return NV_RS_STATUS_OBJECT_NOT_FOUND;
bar1_start = pci_resource_start(pdev, 1);
bar1_len = pci_resource_len(pdev, 1);
if (!bar1_start || offset > (u64)bar1_len || length > (u64)bar1_len - offset) {
rc = NV_RS_STATUS_INVALID_ARGUMENT;
goto out_put;
}
va = ioremap_wc(bar1_start + offset, length);
if (!va) {
rc = NV_RS_STATUS_NO_MEMORY;
goto out_put;
}
*address = (u64)(uintptr_t)va;
out_put:
pci_dev_put(pdev);
return rc;
}
u32 nv_rs_rmapi_os_kernel_video_phys(u32 gpu_id, u64 offset, u64 length, u64 *phys_out)
{
struct pci_dev *pdev;
resource_size_t bar1_start, bar1_len;
u32 rc = 0;
if (!phys_out || !length)
return NV_RS_STATUS_INVALID_ARGUMENT;
pdev = nv_rs_rmapi_gpu_pci_get(gpu_id);
if (!pdev)
return NV_RS_STATUS_OBJECT_NOT_FOUND;
bar1_start = pci_resource_start(pdev, 1);
bar1_len = pci_resource_len(pdev, 1);
if (!bar1_start || offset > (u64)bar1_len || length > (u64)bar1_len - offset) {
rc = NV_RS_STATUS_INVALID_ARGUMENT;
goto out_put;
}
*phys_out = (u64)bar1_start + offset;
out_put:
pci_dev_put(pdev);
return rc;
}
u32 nv_rs_rmapi_os_kernel_read_u64(u64 token, u64 offset, u64 *val_out)
{
struct nv_rs_rmapi_alloc *alloc;
u64 total;
u32 rc = 0;
if (!val_out || (offset & 7))
return NV_RS_STATUS_INVALID_ARGUMENT;
mutex_lock(&nv_rs_rmapi_alloc_lock);
alloc = nv_rs_rmapi_alloc_find(token);
if (!alloc) {
rc = NV_RS_STATUS_INVALID_ARGUMENT;
} else {
total = alloc->count << PAGE_SHIFT;
if (offset > total || 8 > total - offset) {
rc = NV_RS_STATUS_INVALID_ARGUMENT;
} else {
rc = nv_rs_rmapi_alloc_ensure_kernel_locked(alloc);
if (!rc)
*val_out = READ_ONCE(*(volatile u64 *)((u8 *)alloc->kernel + offset));
}
}
mutex_unlock(&nv_rs_rmapi_alloc_lock);
return rc;
}
void nv_rs_rmapi_os_kernel_unmap_io(u64 address)
{
if (address)
iounmap((void __iomem *)(uintptr_t)address);
}
/* Mark dead before releasing the fault lock, but keep the cookie and block
* reserved until the zap completes. The revoke mutex pins the context against
* file release and excludes parallel zaps. Entry and exit hold USERD lock. */
static void nv_rs_rmapi_revoke_userd_locked(struct nv_rs_rmapi_file *context)
{
struct file *control = context->userd_control;
loff_t start = (loff_t)context->userd_pgoff << PAGE_SHIFT;
context->userd_map_refs = 0;
mutex_unlock(&nv_rs_rmapi_userd_lock);
unmap_mapping_range(context->file->f_mapping, start, PAGE_SIZE, 1);
mutex_lock(&nv_rs_rmapi_userd_lock);
mutex_lock(&nv_rs_rmapi_alloc_lock);
nv_rs_file_map_remove(context->owner); /* USERD entries are IO-only. */
mutex_unlock(&nv_rs_rmapi_alloc_lock);
list_del_init(&context->userd_link);
context->userd_pgoff = 0;
context->userd_control = NULL;
fput(control);
}
void nv_rs_rmapi_os_unmap_pascal_userd(u64 cookie)
{
struct nv_rs_rmapi_file *context;
mutex_lock(&nv_rs_rmapi_userd_revoke_lock);
mutex_lock(&nv_rs_rmapi_userd_lock);
list_for_each_entry(context, &nv_rs_rmapi_userd_files, userd_link) {
if (context->userd_pgoff == cookie) {
if (--context->userd_map_refs == 0)
nv_rs_rmapi_revoke_userd_locked(context);
break;
}
}
mutex_unlock(&nv_rs_rmapi_userd_lock);
mutex_unlock(&nv_rs_rmapi_userd_revoke_lock);
}
static void nv_rs_rmapi_revoke_gpu_userd(int minor, u32 generation)
{
struct nv_rs_rmapi_file *context, *next;
mutex_lock(&nv_rs_rmapi_userd_revoke_lock);
mutex_lock(&nv_rs_rmapi_userd_lock);
list_for_each_entry_safe(context, next, &nv_rs_rmapi_userd_files, userd_link) {
if (context->gpu == minor && context->generation == generation)
nv_rs_rmapi_revoke_userd_locked(context);
}
mutex_unlock(&nv_rs_rmapi_userd_lock);
mutex_unlock(&nv_rs_rmapi_userd_revoke_lock);
}
/* Runtime stop can leave the PCI node registered. Close admission before
* dropping the fault lock for any zaps, including on the lost PM path. */
void nv_rs_rmapi_revoke_runtime_userd(u32 gpu_id, bool pm_lost)
{
struct nv_rs_rmapi_file *context, *next;
unsigned long flags;
int i;
mutex_lock(&nv_rs_rmapi_userd_revoke_lock);
mutex_lock(&nv_rs_rmapi_userd_lock);
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
for (i = 0; i < NV_RS_RMAPI_MAX_GPUS; i++) {
struct nv_rs_rmapi_gpu_node *node = &nv_rs_rmapi_gpu_nodes[i];
if (node->live && node->gpu_id == gpu_id) {
node->userd_runtime_live = false;
node->userd_pm_lost |= pm_lost;
}
}
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
list_for_each_entry_safe(context, next, &nv_rs_rmapi_userd_files, userd_link) {
if (context->userd_gpu_id == gpu_id)
nv_rs_rmapi_revoke_userd_locked(context);
}
mutex_unlock(&nv_rs_rmapi_userd_lock);
mutex_unlock(&nv_rs_rmapi_userd_revoke_lock);
}
/* Only a successful runtime activation opens admission. PM resume clears the
* lost latch after BAR0 verification, but does not publish an old runtime. */
void nv_rs_rmapi_runtime_userd_ready(u32 gpu_id, bool verified_pm_resume)
{
unsigned long flags;
int i;
mutex_lock(&nv_rs_rmapi_userd_revoke_lock);
mutex_lock(&nv_rs_rmapi_userd_lock);
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
for (i = 0; i < NV_RS_RMAPI_MAX_GPUS; i++) {
struct nv_rs_rmapi_gpu_node *node = &nv_rs_rmapi_gpu_nodes[i];
if (!node->live || node->gpu_id != gpu_id || !node->pascal_userd_gpu)
continue;
if (verified_pm_resume)
node->userd_pm_lost = false;
else if (!node->userd_pm_lost)
node->userd_runtime_live = true;
}
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
mutex_unlock(&nv_rs_rmapi_userd_lock);
mutex_unlock(&nv_rs_rmapi_userd_revoke_lock);
}
/* Returns the init-namespace TGID (stable across PID namespaces) for TSG nice tracking. */
u32 nv_rs_current_tgid(void);
u32 nv_rs_current_tgid(void)
{
return (u32)task_tgid_nr(current);
}
/* Returns the group leader's monotonic boot start time for PID-reuse detection. */
u64 nv_rs_current_start_time(void);
u64 nv_rs_current_start_time(void)
{
u64 start_time = 0;
rcu_read_lock();
if (!nv_rs_sample_tg_meta_rcu(nv_rs_current_tg_leader_rcu(), &start_time, NULL, NULL,
NULL, NULL, 0, NULL))
start_time = nv_rs_current_tg_leader_rcu()->start_boottime;
rcu_read_unlock();
return start_time;
}
bool nv_rs_os_capable_nice(void);
bool nv_rs_os_capable_nice(void)
{
return capable(CAP_SYS_NICE);
}
bool nv_rs_current_has_desktop_cap(void);
bool nv_rs_current_has_desktop_cap(void)
{
bool has_cap = false;
rcu_read_lock();
if (!nv_rs_sample_tg_meta_rcu(nv_rs_current_tg_leader_rcu(), NULL, NULL, NULL, NULL,
NULL, 0, &has_cap)) {
const struct cred *cred = __task_cred(current);
has_cap = cred && cred->user_ns == &init_user_ns &&
(cap_raised(cred->cap_effective, CAP_SYS_NICE) ||
cap_raised(cred->cap_effective, CAP_SYS_ADMIN));
}
rcu_read_unlock();
return has_cap;
}
int nv_rs_current_nice(void);
int nv_rs_current_nice(void)
{
s32 nice = 0;
rcu_read_lock();
if (!nv_rs_sample_tg_meta_rcu(nv_rs_current_tg_leader_rcu(), NULL, &nice, NULL, NULL,
NULL, 0, NULL))
nice = task_nice(current);
rcu_read_unlock();
return (int)nice;
}
u32 nv_rs_current_uid(void);
u32 nv_rs_current_uid(void)
{
u32 uid = (u32)-1;
rcu_read_lock();
if (!nv_rs_sample_tg_meta_rcu(nv_rs_current_tg_leader_rcu(), NULL, NULL, &uid, NULL,
NULL, 0, NULL)) {
const struct cred *cred = __task_cred(current);
uid = cred ? from_kuid_munged(&init_user_ns, cred->uid) : (u32)-1;
}
rcu_read_unlock();
return uid;
}
void nv_rs_current_comm(u8 *out, size_t len);
void nv_rs_current_comm(u8 *out, size_t len)
{
if (!out || !len)
return;
memset(out, 0, len);
rcu_read_lock();
if (!nv_rs_sample_tg_meta_rcu(nv_rs_current_tg_leader_rcu(), NULL, NULL, NULL, NULL,
out, len, NULL)) {
size_t n = min_t(size_t, len - 1, TASK_COMM_LEN - 1);
task_lock(current);
memcpy(out, current->comm, n);
task_unlock(current);
out[n] = '\0';
}
rcu_read_unlock();
}
/* The release of GPU-cacheable system memory. The original writes 1 to the BAR0
* registers 0x70000, 0x70010 and 0x70004 and polls each; that needs the GPU's register
* mapping, which these nodes do not have. Counted, nothing else. */
void nv_rs_rmapi_os_flush_gpu_cache(void)
{
nv_rs_rmapi_gpu_cache_flushes++;
}
/* Resolves a POSIX fd belonging to the calling process to the `owner` token of the
* `/dev/nvidiactl` file it refers to, or 0 if invalid or not a control node file.
* Caller holds nv_rs_rmapi_lock, preventing concurrent release of that owner. */
u64 nv_rs_rmapi_os_ctl_fd_owner(s32 descriptor);
u64 nv_rs_rmapi_os_ctl_fd_owner(s32 descriptor)
{
struct file *target;
struct nv_rs_rmapi_file *context;
u64 owner = 0;
if (descriptor < 0)
return 0;
target = fget(descriptor);
if (target) {
context = target->private_data;
if (target->f_op == &nv_rs_rmapi_operations && context && context->gpu < 0)
owner = context->owner;
fput(target);
}
return owner;
}
static int nv_rs_rmapi_open(struct inode *inode, struct file *file)
{
struct nv_rs_rmapi_file *context = nv_rs_rmapi_context(file, -1);
if (!context)
return -ENOMEM;
file->private_data = context;
return nonseekable_open(inode, file);
}
/* The registers the original's attach and copy-engine load read for the controls this node
* answers (the Rust side lists them: the fuse and Jtag status words and the eleven PCE-LCE
* mapping words of the copy engines). Read once per GPU, at the first
* open of its device node, through the reader the PCI driver registered. Nothing is
* written. A failed or missing read leaves the dependent control unavailable. Caller
* holds nv_rs_rmapi_lock, which also keeps the GPU from being removed meanwhile. */
static void nv_rs_rmapi_read_attach_registers(struct nv_rs_rmapi_gpu_node *node, int gpu)
{
u32 values[NV_RS_RMAPI_ATTACH_REGISTERS];
u32 count = nv_rs_rmapi_attach_register_count(), index;
if (!node->read32 || count > NV_RS_RMAPI_ATTACH_REGISTERS ||
!nv_rs_rmapi_gpu_needs_registers(nv_rs_rmapi_state, gpu))
return;
for (index = 0; index < count; index++) {
if (node->read32(node->cookie, nv_rs_rmapi_attach_register(index), &values[index]))
return;
}
nv_rs_rmapi_gpu_attach_registers(nv_rs_rmapi_state, gpu, values, count);
}
/* Device node. The open succeeds without engine initialization and attaches the GPU: it is
* then listed as attached and device objects can be made on it, but only the controls that
* need no engine state answer (see the implementation notes). The original runs the whole
* adapter initialization here and fails the open without it. */
static int nv_rs_rmapi_gpu_open_file(struct inode *inode, struct file *file)
{
struct nv_rs_rmapi_gpu_node *node;
int gpu;
struct nv_rs_rmapi_file *context;
struct nv_rs_gpu_owner *owner = NULL;
int result;
if (imajor(inode) == NV_RS_COMPAT_MAJOR) {
gpu = iminor(inode);
if (gpu < 0 || gpu >= NV_RS_RMAPI_MAX_GPUS)
return -ENODEV;
node = &nv_rs_rmapi_gpu_nodes[gpu];
} else {
/* misc_open left the miscdevice in private_data. */
node = container_of(file->private_data, struct nv_rs_rmapi_gpu_node, misc);
gpu = (int)(node - nv_rs_rmapi_gpu_nodes);
}
context = nv_rs_rmapi_context(file, gpu);
if (!context)
return -ENOMEM;
mutex_lock(&nv_rs_rmapi_lock);
if (node->live && node->owner) {
owner = node->owner;
atomic_inc(&node->runtime_start_users);
}
mutex_unlock(&nv_rs_rmapi_lock);
if (owner && nv_rs_runtime_engines()) {
result = nv_rs_gpu_owner_runtime_start(owner);
if (atomic_dec_and_test(&node->runtime_start_users))
wake_up_all(&nv_rs_rmapi_owner_wq);
if (result) {
kfree(context);
return result;
}
} else if (owner) {
if (atomic_dec_and_test(&node->runtime_start_users))
wake_up_all(&nv_rs_rmapi_owner_wq);
}
mutex_lock(&nv_rs_rmapi_lock);
result = node->live ? nv_rs_rmapi_gpu_open(nv_rs_rmapi_state, gpu) : -ENODEV;
context->generation = node->generation;
if (!result)
nv_rs_rmapi_read_attach_registers(node, gpu);
mutex_unlock(&nv_rs_rmapi_lock);
if (result) {
kfree(context);
return result;
}
file->private_data = context;
return nonseekable_open(inode, file);
}
static void nv_rs_rmapi_plat_io_release_file(struct file *file);
static int nv_rs_rmapi_release(struct inode *inode, struct file *file)
{
struct nv_rs_rmapi_file *context = file->private_data;
struct nv_rs_file_map_record removed;
bool had_map;
(void)inode;
mutex_lock(&nv_rs_rmapi_lock);
nv_rs_rmapi_close(nv_rs_rmapi_state, context->owner);
if (context->gpu >= 0 &&
nv_rs_gpu_slot_is_live_gen((u32)context->gpu, context->generation))
nv_rs_rmapi_gpu_release(nv_rs_rmapi_state, context->gpu);
/* The final file reference implies no VMA, but a revoker may still be zapping. */
mutex_lock(&nv_rs_rmapi_userd_revoke_lock);
mutex_lock(&nv_rs_rmapi_userd_lock);
list_del_init(&context->userd_link);
mutex_unlock(&nv_rs_rmapi_userd_lock);
mutex_unlock(&nv_rs_rmapi_userd_revoke_lock);
mutex_lock(&nv_rs_rmapi_alloc_lock);
had_map = nv_rs_file_map_take(context->owner, &removed);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (had_map && removed.alloc_ptr) {
if (removed.is_io)
kvfree(removed.alloc_ptr);
else
nv_rs_rmapi_alloc_put(removed.alloc_ptr);
}
mutex_unlock(&nv_rs_rmapi_lock);
nv_rs_rmapi_plat_io_release_file(file);
if (context->control)
fput(context->control);
if (context->userd_control)
fput(context->userd_control);
kfree(context);
/* Return pooled system pages to the OS after client teardown (both control-fd
* and per-GPU device-fd closes run through here), outside nv_rs_rmapi_lock. */
nv_rs_rmapi_trim_page_pools_on_client_close();
return 0;
}
/* nv_is_gpu_accessible of the original's open layer: the device nodes the calling process
* holds open. Runs under the files lock (no sleeping), so it only collects the files'
* (minor, generation) pairs; nv_rs_rmapi_gpu_access checks them under the node lock. */
struct nv_rs_rmapi_access { u32 seen; unsigned int generation[NV_RS_RMAPI_MAX_GPUS]; };
static int nv_rs_rmapi_match_gpu(const void *cookie, struct file *file, unsigned int fd)
{
struct nv_rs_rmapi_access *access = (struct nv_rs_rmapi_access *)cookie;
(void)fd;
if (file->f_op == &nv_rs_rmapi_gpu_operations) {
struct nv_rs_rmapi_file *context = file->private_data;
/* private_data still holds the miscdevice while the open is in progress. */
if (context && context->owner == (u64)(unsigned long)context &&
!(access->seen & (1u << context->gpu))) {
access->seen |= 1u << context->gpu;
access->generation[context->gpu] = context->generation;
}
}
return 0;
}
/* Mask of the minor numbers of live device nodes the calling process holds open. Call with
* nv_rs_rmapi_lock held. */
static u32 nv_rs_rmapi_gpu_access(const struct nv_rs_rmapi_access *access)
{
u32 mask = 0;
int gpu;
for (gpu = 0; gpu < NV_RS_RMAPI_MAX_GPUS; gpu++)
if ((access->seen & (1u << gpu)) &&
nv_rs_gpu_slot_is_live_gen((u32)gpu, access->generation[gpu]))
mask |= 1u << gpu;
return mask;
}
/* NV_ESC_REGISTER_FD: associates a control file with the calling file. */
static int nv_rs_rmapi_register(struct file *file, const u8 *top, size_t size)
{
struct nv_rs_rmapi_file *context = file->private_data, *target_context = NULL;
struct file *target;
s32 fd;
u32 status;
if (size != sizeof(fd))
return -EINVAL;
memcpy(&fd, top, sizeof(fd));
target = fget(fd);
if (target && target->f_op == &nv_rs_rmapi_operations)
target_context = target->private_data;
mutex_lock(&nv_rs_rmapi_lock);
mutex_lock(&nv_rs_rmapi_userd_lock);
status = nv_rs_rmapi_register_fd(context->control != NULL ||
(context->userd_control && context->userd_control != target),
target_context != NULL,
target_context && target_context->control != NULL,
target == file);
mutex_unlock(&nv_rs_rmapi_userd_lock);
if (!status) {
context->control = target;
target = NULL;
}
mutex_unlock(&nv_rs_rmapi_lock);
if (target)
fput(target);
/* rm_ioctl's non-zero result becomes -EINVAL; the block goes back unchanged. */
return status ? -EINVAL : 0;
}
/* NV_ESC_QUERY_DEVICE_INTR (0xd5): 8-byte { u32 intrStatus; u32 status; } — device node only. */
static int nv_rs_rmapi_query_device_intr(struct file *file, u8 *top, size_t size)
{
struct nv_rs_rmapi_file *context = file->private_data;
u32 intr = 0, status = 0;
if (context->gpu < 0 || size != 8)
return -EINVAL;
mutex_lock(&nv_rs_rmapi_lock);
if (context->gpu < NV_RS_RMAPI_MAX_GPUS) {
struct nv_rs_rmapi_gpu_node *node = &nv_rs_rmapi_gpu_nodes[context->gpu];
if (node->live && node->read32)
(void)node->read32(node->cookie, 0x100, &intr);
}
mutex_unlock(&nv_rs_rmapi_lock);
memcpy(top, &intr, sizeof(intr));
memcpy(top + 4, &status, sizeof(status));
return 0;
}
/* NV_ESC_SET_NUMA_STATUS (0xd8): 4-byte { s32 status; } — device node only. */
static int nv_rs_rmapi_set_numa_status(struct file *file, const u8 *top, size_t size)
{
struct nv_rs_rmapi_file *context = file->private_data;
s32 st = 0;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (context->gpu < 0 || size != 4)
return -EINVAL;
memcpy(&st, top, sizeof(st));
if (st < 0 || st > 5)
return -EINVAL;
mutex_lock(&nv_rs_rmapi_lock);
if (context->gpu >= 0 && context->gpu < NV_RS_RMAPI_MAX_GPUS)
(void)nv_rs_gpu_slot_set_numa((u32)context->gpu, st);
mutex_unlock(&nv_rs_rmapi_lock);
return 0;
}
/* NV_ESC_EXPORT_TO_DMABUF_FD (0xd9): stock-ABI dma-buf export backed by BAR1 P2PDMA.
* Layout verified against stock 580.178.04 nv_ioctl_export_to_dma_buf_fd_t (2608 bytes):
* off 0: s32 fd (IN/OUT: OUT when index==0, IN when index>0)
* off 4: u32 hClient (IN)
* off 8: u32 totalObjects (IN)
* off 12: u32 numObjects (IN, 1..=128)
* off 16: u32 index (IN, starting object index for batched >128 exports)
* off 24: u64 totalSize (IN)
* off 32: u8 mappingType (IN: 0=DEFAULT, 1=FORCE_PCIE)
* off 33: u8 bAllowMmap (IN)
* off 36: u32 handles[128] (IN)
* off 552: u64 offsets[128] (IN)
* off 1576: u64 sizes[128] (IN)
* off 2600: u32 status (OUT) */
static u32 nv_rs_errno_to_nv_status(int err)
{
if (err == -ENOMEM)
return 0x00000051u; /* NV_ERR_NO_MEMORY */
if (err == -EPERM || err == -EACCES)
return 0x0000001bu; /* NV_ERR_INSUFFICIENT_PERMISSIONS */
if (err == -ENODEV)
return 0x00000040u; /* NV_ERR_INVALID_STATE */
if (err == -EOPNOTSUPP)
return 0x00000056u; /* NV_ERR_NOT_SUPPORTED */
return 0x0000001fu; /* NV_ERR_INVALID_ARGUMENT */
}
void nv_rs_dmabuf_unpin_pins_locked(const struct nv_rs_dmabuf_pin *pins, u32 num_pins)
{
u32 i;
lockdep_assert_held(&nv_rs_rmapi_lock);
if (!nv_rs_rmapi_state || !pins)
return;
for (i = 0; i < num_pins; i++)
nv_rs_rmapi_dmabuf_unpin(nv_rs_rmapi_state, &pins[i]);
}
void nv_rs_dmabuf_unpin_pins(const struct nv_rs_dmabuf_pin *pins, u32 num_pins)
{
mutex_lock(&nv_rs_rmapi_lock);
nv_rs_dmabuf_unpin_pins_locked(pins, num_pins);
mutex_unlock(&nv_rs_rmapi_lock);
}
/* The growing list of BAR1 extents one export resolves to. */
struct nv_rs_dmabuf_extents {
struct nv_rs_dmabuf_extent *ext;
u32 count;
u32 cap;
struct nv_rs_dmabuf_range *scratch;
u32 scratch_cap;
};
static int nv_rs_dmabuf_extents_reserve(struct nv_rs_dmabuf_extents *e, u32 more)
{
struct nv_rs_dmabuf_extent *grown;
u32 cap;
if (more > NV_RS_DMABUF_MAX_EXTENTS - e->count)
return -E2BIG;
if (e->count + more <= e->cap)
return 0;
cap = min_t(u32, max_t(u32, e->count + more, e->cap * 2), NV_RS_DMABUF_MAX_EXTENTS);
grown = kvmalloc_array(cap, sizeof(*grown), GFP_KERNEL);
if (!grown)
return -ENOMEM;
if (e->count)
memcpy(grown, e->ext, (size_t)e->count * sizeof(*grown));
kvfree(e->ext);
e->ext = grown;
e->cap = cap;
return 0;
}
static void nv_rs_dmabuf_extents_free(struct nv_rs_dmabuf_extents *e)
{
kvfree(e->ext);
kvfree(e->scratch);
}
/* Resolve and pin one (h_client, h_memory, offset, size) entry and append its BAR1 extents. With
* nv_rs_rmapi_lock held. *pdev is the GPU of the earlier entries (NULL for the first): an entry
* on another GPU is refused. Returns the NV_STATUS; on success *pin holds the pin, on failure
* nothing is pinned. */
static u32 nv_rs_dmabuf_resolve_one(u64 owner, u64 control_owner, bool admin, u32 h_client,
u32 h_memory, u64 offset, u64 size,
struct nv_rs_dmabuf_extents *e, struct pci_dev **pdev,
struct nv_rs_dmabuf_resolved *res,
struct nv_rs_dmabuf_pin *pin)
{
resource_size_t bar1_start, bar1_len;
struct pci_dev *gpu_pdev;
u32 st, i;
lockdep_assert_held(&nv_rs_rmapi_lock);
for (;;) {
memset(res, 0, sizeof(*res));
st = nv_rs_rmapi_resolve_dmabuf_object(nv_rs_rmapi_state, owner, control_owner, admin,
h_client, h_memory, offset, size, res,
e->scratch, e->scratch_cap, pin);
if (st != 0x00000002u) /* NV_ERR_BUFFER_TOO_SMALL: a non-contiguous allocation */
break;
if (res->num_ranges <= e->scratch_cap || res->num_ranges > NV_RS_DMABUF_MAX_EXTENTS)
return 0x00000056u; /* NV_ERR_NOT_SUPPORTED */
kvfree(e->scratch);
e->scratch_cap = 0;
e->scratch = kvmalloc_array(res->num_ranges, sizeof(*e->scratch), GFP_KERNEL);
if (!e->scratch)
return 0x00000051u; /* NV_ERR_NO_MEMORY */
e->scratch_cap = res->num_ranges;
}
if (st != 0)
return st;
/* pinned from here: undo on every failure */
st = 0x00000040u; /* NV_ERR_INVALID_STATE */
if (res->gpu_minor >= NV_RS_RMAPI_MAX_GPUS || !nv_rs_rmapi_gpu_nodes[res->gpu_minor].live ||
!nv_rs_rmapi_gpu_nodes[res->gpu_minor].pdev)
goto unpin;
st = 0x00000056u; /* NV_ERR_NOT_SUPPORTED: BAR1 may be reprogrammed under the export */
if (nv_rs_rmapi_gpu_nodes[res->gpu_minor].pascal_userd_gpu && nv_rs_runtime_engines())
goto unpin;
gpu_pdev = nv_rs_rmapi_gpu_nodes[res->gpu_minor].pdev;
st = 0x0000001fu; /* NV_ERR_INVALID_ARGUMENT: cross-GPU mix */
if (*pdev && *pdev != gpu_pdev)
goto unpin;
bar1_start = pci_resource_start(gpu_pdev, 1);
bar1_len = pci_resource_len(gpu_pdev, 1);
st = 0x00000056u; /* NV_ERR_NOT_SUPPORTED: outside the BAR1 aperture */
if (!bar1_start || res->num_ranges == 0 || res->num_ranges > e->scratch_cap)
goto unpin;
for (i = 0; i < res->num_ranges; i++) {
const struct nv_rs_dmabuf_range *r = &e->scratch[i];
if (r->bar1_offset >= (u64)bar1_len || r->size > (u64)bar1_len - r->bar1_offset)
goto unpin;
}
st = 0x00000051u; /* NV_ERR_NO_MEMORY */
if (nv_rs_dmabuf_extents_reserve(e, res->num_ranges))
goto unpin;
for (i = 0; i < res->num_ranges; i++) {
e->ext[e->count].bar1_phys = bar1_start + (resource_size_t)e->scratch[i].bar1_offset;
e->ext[e->count].size = e->scratch[i].size;
e->count++;
}
*pdev = gpu_pdev;
return 0;
unpin:
nv_rs_rmapi_dmabuf_unpin(nv_rs_rmapi_state, pin);
return st;
}
/* nvidia_rs dma-buf export of one RM video-memory object range, for callers that found the object
* themselves (uvm_node.c: by the CUDA GPU virtual address, through the UVM external mapping). It is
* the single-object case of NV_ESC_EXPORT_TO_DMABUF_FD below, authorized the same way: the
* memory's client must belong to the RM file the caller passes as rm_fd (or to that file's control
* file), or the caller is CAP_SYS_ADMIN. A UVM mapping of the memory is not enough on its own.
* Takes nv_rs_rmapi_lock itself (the caller must not hold it). Returns the fd reserved in
* `pending` (the caller publishes it once its reply is copied out), or a negative errno with
* *status_out set to the NV_STATUS. */
int nv_rs_rmapi_export_dmabuf_object(int rm_fd, u32 h_client, u32 h_memory, u64 offset, u64 size,
bool allow_mmap, u32 *status_out,
struct nv_rs_dmabuf_pending *pending);
int nv_rs_rmapi_export_dmabuf_object(int rm_fd, u32 h_client, u32 h_memory, u64 offset, u64 size,
bool allow_mmap, u32 *status_out,
struct nv_rs_dmabuf_pending *pending)
{
struct nv_rs_dmabuf_extents e = { 0 };
struct nv_rs_dmabuf_resolved res;
struct nv_rs_dmabuf_pin pin;
struct nv_rs_rmapi_file *context;
struct pci_dev *pdev = NULL;
struct dma_buf *dmabuf = NULL;
struct file *rm_file;
bool admin = capable(CAP_SYS_ADMIN);
u64 owner, control_owner = 0;
u32 st;
int fd;
*status_out = 0x0000001fu; /* NV_ERR_INVALID_ARGUMENT */
if (!size || ((offset | size) & (PAGE_SIZE - 1)))
return -EINVAL;
rm_file = fget(rm_fd);
if (!rm_file)
return -EBADF;
if (rm_file->f_op != &nv_rs_rmapi_operations && rm_file->f_op != &nv_rs_rmapi_gpu_operations) {
fput(rm_file);
return -EINVAL;
}
context = rm_file->private_data;
if (mutex_lock_interruptible(&nv_rs_rmapi_lock)) {
fput(rm_file);
return -ERESTARTSYS;
}
owner = context->owner;
if (context->control)
control_owner = ((struct nv_rs_rmapi_file *)context->control->private_data)->owner;
st = nv_rs_dmabuf_resolve_one(owner, control_owner, admin, h_client, h_memory, offset, size,
&e, &pdev, &res, &pin);
if (st == 0) {
dmabuf = nv_rs_dmabuf_export_create(pdev, res.client_owner, h_client, res.gpu_id, 1,
size, allow_mmap, e.ext, e.count, &pin, 1);
if (IS_ERR(dmabuf)) {
st = nv_rs_errno_to_nv_status(PTR_ERR(dmabuf));
dmabuf = NULL;
nv_rs_dmabuf_unpin_pins_locked(&pin, 1);
}
}
mutex_unlock(&nv_rs_rmapi_lock);
fput(rm_file);
nv_rs_dmabuf_extents_free(&e);
if (st != 0) {
*status_out = st;
return -EINVAL;
}
fd = nv_rs_dmabuf_reserve_fd(pending, dmabuf);
*status_out = fd >= 0 ? 0 : nv_rs_errno_to_nv_status(fd);
return fd;
}
/* The fd of a new dma-buf is only reserved here, in `pending`: the ioctl installs it once the
* reply has been copied out. */
static int nv_rs_rmapi_export_dmabuf(struct file *file, u8 *top, size_t size,
struct nv_rs_dmabuf_pending *pending)
{
struct nv_rs_rmapi_file *context = file->private_data;
struct pci_dev *pdev = NULL;
struct nv_rs_dmabuf_extents ext = { 0 };
struct nv_rs_dmabuf_pin *pins = NULL;
struct dma_buf *new_buf = NULL;
s32 in_fd = -1, out_fd = -1;
u32 h_client = 0, total_objects = 0, num_objects = 0, index = 0, num_pins = 0;
u64 total_size = 0;
u8 mapping_type = 0, allow_mmap = 0;
u32 status = 0x0000001fu; /* NV_ERR_INVALID_ARGUMENT */
u32 gpu_id = 0, i;
u64 client_owner = 0, control_owner = 0;
bool admin = capable(CAP_SYS_ADMIN);
if (size != NV_RS_DMABUF_EXPORT_IOCTL_SIZE)
return -EINVAL;
memcpy(&in_fd, top + 0, sizeof(in_fd));
memcpy(&h_client, top + 4, sizeof(h_client));
memcpy(&total_objects, top + 8, sizeof(total_objects));
memcpy(&num_objects, top + 12, sizeof(num_objects));
memcpy(&index, top + 16, sizeof(index));
memcpy(&total_size, top + 24, sizeof(total_size));
mapping_type = top[32];
allow_mmap = top[33];
/* Backwards-compatible raw BAR1 diagnostic export (root-only, no RM handles). */
if (h_client == 0 && total_objects == 0 && num_objects == 0) {
u64 offset0 = 0, size0 = 0, export_size;
int gpu;
if (!admin)
return -EPERM;
memcpy(&offset0, top + 552, sizeof(offset0));
memcpy(&size0, top + 1576, sizeof(size0));
export_size = size0 ? size0 : total_size;
mutex_lock(&nv_rs_rmapi_lock);
gpu = context->gpu;
if (gpu >= 0 && gpu < NV_RS_RMAPI_MAX_GPUS && nv_rs_rmapi_gpu_nodes[gpu].live) {
pdev = nv_rs_rmapi_gpu_nodes[gpu].pdev;
} else {
for (gpu = 0; gpu < NV_RS_RMAPI_MAX_GPUS; gpu++) {
if (nv_rs_rmapi_gpu_nodes[gpu].live && nv_rs_rmapi_gpu_nodes[gpu].pdev) {
pdev = nv_rs_rmapi_gpu_nodes[gpu].pdev;
break;
}
}
}
/* A raw export could outlive a reprogramming of the aperture. */
if (pdev && nv_rs_rmapi_gpu_nodes[gpu].pascal_userd_gpu && nv_rs_runtime_engines())
pdev = NULL;
if (pdev)
pci_dev_get(pdev);
mutex_unlock(&nv_rs_rmapi_lock);
if (pdev && export_size > 0) {
struct dma_buf *raw = nv_rs_dmabuf_export_bar1(pdev, offset0, export_size);
int res = IS_ERR(raw) ? PTR_ERR(raw) : nv_rs_dmabuf_reserve_fd(pending, raw);
if (res >= 0) {
out_fd = res;
status = 0;
} else {
status = nv_rs_errno_to_nv_status(res);
}
}
if (pdev)
pci_dev_put(pdev);
goto reply;
}
if (mapping_type > 1) {
status = 0x00000056u; /* NV_ERR_NOT_SUPPORTED (e.g. FORCE_C2C on PCIe) */
goto reply;
}
if (total_objects == 0 || total_objects > NV_RS_DMABUF_MAX_OBJECTS ||
num_objects == 0 || num_objects > 128u ||
index > total_objects || num_objects > total_objects - index ||
total_size == 0 || (total_size & (PAGE_SIZE - 1))) {
status = 0x0000001fu; /* NV_ERR_INVALID_ARGUMENT */
goto reply;
}
pins = kcalloc(num_objects, sizeof(*pins), GFP_KERNEL);
if (!pins) {
status = 0x00000051u; /* NV_ERR_NO_MEMORY */
goto reply;
}
if (mutex_lock_interruptible(&nv_rs_rmapi_lock)) {
kfree(pins);
return -ERESTARTSYS;
}
if (context->control)
control_owner = ((struct nv_rs_rmapi_file *)context->control->private_data)->owner;
status = 0;
for (i = 0; i < num_objects; i++) {
struct nv_rs_dmabuf_resolved res;
u32 h_mem = 0;
u64 off_i = 0, size_i = 0;
memcpy(&h_mem, top + 36 + (size_t)i * 4, sizeof(h_mem));
memcpy(&off_i, top + 552 + (size_t)i * 8, sizeof(off_i));
memcpy(&size_i, top + 1576 + (size_t)i * 8, sizeof(size_i));
status = nv_rs_dmabuf_resolve_one(context->owner, control_owner, admin, h_client, h_mem,
off_i, size_i, &ext, &pdev, &res, &pins[num_pins]);
if (status != 0)
break;
num_pins++;
if (num_pins == 1) {
gpu_id = res.gpu_id;
client_owner = res.client_owner;
} else if (res.gpu_id != gpu_id) {
status = 0x0000001fu; /* NV_ERR_INVALID_ARGUMENT: cross-GPU mix */
break;
}
}
/* Create (or extend) the dma-buf in the critical section that took the pins; it owns them
* from then on. A failure drops them again. */
if (status == 0 && pdev) {
if (index == 0) {
new_buf = nv_rs_dmabuf_export_create(pdev, client_owner, h_client, gpu_id,
total_objects, total_size, allow_mmap != 0,
ext.ext, ext.count, pins, num_pins);
if (IS_ERR(new_buf)) {
status = nv_rs_errno_to_nv_status(PTR_ERR(new_buf));
new_buf = NULL;
}
} else {
int rc = nv_rs_dmabuf_export_append_fd(in_fd, client_owner, h_client,
gpu_id, total_objects, index,
ext.ext, ext.count, pins, num_pins);
if (rc == 0)
out_fd = in_fd;
else
status = nv_rs_errno_to_nv_status(rc);
}
}
if (status != 0)
nv_rs_dmabuf_unpin_pins_locked(pins, num_pins);
mutex_unlock(&nv_rs_rmapi_lock);
if (new_buf) {
int res_fd = nv_rs_dmabuf_reserve_fd(pending, new_buf);
if (res_fd >= 0)
out_fd = res_fd;
else
status = nv_rs_errno_to_nv_status(res_fd);
}
kfree(pins);
nv_rs_dmabuf_extents_free(&ext);
reply:
if (index == 0 || status == 0)
memcpy(top, &out_fd, sizeof(out_fd));
memcpy(top + 2600, &status, sizeof(status));
return 0;
}
static long nv_rs_rmapi_ioctl(struct file *file, unsigned int command, unsigned long argument)
{
struct nv_rs_rmapi_file *context = file->private_data;
struct nv_rs_request request;
struct nv_rs_xfer xfer;
struct nv_rs_rmapi_write writes[3];
void __user *user;
u8 top_buf[96];
u8 params_buf[192];
u8 *top = NULL, *params = NULL, *nested = NULL;
u64 address = 0, owner = context->owner, file_owner = context->owner;
u64 nested_in = 0, nested_out = 0;
size_t length = 0, nested_len = 0;
u32 write_count = 0, index;
bool admin = capable(CAP_SYS_ADMIN), control_node = context->gpu < 0;
bool owner_resolved = false;
struct nv_rs_rmapi_access access = { 0 };
struct nv_rs_dmabuf_pending dmabuf_pending = { 0 };
u32 gpu_access;
int result, step = 0;
result = nv_rs_plan(command, argument, NULL, &request);
if (result == 1) {
if (copy_from_user(&xfer, (void __user *)argument, sizeof(xfer)))
return -EFAULT;
result = nv_rs_plan(command, argument, &xfer, &request);
}
if (result)
return result;
user = u64_to_user_ptr(request.pointer);
if (request.size <= sizeof(top_buf)) {
top = top_buf;
} else {
top = kmalloc(request.size, GFP_KERNEL);
if (!top)
return -ENOMEM;
}
if (copy_from_user(top, user, request.size)) {
result = -EFAULT;
goto out;
}
if (request.command == NV_RS_ESC_REGISTER_FD) {
result = nv_rs_rmapi_register(file, top, request.size);
goto copy_top;
}
if (request.command == NV_RS_ESC_QUERY_DEVICE_INTR) {
result = nv_rs_rmapi_query_device_intr(file, top, request.size);
goto copy_top;
}
if (request.command == NV_RS_ESC_SET_NUMA_STATUS) {
result = nv_rs_rmapi_set_numa_status(file, top, request.size);
goto copy_top;
}
if (request.command == NV_RS_ESC_EXPORT_TO_DMABUF_FD) {
result = nv_rs_rmapi_export_dmabuf(file, top, request.size, &dmabuf_pending);
goto copy_top;
}
if (request.command == NV_RS_ESC_RM_GET_EVENT_DATA) {
u32 more = 0;
u32 st;
if (request.size != 16) {
result = -EINVAL;
goto out;
}
st = test_and_clear_bit(0, &context->events) ? 0u : 0x57u;
memcpy(top + 8, &more, sizeof(more));
memcpy(top + 12, &st, sizeof(st));
result = 0;
goto copy_top;
}
/* Only NV_ESC_RM_ALLOC (0x2b) for class 0x80 (NV01_DEVICE_0) consults gpu_access
* (deviceConstruct_IMPL -> osIsGpuAccessible). Skip iterate_fd over current->files
* on all other RM escapes to avoid taking files->file_lock on every ioctl. */
if (request.command == 0x2b && request.size >= 16 && *(u32 *)(top + 12) == 0x80u)
iterate_fd(current->files, 0, nv_rs_rmapi_match_gpu, &access);
/* Only NV_ESC_RM_CONTROL (0x2a) and channel NV_ESC_RM_ALLOC (0x2b with
* 368-byte R580 NV_CHANNEL_ALLOC_PARAMS, which grows to 376 B on R620+
* userspace) inspect server/version state during prepare(). Every other
* NV_ESC_RM_ALLOC stays on the lockless fast path, and all other escapes
* have zero user parameter copy. */
if (request.command == 0x2a) {
if (mutex_lock_interruptible(&nv_rs_rmapi_lock)) {
result = -ERESTARTSYS;
goto out;
}
if (context->control && request.command != NV_RS_ESC_ALLOC_OS_EVENT &&
request.command != NV_RS_ESC_FREE_OS_EVENT)
owner = ((struct nv_rs_rmapi_file *)context->control->private_data)->owner;
owner_resolved = true;
gpu_access = nv_rs_rmapi_gpu_access(&access);
step = nv_rs_rmapi_prepare(nv_rs_rmapi_state, owner, file_owner, admin, control_node,
gpu_access, request.command, top, request.size, &address,
&length, &result);
mutex_unlock(&nv_rs_rmapi_lock);
if (step < 0) {
result = step;
goto out;
}
if (step == 1)
goto copy_top;
} else if (request.command == 0x2b) {
step = nv_rs_rmapi_prepare_alloc(control_node, top, request.size, &address, &length);
if (step < 0) {
result = step;
goto out;
}
if (length == 368u) {
if (mutex_lock_interruptible(&nv_rs_rmapi_lock)) {
result = -ERESTARTSYS;
goto out;
}
if (context->control)
owner = ((struct nv_rs_rmapi_file *)context->control->private_data)->owner;
owner_resolved = true;
gpu_access = nv_rs_rmapi_gpu_access(&access);
step = nv_rs_rmapi_prepare(nv_rs_rmapi_state, owner, file_owner, admin, control_node,
gpu_access, request.command, top, request.size, &address,
&length, &result);
mutex_unlock(&nv_rs_rmapi_lock);
if (step < 0) {
result = step;
goto out;
}
if (step == 1)
goto copy_top;
}
}
if (length) {
if (length <= sizeof(params_buf)) {
params = params_buf;
} else {
params = kvmalloc(length, GFP_KERNEL);
if (!params) {
result = -ENOMEM;
goto out;
}
}
if (copy_from_user(params, u64_to_user_ptr(address), length)) {
result = nv_rs_rmapi_copy_fault(request.command, top, request.size, false);
length = 0;
goto copy_top;
}
if (nv_rs_rmapi_nested_plan(top, request.size, params, length, &nested_in, &nested_out,
&nested_len) == 1 && nested_len) {
nested = kvmalloc(nested_len, GFP_KERNEL);
if (!nested) {
result = -ENOMEM;
goto out;
}
if (copy_from_user(nested, u64_to_user_ptr(nested_in), nested_len)) {
result = nv_rs_rmapi_copy_fault(request.command, top, request.size, false);
length = 0;
nested_len = 0;
goto copy_top;
}
}
}
if (mutex_lock_interruptible(&nv_rs_rmapi_lock)) {
result = -ERESTARTSYS;
goto out;
}
/* Keep the owner selected during prepare() when prepare() ran under lock
* (RM_CONTROL or channel RM_ALLOC) so a concurrent REGISTER_FD between
* prepare and execute cannot split preflight and execution across two
* owners. Single-lock escapes resolve context->control once here under
* nv_rs_rmapi_lock. */
if (!owner_resolved && context->control &&
request.command != NV_RS_ESC_ALLOC_OS_EVENT &&
request.command != NV_RS_ESC_FREE_OS_EVENT)
owner = ((struct nv_rs_rmapi_file *)context->control->private_data)->owner;
/* The lock was dropped for the user copy: a GPU may have left meanwhile. */
if (!admin && nv_rs_unpriv_profiling()) {
if (request.command == 0x2a && request.size >= 12) {
u32 ctrl_cmd = *(u32 *)(top + 8);
u32 cls = ctrl_cmd >> 16;
u32 cat = ctrl_cmd >> 8;
if (cat == 0x208020u || cat == 0x208030u ||
cls == 0xb0ccu || cls == 0xb1ccu || cls == 0xb2ccu)
admin = true;
} else if (request.command == 0x2b && request.size >= 16) {
u32 hclass = *(u32 *)(top + 12);
if (hclass == 0xb0ccu || hclass == 0xb1ccu || hclass == 0xb2ccu)
admin = true;
}
}
if (request.command == 0x2a || request.command == 0x2b)
nv_rs_gpu_nice_apply_params_locked(false);
gpu_access = nv_rs_rmapi_gpu_access(&access);
result = nv_rs_rmapi_execute(nv_rs_rmapi_state, owner, file_owner, admin, control_node,
gpu_access, request.command, top, request.size, params, length,
nested, nested_len, writes, &write_count);
{
bool has_nice_tsgs = (request.command == 0x2a || request.command == 0x2b) &&
nv_rs_gpu_nice_has_tracked(nv_rs_rmapi_state);
mutex_unlock(&nv_rs_rmapi_lock);
#ifndef NV_RS_PCI_TEST_EDU
{
extern void nv_rs_gpu_dispatch_pending_kcbs(void);
nv_rs_gpu_dispatch_pending_kcbs();
}
#endif
nv_rs_gpu_nice_schedule_if_active(has_nice_tsgs);
}
if (nv_rs_runtime_engines() && result != 0)
pr_info_ratelimited("nvidia_rs: rt RM_ESC cmd=0x%x size=0x%x rc=%d\n",
request.command, request.size, result);
if (nv_rs_runtime_engines() && result == 0) {
if (request.command == 0x2b && request.size >= 0x20) {
u32 hclass = *(u32 *)(top + 12);
u32 st = request.size >= 0x30 ? *(u32 *)(top + 40) : *(u32 *)(top + 28);
if (st != 0)
pr_info_ratelimited("nvidia_rs: rt RM_ALLOC class=0x%x status=0x%x\n", hclass, st);
} else if (request.command == 0x2a && request.size >= 0x20) {
u32 cmd = *(u32 *)(top + 8);
u32 st = *(u32 *)(top + 28);
if (st != 0 && cmd != 0x2080182a && cmd != 0x00de0001 &&
cmd != 0x2080a637 && cmd != 0x20808165)
pr_info_ratelimited("nvidia_rs: rt RM_CONTROL cmd=0x%x status=0x%x\n", cmd, st);
} else if (request.command == 0x4e && request.size >= 0x38) {
u32 st = *(u32 *)(top + 40);
if (st != 0)
pr_info_ratelimited("nvidia_rs: rt RM_MAP_MEMORY handle=0x%x status=0x%x\n",
*(u32 *)(top + 8), st);
} else if (request.command == 0x57 && request.size >= 0x40) {
u32 st = *(u32 *)(top + 56);
if (st != 0) {
u64 off = *(u64 *)(top + 16);
u64 len = *(u64 *)(top + 24);
u32 fl = *(u32 *)(top + 32);
u64 va = *(u64 *)(top + 48);
pr_info_ratelimited("nvidia_rs: rt RM_MAP_MEMORY_DMA handle=0x%x fl=0x%x off=0x%llx len=0x%llx va=0x%llx status=0x%x\n",
*(u32 *)(top + 12), fl, off, len, va, st);
}
}
}
for (index = 0; index < write_count; index++) {
const void *src = writes[index].use_inline ? writes[index].inline_data : writes[index].data;
if (copy_to_user(u64_to_user_ptr(writes[index].address), src,
writes[index].length)) {
nv_rs_rmapi_copy_fault(request.command, top, request.size, true);
break;
}
}
if (nested_len && copy_to_user(u64_to_user_ptr(nested_out), nested, nested_len))
nv_rs_rmapi_copy_fault(request.command, top, request.size, true);
if (length && copy_to_user(u64_to_user_ptr(address), params, length))
nv_rs_rmapi_copy_fault(request.command, top, request.size, true);
copy_top:
/* As nvidia_ioctl: the block goes back whatever the result is. A dma-buf fd it carries is
* installed only if it arrived. */
if (copy_to_user(user, top, request.size)) {
result = -EFAULT;
nv_rs_dmabuf_publish_fd(&dmabuf_pending, false);
} else {
nv_rs_dmabuf_publish_fd(&dmabuf_pending, true);
}
out:
kvfree(nested);
if (params && params != params_buf)
kvfree(params);
if (top && top != top_buf)
kfree(top);
return result;
}
#ifdef CONFIG_COMPAT
static long nv_rs_rmapi_compat_ioctl(struct file *file, unsigned int command, unsigned long arg)
{
return nv_rs_rmapi_ioctl(file, command, (unsigned long)compat_ptr(arg));
}
#endif
/* All pages are inserted by mmap; nothing is ever faulted in (nvidia_fault on the
* control node). */
static vm_fault_t nv_rs_rmapi_fault(struct vm_fault *fault)
{
(void)fault;
return VM_FAULT_SIGBUS;
}
static const struct vm_operations_struct nv_rs_rmapi_vm_operations = {
.fault = nv_rs_rmapi_fault,
};
/* nvidia_mmap_helper for the control node (nv-mmap.c): a file without a mapping context
* is refused with EINVAL (always the case for a device-node file here: BAR mappings do
* not exist), the offset must be 0, the mapping starts at the context's page and must end
* inside the allocation (ERANGE). The pages are inserted at once with vm_insert_page,
* whose page references keep them alive while mapped.
*
* Differences from the original: a private mapping is refused with EINVAL (the original
* turns it into a shared one by setting VM_SHARED afterwards); the allocation's cache type
* is applied only when its kernel mapping was made uncached (for pinned user pages: when
* their range maps such allocations, all of one type, which the record's mappings take),
* otherwise the pages are mapped cached; pinned user pages of write-combined mappings are
* mapped write-combined, not uncached; a read-only context is applied before the pages
* are inserted, not after.
*
* The context is immutable once valid and holds a use of the allocation until the file is
* released, so nothing is locked here. */
static inline void nv_rs_vm_flags_set(struct vm_area_struct *vma, vm_flags_t flags)
{
#if defined(NV_RS_HAVE_VMA_FLAGS_SET_WORD)
vma_flags_set_word(&vma->flags, flags);
#elif defined(NV_RS_HAVE_VM_FLAGS_SET) || LINUX_VERSION_CODE >= KERNEL_VERSION(6, 3, 0)
vm_flags_set(vma, flags);
#else
vma->vm_flags |= flags;
#endif
}
static inline void nv_rs_vm_flags_clear(struct vm_area_struct *vma, vm_flags_t flags)
{
#if defined(NV_RS_HAVE_VMA_FLAGS_SET_WORD)
vma_flags_clear_word(&vma->flags, flags);
#elif defined(NV_RS_HAVE_VM_FLAGS_SET) || LINUX_VERSION_CODE >= KERNEL_VERSION(6, 3, 0)
vm_flags_clear(vma, flags);
#else
vma->vm_flags &= ~flags;
#endif
}
static bool nv_rs_rmapi_userd_live_locked(struct nv_rs_rmapi_file *context)
{
return context->userd_map_refs &&
nv_rs_rmapi_userd_admitted_locked(context, context->userd_gpu_id);
}
static vm_fault_t nv_rs_rmapi_userd_fault(struct vm_fault *vmf)
{
struct vm_area_struct *vma = vmf->vma;
struct nv_rs_rmapi_file *context = vma->vm_file->private_data;
struct nv_rs_file_map_record mapping;
vm_fault_t result = VM_FAULT_SIGBUS;
bool found;
/* Revocation marks the cookie dead under this lock, then zaps unlocked. */
mutex_lock(&nv_rs_rmapi_userd_lock);
if (vmf->pgoff == context->userd_pgoff && nv_rs_rmapi_userd_live_locked(context)) {
mutex_lock(&nv_rs_rmapi_alloc_lock);
found = nv_rs_file_map_get(context->owner, &mapping);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (found && mapping.is_io && mapping.io_bytes == PAGE_SIZE)
result = vmf_insert_pfn_prot(vma, vmf->address, mapping.io_phys >> PAGE_SHIFT,
vma->vm_page_prot);
}
mutex_unlock(&nv_rs_rmapi_userd_lock);
return result;
}
static const struct vm_operations_struct nv_rs_rmapi_userd_vm_operations = {
.fault = nv_rs_rmapi_userd_fault,
};
static bool nv_rs_rmapi_plat_node_live(int gpu, unsigned int generation)
{
unsigned long flags;
bool live = false;
if (gpu < 0 || gpu >= NV_RS_RMAPI_MAX_GPUS)
return false;
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
live = nv_rs_rmapi_gpu_nodes[gpu].live &&
nv_rs_rmapi_gpu_nodes[gpu].generation == generation &&
nv_rs_rmapi_gpu_nodes[gpu].is_platform;
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
return live;
}
#include "rmapi_plat_io.h"
static int nv_rs_rmapi_mmap(struct file *file, struct vm_area_struct *vma)
{
struct nv_rs_rmapi_file *context = file->private_data;
struct nv_rs_file_map_record mapping;
struct nv_rs_rmapi_alloc *alloc;
unsigned long address = vma->vm_start;
u64 pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT, index;
bool has_map;
if (vma->vm_pgoff != 0 || !(vma->vm_flags & VM_SHARED))
return -EINVAL;
/* Take the mode and cookie together. A previously authorized mmap may
* publish its VMA after a zap; its immutable old key then faults closed. */
mutex_lock(&nv_rs_rmapi_userd_lock);
if (context->userd_file) {
if (!nv_rs_rmapi_userd_live_locked(context)) {
mutex_unlock(&nv_rs_rmapi_userd_lock);
return -ENODEV;
}
if (pages != 1) {
mutex_unlock(&nv_rs_rmapi_userd_lock);
return -ERANGE;
}
vma->vm_pgoff = context->userd_pgoff;
mutex_unlock(&nv_rs_rmapi_userd_lock);
vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot);
nv_rs_vm_flags_set(vma, VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP);
vma->vm_ops = &nv_rs_rmapi_userd_vm_operations;
return 0;
}
mutex_lock(&nv_rs_rmapi_alloc_lock);
has_map = nv_rs_file_map_get(context->owner, &mapping);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
mutex_unlock(&nv_rs_rmapi_userd_lock);
if (!has_map)
return -EINVAL;
if (mapping.is_io) {
unsigned long size = vma->vm_end - vma->vm_start;
struct nv_rs_pci *pci = NULL;
struct pci_dev *pdev = NULL;
struct device *plat_dev = NULL;
unsigned long flags;
int rc;
if (!size || size > mapping.io_bytes) {
return -ERANGE;
}
if (context->gpu < 0 || context->gpu >= NV_RS_RMAPI_MAX_GPUS)
return -ENODEV;
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
if (nv_rs_rmapi_gpu_nodes[context->gpu].live &&
nv_rs_rmapi_gpu_nodes[context->gpu].generation == context->generation) {
if (nv_rs_rmapi_gpu_nodes[context->gpu].owner)
pci = nv_rs_gpu_owner_pci_get(nv_rs_rmapi_gpu_nodes[context->gpu].owner);
else if (nv_rs_rmapi_gpu_nodes[context->gpu].pdev)
pdev = pci_dev_get(nv_rs_rmapi_gpu_nodes[context->gpu].pdev);
else if (nv_rs_rmapi_gpu_nodes[context->gpu].is_platform &&
nv_rs_rmapi_gpu_nodes[context->gpu].dev)
plat_dev = get_device(nv_rs_rmapi_gpu_nodes[context->gpu].dev);
}
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
if (!pci && !pdev && !plat_dev)
return -ENODEV;
if (!(mapping.protection & 2)) {
nv_rs_vm_flags_clear(vma, VM_WRITE | VM_MAYWRITE);
vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
}
if (mapping.caching == 2)
vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot);
else
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
nv_rs_vm_flags_set(vma, VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP);
if (plat_dev) {
if (mapping.alloc_ptr)
rc = -EOPNOTSUPP;
else
rc = nv_rs_rmapi_plat_io_mmap_setup(file, vma, context->gpu,
context->generation, mapping.io_phys,
size);
put_device(plat_dev);
return rc;
}
if (mapping.alloc_ptr) {
const struct nv_rs_io_scatter *sc = (const struct nv_rs_io_scatter *)mapping.alloc_ptr;
unsigned long cur_addr = vma->vm_start;
unsigned long rem = size;
u32 seg_i;
rc = 0;
for (seg_i = 0; seg_i < sc->count && rem > 0; seg_i++) {
unsigned long take = (unsigned long)min_t(u64, rem, sc->segs[seg_i].io_bytes);
rc = remap_pfn_range(vma, cur_addr, sc->segs[seg_i].io_phys >> PAGE_SHIFT,
take, vma->vm_page_prot);
if (rc)
break;
cur_addr += take;
rem -= take;
}
if (!rc && rem != 0)
rc = -ERANGE;
} else {
rc = remap_pfn_range(vma, vma->vm_start, mapping.io_phys >> PAGE_SHIFT,
size, vma->vm_page_prot);
}
if (pci)
nv_rs_pci_put(pci);
if (pdev)
pci_dev_put(pdev);
return rc;
}
alloc = (struct nv_rs_rmapi_alloc *)mapping.alloc_ptr;
if (!alloc || alloc->external_dma || mapping.page_index + pages > alloc->count)
return -ERANGE;
if (!(mapping.protection & 2)) {
nv_rs_vm_flags_clear(vma, VM_WRITE | VM_MAYWRITE);
vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
}
/* nvidia_mmap: nv_encode_caching(at->cache_type) before nvidia_mmap_sysmem (580.178.04 nv-mmap.c:328-394,
* 699-708; 620.73.04 nv-mmap.c:346-363 uses pgprot_writecombine / pgprot_noncached as here). The type is the
* one nv_rs_rmapi_pin_scan counts this area as. */
switch (nv_rs_rmapi_user_cache(alloc)) {
case 2:
vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot);
break;
case 1:
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
break;
default:
break;
}
nv_rs_vm_flags_set(vma, VM_DONTEXPAND | VM_DONTDUMP);
vma->vm_ops = &nv_rs_rmapi_vm_operations;
/* NV_VMA_PRIVATE(vma) = at (580.178.04 nv-mmap.c:706); read by nv_rs_rmapi_area_alloc */
vma->vm_private_data = alloc;
for (index = mapping.page_index; index < mapping.page_index + pages; index++) {
/* On failure the caller removes the area and with it the pages inserted so far. */
if (vm_insert_page(vma, address, alloc->pages[index]))
return -EAGAIN;
address += PAGE_SIZE;
}
return 0;
}
/* Post a dataless OS event to `owner` (matching stock `nv_post_event` without data).
* Caller must hold `nv_rs_rmapi_lock` so the file context stays alive. */
void nv_rs_rmapi_file_post(u64 owner)
{
struct nv_rs_rmapi_file *context = (struct nv_rs_rmapi_file *)(unsigned long)owner;
if (!context)
return;
set_bit(0, &context->events);
wake_up_interruptible(&context->wait);
}
/* The engines' non-stall interrupts of `gpu` whose event slots are in `mask` happened (ga10x_events.rs, from an IRQ
* thread): the OS-event files registered for them are posted (nv_rs_gpu_events). The lock is only tried: -EBUSY while
* the node is busy (the caller tries again; it never waits, so stopping it under the lock cannot deadlock); otherwise
* the number of non-stall events registered on the GPU. */
#ifndef NV_RS_PCI_TEST_EDU /* the guest test module has no GA10x / GV100 event code */
int nv_rs_rmapi_engine_events(u32 gpu, u32 mask);
int nv_rs_rmapi_engine_events(u32 gpu, u32 mask)
{
extern u32 nv_rs_gpu_events(void *node, u32 gpu, u32 mask);
int n;
if (!mutex_trylock(&nv_rs_rmapi_lock))
return -EBUSY;
n = nv_rs_rmapi_state ? (int)nv_rs_gpu_events(nv_rs_rmapi_state, gpu, mask) : 0;
mutex_unlock(&nv_rs_rmapi_lock);
return n;
}
/* An IRQ thread ran out of tries (the node busy for ~200 ms in one go): the slots stay pending in the event code and
* this work posts them once the lock is free (nv_rs_gpu_events_retry), without waiting for another interrupt. It
* only tries the lock too (again every 5 ms), so a teardown holding the lock never waits for it; cancelled at node
* exit. */
struct nv_rs_pending_modeset {
u32 gpu_id;
u32 vblank_heads;
u32 plug_mask;
u32 unplug_mask;
};
static void nv_rs_rmapi_events_retry_fn(struct work_struct *work);
static DECLARE_DELAYED_WORK(nv_rs_rmapi_events_retry, nv_rs_rmapi_events_retry_fn);
static void nv_rs_rmapi_events_retry_fn(struct work_struct *work)
{
extern u32 nv_rs_gpu_events_retry(void *node, struct nv_rs_pending_modeset *out, u32 cap);
extern void nv_rs_gpu_events_dispatch_modeset(const struct nv_rs_pending_modeset *items, u32 count);
static struct nv_rs_pending_modeset pending[NV_RS_RMAPI_MAX_GPUS];
u32 count = 0;
if (!mutex_trylock(&nv_rs_rmapi_lock)) {
schedule_delayed_work(&nv_rs_rmapi_events_retry, msecs_to_jiffies(1));
return;
}
if (nv_rs_rmapi_state)
count = nv_rs_gpu_events_retry(nv_rs_rmapi_state, pending, ARRAY_SIZE(pending));
mutex_unlock(&nv_rs_rmapi_lock);
if (count > 0)
nv_rs_gpu_events_dispatch_modeset(pending, count);
if (count >= ARRAY_SIZE(pending))
schedule_delayed_work(&nv_rs_rmapi_events_retry, msecs_to_jiffies(1));
}
void nv_rs_rmapi_engine_events_later(void);
void nv_rs_rmapi_engine_events_later(void)
{
schedule_delayed_work(&nv_rs_rmapi_events_retry, msecs_to_jiffies(1));
}
void nv_rs_rmapi_engine_events_now(void);
void nv_rs_rmapi_engine_events_now(void)
{
mod_delayed_work(system_wq, &nv_rs_rmapi_events_retry, 0);
}
#endif
static __poll_t nv_rs_rmapi_poll(struct file *file, poll_table *wait)
{
struct nv_rs_rmapi_file *context = file->private_data;
if (!(file->f_flags & O_NONBLOCK))
poll_wait(file, &context->wait, wait);
/* Report a posted dataless event once, matching stock `nvidia_poll`. */
if (test_and_clear_bit(0, &context->events))
return EPOLLPRI | EPOLLIN;
return 0;
}
static const struct file_operations nv_rs_rmapi_operations = {
.owner = THIS_MODULE, .open = nv_rs_rmapi_open, .release = nv_rs_rmapi_release,
.unlocked_ioctl = nv_rs_rmapi_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = nv_rs_rmapi_compat_ioctl,
#endif
.mmap = nv_rs_rmapi_mmap, .poll = nv_rs_rmapi_poll,
/* Match stock 580.178.04 nvidia_fops: omit .llseek (NULL -> -ESPIPE on all kernels). */
};
static const struct file_operations nv_rs_rmapi_gpu_operations = {
.owner = THIS_MODULE, .open = nv_rs_rmapi_gpu_open_file, .release = nv_rs_rmapi_release,
.unlocked_ioctl = nv_rs_rmapi_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = nv_rs_rmapi_compat_ioctl,
#endif
.mmap = nv_rs_rmapi_mmap, .poll = nv_rs_rmapi_poll,
/* Match stock 580.178.04 nvidia_fops: omit .llseek (NULL -> -ESPIPE on all kernels). */
};
static struct miscdevice nv_rs_rmapi_device = {
.minor = MISC_DYNAMIC_MINOR, .name = "nvidia-rs-rmapi-ctl",
.fops = &nv_rs_rmapi_operations, .mode = 0666,
};
/* Lists the GPU on the control node and creates its device node
* /dev/nvidia-rs-rmapi-gpu<minor>. Returns the minor number or a negative errno. */
int nv_rs_rmapi_node_gpu_add_desc(const struct nv_rs_rmapi_gpu_desc *desc)
{
struct nv_rs_rmapi_gpu gpu;
struct nv_rs_rmapi_gpu_node *node;
int minor, result;
if (!nv_rs_rmapi_state)
return -ENODEV;
if (!desc)
return -EINVAL;
gpu = (struct nv_rs_rmapi_gpu){
.domain = desc->domain, .bus = desc->bus,
.slot = desc->slot, .function = desc->function,
.vendor = desc->vendor, .device = desc->device, .irq = desc->irq,
.bar0 = desc->bar0, .bar0_size = desc->bar0_size,
.bar1 = desc->bar1, .bar1_size = desc->bar1_size,
.bar2 = desc->bar2, .bar2_size = desc->bar2_size,
.subsystem_vendor = desc->subsystem_vendor, .subsystem = desc->subsystem,
.revision = desc->revision, .boot0 = desc->boot0,
.pci_class = desc->pci_class,
};
mutex_lock(&nv_rs_rmapi_lock);
minor = nv_rs_rmapi_gpu_add(nv_rs_rmapi_state, &gpu);
if (minor >= NV_RS_RMAPI_MAX_GPUS || (minor >= 0 && nv_rs_rmapi_gpu_nodes[minor].live)) {
nv_rs_rmapi_gpu_remove(nv_rs_rmapi_state, gpu.domain, gpu.bus, gpu.slot);
minor = -ENOSPC;
}
mutex_unlock(&nv_rs_rmapi_lock);
if (minor < 0)
return minor;
/* Registered outside the lock: an open may arrive at once and takes the lock. */
node = &nv_rs_rmapi_gpu_nodes[minor];
memset(&node->misc, 0, sizeof(node->misc));
snprintf(node->name, sizeof(node->name), "nvidia-rs-rmapi-gpu%d", minor);
node->misc.minor = MISC_DYNAMIC_MINOR;
node->misc.name = node->name;
node->misc.fops = &nv_rs_rmapi_gpu_operations;
node->misc.mode = 0666;
mutex_lock(&nv_rs_rmapi_lock);
node->read32 = desc->read32;
node->release = desc->release;
node->cookie = desc->cookie;
node->minor_index = minor;
{
unsigned long flags;
u32 gpu_id = (((u32)gpu.domain & 0xffffU) << 16) | ((u32)gpu.bus << 8) | (u32)gpu.slot;
#ifdef CONFIG_PCI
struct pci_dev *pdev = (desc->dev && dev_is_pci(desc->dev)) ? to_pci_dev(desc->dev) : NULL;
#else
struct pci_dev *pdev = NULL;
#endif
node->generation = nv_rs_gpu_slot_activate((u32)minor, gpu_id,
gpu.bar0, gpu.bar0_size,
gpu.bar1, gpu.bar1_size);
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
node->dev = desc->dev;
node->pdev = pdev;
node->gpu_id = gpu_id;
node->boot0 = desc->boot0;
node->dma_bits = desc->dma_bits ? desc->dma_bits
: nv_rs_uvm_dma_bits_for_boot0(desc->boot0);
node->device_id = desc->device;
node->irq = desc->irq;
node->is_platform = desc->dev && !pdev;
atomic_set(&node->idle_pstate_mode, 0);
atomic64_set(&node->idle_pstate_transitions, 0);
atomic64_set(&node->idle_pstate_total_secs, 0);
atomic64_set(&node->power_cap_mw, 0);
atomic_set(&node->tensor_fp32_rate, 0);
/* GP100/GP104 use a dedicated BAR1 root in the opt-in legacy runtime. */
node->pascal_userd_gpu = (desc->boot0 >> 20 & 0x1ff) == 0x130 ||
(desc->boot0 >> 20 & 0x1ff) == 0x134;
node->userd_runtime_live = false;
node->userd_pm_lost = false;
node->live = true;
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
}
mutex_unlock(&nv_rs_rmapi_lock);
result = misc_register(&node->misc);
if (result) {
unsigned long flags;
mutex_lock(&nv_rs_rmapi_lock);
node->read32 = NULL;
node->release = NULL;
node->cookie = NULL;
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
node->live = false;
node->userd_runtime_live = false;
node->dev = NULL;
node->pdev = NULL;
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
node->generation = nv_rs_gpu_slot_deactivate((u32)minor);
nv_rs_rmapi_gpu_remove(nv_rs_rmapi_state, gpu.domain, gpu.bus, gpu.slot);
mutex_unlock(&nv_rs_rmapi_lock);
return result;
}
if (nv_rs_compat_gpu_registered && nv_rs_compat_class) {
struct device *cdev_dev = device_create(nv_rs_compat_class, desc->dev,
MKDEV(NV_RS_COMPAT_MAJOR, (unsigned int)minor),
NULL, "nvidia%d", minor);
if (IS_ERR(cdev_dev))
pr_warn("nvidia_rs: compat /dev/nvidia%d device_create failed (%ld)\n",
minor, PTR_ERR(cdev_dev));
}
nv_rs_modeset_register_gpu(((gpu.domain & 0xffffU) << 16) | ((u32)gpu.bus << 8) | (u32)gpu.slot,
gpu.domain, gpu.bus, gpu.slot, gpu.function, desc->dev);
#ifdef CONFIG_PROC_FS
if (nv_rs_proc_gpus) {
snprintf(node->bdf, sizeof(node->bdf), "%04x:%02x:%02x.%u",
gpu.domain, gpu.bus, gpu.slot, gpu.function);
node->proc_dir = proc_mkdir(node->bdf, nv_rs_proc_gpus);
if (node->proc_dir) {
proc_create_single_data("information", 0444, node->proc_dir,
nv_rs_proc_gpu_info_show, node);
proc_create_single_data("power", 0444, node->proc_dir,
nv_rs_proc_gpu_power_show, node);
proc_create_single_data("registry", 0444, node->proc_dir,
nv_rs_proc_gpu_registry_show, node);
}
}
/* Stock creates capabilities/gpu<minor>/mig for every GPU; the gi/ci files appear only
* once MIG is enabled, which no Volta can do. Its own tree, so a failed gpus/ directory
* must not skip it. */
if (nv_rs_proc_caps) {
char caps_name[16];
snprintf(caps_name, sizeof(caps_name), "gpu%d", node->minor_index);
node->caps_dir = proc_mkdir(caps_name, nv_rs_proc_caps);
if (node->caps_dir)
proc_mkdir("mig", node->caps_dir);
}
#endif
return minor;
}
void nv_rs_rmapi_update_power_telemetry(u32 gpu_id, u8 idle_mode, u64 transitions,
u64 idle_secs, u32 power_cap_mw)
{
unsigned long flags;
int i;
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
for (i = 0; i < NV_RS_RMAPI_MAX_GPUS; i++) {
if (nv_rs_rmapi_gpu_nodes[i].live && nv_rs_rmapi_gpu_nodes[i].gpu_id == gpu_id) {
atomic_set(&nv_rs_rmapi_gpu_nodes[i].idle_pstate_mode, idle_mode ? 1 : 0);
atomic64_set(&nv_rs_rmapi_gpu_nodes[i].idle_pstate_transitions, (s64)transitions);
atomic64_set(&nv_rs_rmapi_gpu_nodes[i].idle_pstate_total_secs, (s64)idle_secs);
atomic64_set(&nv_rs_rmapi_gpu_nodes[i].power_cap_mw, (s64)power_cap_mw);
break;
}
}
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
}
void nv_rs_rmapi_set_power_cap_mw(u32 gpu_id, u32 power_cap_mw)
{
unsigned long flags;
int i;
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
for (i = 0; i < NV_RS_RMAPI_MAX_GPUS; i++) {
if (nv_rs_rmapi_gpu_nodes[i].live && nv_rs_rmapi_gpu_nodes[i].gpu_id == gpu_id) {
atomic64_set(&nv_rs_rmapi_gpu_nodes[i].power_cap_mw, (s64)power_cap_mw);
break;
}
}
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
}
void nv_rs_rmapi_set_tensor_fp32_rate(u32 gpu_id, u8 rate)
{
unsigned long flags;
int i;
if (rate > 2)
rate = 0;
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
for (i = 0; i < NV_RS_RMAPI_MAX_GPUS; i++) {
if (nv_rs_rmapi_gpu_nodes[i].live && nv_rs_rmapi_gpu_nodes[i].gpu_id == gpu_id) {
atomic_set(&nv_rs_rmapi_gpu_nodes[i].tensor_fp32_rate, (int)rate);
break;
}
}
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
}
int nv_rs_rmapi_node_gpu_add(struct pci_dev *pdev, u32 boot0)
{
struct nv_rs_rmapi_gpu_desc desc = {
.dev = &pdev->dev,
.domain = pci_domain_nr(pdev->bus),
.bus = pdev->bus->number,
.slot = PCI_SLOT(pdev->devfn),
.function = PCI_FUNC(pdev->devfn),
.vendor = pdev->vendor,
.device = pdev->device,
.subsystem_vendor = pdev->subsystem_vendor,
.subsystem = pdev->subsystem_device,
.revision = pdev->revision,
.pci_class = pdev->class,
.irq = pdev->irq,
.bar0 = pci_resource_start(pdev, 0),
.bar0_size = pci_resource_len(pdev, 0),
.bar1 = pci_resource_start(pdev, 1),
.bar1_size = pci_resource_len(pdev, 1),
.bar2 = pci_resource_start(pdev, 3),
.bar2_size = pci_resource_len(pdev, 3),
.boot0 = boot0,
};
return nv_rs_rmapi_node_gpu_add_desc(&desc);
}
int nv_rs_rmapi_node_gpu_reader_by_bdf(u32 domain, u8 bus, u8 slot,
int (*read32)(void *cookie, u64 offset, u32 *value),
void (*release)(void *cookie), void *cookie)
{
int minor;
if (!nv_rs_rmapi_state)
return -ENODEV;
mutex_lock(&nv_rs_rmapi_lock);
minor = nv_rs_rmapi_gpu_minor(nv_rs_rmapi_state, domain, bus, slot);
if (minor >= 0 && minor < NV_RS_RMAPI_MAX_GPUS && nv_rs_rmapi_gpu_nodes[minor].live) {
nv_rs_rmapi_gpu_nodes[minor].read32 = read32;
nv_rs_rmapi_gpu_nodes[minor].release = release;
nv_rs_rmapi_gpu_nodes[minor].cookie = cookie;
minor = 0;
} else {
minor = -ENOENT;
}
mutex_unlock(&nv_rs_rmapi_lock);
return minor;
}
int nv_rs_rmapi_node_gpu_reader(struct pci_dev *pdev,
int (*read32)(void *cookie, u64 offset, u32 *value),
void (*release)(void *cookie), void *cookie)
{
return nv_rs_rmapi_node_gpu_reader_by_bdf(pci_domain_nr(pdev->bus),
pdev->bus->number,
PCI_SLOT(pdev->devfn),
read32, release, cookie);
}
int nv_rs_rmapi_node_gpu_runtime(struct pci_dev *pdev, struct nv_rs_gpu_owner *owner)
{
int minor;
if (!nv_rs_rmapi_state)
return -ENODEV;
mutex_lock(&nv_rs_rmapi_lock);
minor = nv_rs_rmapi_gpu_minor(nv_rs_rmapi_state, pci_domain_nr(pdev->bus),
pdev->bus->number, PCI_SLOT(pdev->devfn));
if (minor >= 0 && minor < NV_RS_RMAPI_MAX_GPUS && nv_rs_rmapi_gpu_nodes[minor].live) {
unsigned long flags;
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
nv_rs_rmapi_gpu_nodes[minor].owner = owner;
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
minor = 0;
} else {
minor = -ENOENT;
}
mutex_unlock(&nv_rs_rmapi_lock);
return minor;
}
static bool nv_rs_rmapi_node_start_idle(int minor)
{
return atomic_read(&nv_rs_rmapi_gpu_nodes[minor].runtime_start_users) == 0;
}
/* The GPU is leaving. Files of its device node may still be open: they keep
* working as files (their clients are freed at release), but the GPU is gone from the
* table, its devices are freed here and new opens fail. */
/* pdev is NULL for a platform GPU, which exports no dma-buf (it has no GSP-RM). */
static void nv_rs_rmapi_node_gpu_remove_dev(u32 domain, u8 bus, u8 slot, struct pci_dev *pdev)
{
void (*release)(void *cookie) = NULL;
void *cookie = NULL;
struct nv_rs_gpu_owner *owner = NULL;
struct device *dev = NULL;
struct nv_rs_dmabuf_removal dmabuf_removal;
u32 generation = 0;
#ifdef CONFIG_PROC_FS
struct proc_dir_entry *caps_dir = NULL;
#endif
int minor;
if (!nv_rs_rmapi_state)
return;
/* Revoke the dma-bufs over this GPU before the device and BAR1 go, and refuse new ones until
* it is gone. The importers are waited for without nv_rs_rmapi_lock; the pins, and those of
* dma-bufs released meanwhile, are dropped under it. */
if (pdev) {
nv_rs_dmabuf_revoke_pdev(pdev, &dmabuf_removal);
nv_rs_dmabuf_flush_unpins();
}
/* Notify modeset/DRM consumers BEFORE tearing down GSP/DMA/RM state so
* drm_atomic_helper_shutdown() and display channels can complete cleanly. */
nv_rs_modeset_unregister_gpu((((u32)domain & 0xffffU) << 16) |
((u32)bus << 8) | (u32)slot);
mutex_lock(&nv_rs_rmapi_lock);
if (pdev)
nv_rs_dmabuf_drop_pdev_pins(pdev);
minor = nv_rs_rmapi_gpu_minor(nv_rs_rmapi_state, domain, bus, slot);
nv_rs_rmapi_gpu_remove(nv_rs_rmapi_state, domain, bus, slot);
if (minor >= 0 && minor < NV_RS_RMAPI_MAX_GPUS && nv_rs_rmapi_gpu_nodes[minor].live) {
unsigned long flags;
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
nv_rs_rmapi_gpu_nodes[minor].live = false;
dev = nv_rs_rmapi_gpu_nodes[minor].dev ? get_device(nv_rs_rmapi_gpu_nodes[minor].dev) : NULL;
nv_rs_rmapi_gpu_nodes[minor].dev = NULL;
nv_rs_rmapi_gpu_nodes[minor].pdev = NULL;
owner = nv_rs_rmapi_gpu_nodes[minor].owner;
nv_rs_rmapi_gpu_nodes[minor].owner = NULL;
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
generation = nv_rs_rmapi_gpu_nodes[minor].generation;
nv_rs_rmapi_gpu_nodes[minor].generation = nv_rs_gpu_slot_deactivate((u32)minor);
release = nv_rs_rmapi_gpu_nodes[minor].release;
cookie = nv_rs_rmapi_gpu_nodes[minor].cookie;
nv_rs_rmapi_gpu_nodes[minor].read32 = NULL;
nv_rs_rmapi_gpu_nodes[minor].release = NULL;
nv_rs_rmapi_gpu_nodes[minor].cookie = NULL;
#ifdef CONFIG_PROC_FS
/* Taken with the lock: a replacement GPU may already own this minor by the time the
* proc entry goes away, so never read the slot back after dropping the lock. */
caps_dir = nv_rs_rmapi_gpu_nodes[minor].caps_dir;
nv_rs_rmapi_gpu_nodes[minor].caps_dir = NULL;
#endif
} else {
/* Unreachable under normal platform_driver remove (runs once), yet still reclaim any
* probe ref/cookie if called on an already-deactivated slot so release() never leaks. */
if (minor >= 0 && minor < NV_RS_RMAPI_MAX_GPUS) {
release = nv_rs_rmapi_gpu_nodes[minor].release;
cookie = nv_rs_rmapi_gpu_nodes[minor].cookie;
nv_rs_rmapi_gpu_nodes[minor].read32 = NULL;
nv_rs_rmapi_gpu_nodes[minor].release = NULL;
nv_rs_rmapi_gpu_nodes[minor].cookie = NULL;
}
minor = -1;
}
mutex_unlock(&nv_rs_rmapi_lock);
if (minor >= 0) {
nv_rs_rmapi_revoke_gpu_userd(minor, generation);
nv_rs_rmapi_revoke_gpu_plat_io(minor, generation);
wait_event(nv_rs_rmapi_owner_wq, nv_rs_rmapi_node_start_idle(minor));
}
if (owner)
nv_rs_gpu_owner_runtime_stop(owner);
if (dev) {
nv_rs_rmapi_allocs_unmap_dev(dev);
nv_rs_uvm_unmap_gpu_dev(dev);
put_device(dev);
}
if (minor >= 0) {
#ifdef CONFIG_PROC_FS
if (nv_rs_rmapi_gpu_nodes[minor].proc_dir) {
proc_remove(nv_rs_rmapi_gpu_nodes[minor].proc_dir);
nv_rs_rmapi_gpu_nodes[minor].proc_dir = NULL;
}
if (caps_dir)
proc_remove(caps_dir);
#endif
if (nv_rs_compat_gpu_registered && nv_rs_compat_class)
device_destroy(nv_rs_compat_class, MKDEV(NV_RS_COMPAT_MAJOR, (unsigned int)minor));
misc_deregister(&nv_rs_rmapi_gpu_nodes[minor].misc);
}
if (release)
release(cookie);
if (pdev)
nv_rs_dmabuf_removal_done(&dmabuf_removal);
}
void nv_rs_rmapi_node_gpu_remove_by_bdf(u32 domain, u8 bus, u8 slot)
{
nv_rs_rmapi_node_gpu_remove_dev(domain, bus, slot, NULL);
}
void nv_rs_rmapi_node_gpu_remove(struct pci_dev *pdev)
{
nv_rs_rmapi_node_gpu_remove_dev(pci_domain_nr(pdev->bus), pdev->bus->number,
PCI_SLOT(pdev->devfn), pdev);
}
int nv_rs_rmapi_kernel_open_gpu(u32 gpu_id);
int nv_rs_rmapi_kernel_open_gpu(u32 gpu_id)
{
u32 domain = (gpu_id >> 16) & 0xffffU;
u8 bus = (u8)((gpu_id >> 8) & 0xffU);
u8 slot = (u8)(gpu_id & 0xffU);
struct nv_rs_gpu_owner *owner = NULL;
struct nv_rs_rmapi_gpu_node *node;
int minor, result;
if (!nv_rs_rmapi_state)
return -ENODEV;
mutex_lock(&nv_rs_rmapi_lock);
minor = nv_rs_rmapi_gpu_minor(nv_rs_rmapi_state, domain, bus, slot);
if (minor >= 0 && minor < NV_RS_RMAPI_MAX_GPUS && nv_rs_rmapi_gpu_nodes[minor].live) {
owner = nv_rs_rmapi_gpu_nodes[minor].owner;
if (owner)
atomic_inc(&nv_rs_rmapi_gpu_nodes[minor].runtime_start_users);
} else {
minor = -ENODEV;
}
mutex_unlock(&nv_rs_rmapi_lock);
if (minor < 0)
return minor;
if (owner && nv_rs_runtime_engines()) {
result = nv_rs_gpu_owner_runtime_start(owner);
if (atomic_dec_and_test(&nv_rs_rmapi_gpu_nodes[minor].runtime_start_users))
wake_up_all(&nv_rs_rmapi_owner_wq);
if (result)
return result;
} else if (owner) {
if (atomic_dec_and_test(&nv_rs_rmapi_gpu_nodes[minor].runtime_start_users))
wake_up_all(&nv_rs_rmapi_owner_wq);
}
mutex_lock(&nv_rs_rmapi_lock);
node = &nv_rs_rmapi_gpu_nodes[minor];
result = node->live ? nv_rs_rmapi_gpu_open(nv_rs_rmapi_state, (u32)minor) : -ENODEV;
if (!result)
nv_rs_rmapi_read_attach_registers(node, (u32)minor);
mutex_unlock(&nv_rs_rmapi_lock);
return result;
}
void nv_rs_rmapi_kernel_close_gpu(u32 gpu_id);
void nv_rs_rmapi_kernel_close_gpu(u32 gpu_id)
{
u32 domain = (gpu_id >> 16) & 0xffffU;
u8 bus = (u8)((gpu_id >> 8) & 0xffU);
u8 slot = (u8)(gpu_id & 0xffU);
int minor;
if (!nv_rs_rmapi_state)
return;
mutex_lock(&nv_rs_rmapi_lock);
minor = nv_rs_rmapi_gpu_minor(nv_rs_rmapi_state, domain, bus, slot);
if (minor >= 0 && minor < NV_RS_RMAPI_MAX_GPUS)
nv_rs_rmapi_gpu_release(nv_rs_rmapi_state, (u32)minor);
mutex_unlock(&nv_rs_rmapi_lock);
}
u32 nv_rs_rmapi_handle_rc_fault(u32 gpu_id, u64 inst_ptr, u64 fault_va, u32 xid_code)
{
u32 chid = 0;
u32 tsg_id = 0;
u32 diag[3] = {0, 0, 0};
u32 notified = 0;
char bdf[32];
if (!nv_rs_rmapi_state || !inst_ptr)
return 0;
snprintf(bdf, sizeof(bdf), "%04x:%02x:%02x.0",
(gpu_id >> 16) & 0xffffu, (gpu_id >> 8) & 0xffu, gpu_id & 0xffu);
mutex_lock(&nv_rs_rmapi_lock);
notified = nv_rs_rmapi_rc_recover_fault(gpu_id, inst_ptr, xid_code, &chid, &tsg_id, diag);
mutex_unlock(&nv_rs_rmapi_lock);
pr_err("NVRM: Xid (PCI:%s): %u, pid=%d, name=%s, Channel %08x, TSG %u, FaultVA 0x%llx (inst=0x%llx notified=%u gr_st=0x%x ctx=0x%x eng=0x%x)\n",
bdf, xid_code, task_pid_nr(current), current->comm,
chid, tsg_id, (unsigned long long)fault_va,
(unsigned long long)inst_ptr, notified, diag[0], diag[1], diag[2]);
return notified;
}
static void nv_rs_rmapi_probe_cpu_info(void *state)
{
#if defined(CONFIG_X86) || defined(CONFIG_ARM64)
struct nv_rs_rmapi_cpu_info info;
u32 logical = num_online_cpus();
u32 physical;
memset(&info, 0, sizeof(info));
if (logical == 0)
logical = 1;
#ifdef CONFIG_SMP
{
u32 siblings = cpumask_weight(topology_sibling_cpumask(0));
physical = siblings > 1 ? max(1U, logical / siblings) : logical;
}
#else
physical = logical;
#endif
info.num_logical_cpus = logical;
info.num_physical_cpus = physical;
info.cores_on_die = physical;
info.data_cache_line_bytes = (u32)cache_line_size();
#ifdef CONFIG_X86
{
const struct cpuinfo_x86 *c = &boot_cpu_data;
u32 caps = 0;
if (c->x86_vendor == X86_VENDOR_AMD)
info.cpu_type = c->x86 >= 0x17 ? 0x38U : 0x36U; /* RYZEN / K10 */
else if (c->x86_vendor == X86_VENDOR_INTEL)
info.cpu_type = 0x10U; /* CORE2 */
else
info.cpu_type = 0U; /* UNKNOWN */
if (boot_cpu_has(X86_FEATURE_MMX))
caps |= 0x00000001U;
if (boot_cpu_has(X86_FEATURE_XMM))
caps |= 0x00000002U;
if (boot_cpu_has(X86_FEATURE_XMM2))
caps |= 0x00000008U | 0x00000010U; /* SSE2 | SFENCE */
if (boot_cpu_has(X86_FEATURE_PAT) || boot_cpu_has(X86_FEATURE_MTRR))
caps |= 0x00000020U; /* WRITE_COMBINING */
if (boot_cpu_has(X86_FEATURE_CMOV))
caps |= 0x00000800U;
if (boot_cpu_has(X86_FEATURE_CLFLUSH))
caps |= 0x00001000U;
if (boot_cpu_has(X86_FEATURE_XMM3))
caps |= 0x00004000U;
if (boot_cpu_has(X86_FEATURE_HT))
caps |= 0x00010000U;
if (boot_cpu_has(X86_FEATURE_XMM4_1))
caps |= 0x00020000U;
if (boot_cpu_has(X86_FEATURE_XMM4_2))
caps |= 0x00040000U;
if (boot_cpu_has(X86_FEATURE_AVX))
caps |= 0x00080000U;
if (boot_cpu_has(X86_FEATURE_ERMS))
caps |= 0x00100000U;
info.capabilities = caps;
if (tsc_khz > 0)
info.clock_mhz = tsc_khz / 1000U;
else if (cpu_khz > 0)
info.clock_mhz = cpu_khz / 1000U;
if (c->x86_cache_size > 0)
info.l2_data_cache_kb = (u32)c->x86_cache_size;
if (c->x86_clflush_size > 0)
info.data_cache_line_bytes = (u32)c->x86_clflush_size;
strscpy((char *)info.name, c->x86_model_id, sizeof(info.name));
info.family = (u32)c->x86;
info.model = (u32)c->x86_model;
info.stepping = (u8)c->x86_stepping;
}
#elif defined(CONFIG_ARM64)
info.cpu_type = 0xA00FF000U; /* ARMV8A_GENERIC */
strscpy((char *)info.name, "aarch64", sizeof(info.name));
#endif
nv_rs_rmapi_set_cpu_info(state, &info);
#else
(void)state;
#endif
}
int nv_rs_rmapi_node_init(void)
{
void *state;
int result;
if (nv_rs_rmapi_state_align() > ARCH_KMALLOC_MINALIGN ||
nv_rs_rmapi_state_size() > 8 * 1024 * 1024)
return -EINVAL;
state = kvzalloc(nv_rs_rmapi_state_size(), GFP_KERNEL);
if (!state)
return -ENOMEM;
nv_rs_ext_release_wq = alloc_workqueue("nv_rs_ext_rel", WQ_UNBOUND, 0);
if (!nv_rs_ext_release_wq) {
kvfree(state);
return -ENOMEM;
}
result = nv_rs_rmapi_init(state);
if (result) {
destroy_workqueue(nv_rs_ext_release_wq);
nv_rs_ext_release_wq = NULL;
kvfree(state);
return result;
}
{
unsigned long flags;
spin_lock_irqsave(&nv_rs_gpu_nice_sched_lock, flags);
atomic_set(&nv_rs_gpu_nice_stopping, 0);
spin_unlock_irqrestore(&nv_rs_gpu_nice_sched_lock, flags);
}
(void)nv_rs_gpu_nice_set_policy(state,
gpu_nice_auto ? 1 : 0,
gpu_desktop_boost ? 1 : 0,
1,
false);
{
/* The chipset input of the host capabilities: the first host bridge the PCI core
* lists (configuration ids only; nothing of a GPU is touched). */
struct pci_dev *bridge = pci_get_class(PCI_CLASS_BRIDGE_HOST << 8, NULL);
if (bridge) {
nv_rs_rmapi_set_host_bridge(state, bridge->vendor, bridge->device);
pci_dev_put(bridge);
}
nv_rs_rmapi_probe_cpu_info(state);
nv_rs_rmapi_set_force_p2p(state, force_p2p);
if (!nv_rs_rmapi_set_gsp_abi(gsp_abi))
pr_warn("nvidia_rs: gsp_abi=%u is not 580 or 620, keeping the default GSP-RM ABI\n",
gsp_abi);
nv_rs_rmapi_set_strict_version_check(strict_version_check);
nv_rs_rmapi_set_driver_version(driver_version ? driver_version : "",
driver_version ? strlen(driver_version) : 0);
}
nv_rs_rmapi_state = state;
result = misc_register(&nv_rs_rmapi_device);
if (result) {
nv_rs_rmapi_state = NULL;
if (nv_rs_ext_release_wq) {
destroy_workqueue(nv_rs_ext_release_wq);
nv_rs_ext_release_wq = NULL;
}
kvfree(state);
} else {
if (compat_chardev_major) {
dev_t ctl_dev = MKDEV(NV_RS_COMPAT_MAJOR, NV_RS_COMPAT_CTL_MINOR);
dev_t gpu_dev = MKDEV(NV_RS_COMPAT_MAJOR, 0);
#if defined(NV_RS_CLASS_CREATE_NO_OWNER) || (!defined(NV_RS_KBUILD_PROBED) && LINUX_VERSION_CODE >= KERNEL_VERSION(6, 4, 0))
nv_rs_compat_class = class_create("nvidia-rs-compat");
#else
nv_rs_compat_class = class_create(THIS_MODULE, "nvidia-rs-compat");
#endif
if (IS_ERR(nv_rs_compat_class)) {
pr_warn("nvidia_rs: compat class_create failed (%ld)\n",
PTR_ERR(nv_rs_compat_class));
nv_rs_compat_class = NULL;
} else {
nv_rs_compat_class->devnode = nv_rs_compat_devnode;
if (register_chrdev_region(ctl_dev, 1, "nvidia-ctl") == 0) {
cdev_init(&nv_rs_compat_ctl_cdev, &nv_rs_rmapi_operations);
nv_rs_compat_ctl_cdev.owner = THIS_MODULE;
if (cdev_add(&nv_rs_compat_ctl_cdev, ctl_dev, 1) == 0) {
struct device *d = device_create(nv_rs_compat_class, NULL, ctl_dev,
NULL, "nvidiactl");
if (!IS_ERR(d)) {
nv_rs_compat_ctl_registered = true;
} else {
cdev_del(&nv_rs_compat_ctl_cdev);
unregister_chrdev_region(ctl_dev, 1);
}
} else {
unregister_chrdev_region(ctl_dev, 1);
}
} else {
pr_warn("nvidia_rs: major 195:255 already in use, skipping compat /dev/nvidiactl\n");
}
if (register_chrdev_region(gpu_dev, NV_RS_RMAPI_MAX_GPUS, "nvidia-gpu") == 0) {
cdev_init(&nv_rs_compat_gpu_cdev, &nv_rs_rmapi_gpu_operations);
nv_rs_compat_gpu_cdev.owner = THIS_MODULE;
if (cdev_add(&nv_rs_compat_gpu_cdev, gpu_dev, NV_RS_RMAPI_MAX_GPUS) == 0) {
nv_rs_compat_gpu_registered = true;
} else {
unregister_chrdev_region(gpu_dev, NV_RS_RMAPI_MAX_GPUS);
}
} else {
pr_warn("nvidia_rs: major 195:0..%u already in use, skipping compat /dev/nvidia*\n",
NV_RS_RMAPI_MAX_GPUS - 1);
}
}
}
nv_rs_proc_init();
}
return result;
}
void nv_rs_rmapi_node_exit(void)
{
if (!nv_rs_rmapi_state)
return;
#ifndef NV_RS_PCI_TEST_EDU
/* the GPUs (and their interrupts) are gone: no IRQ thread schedules the RM-event retry any more */
cancel_delayed_work_sync(&nv_rs_rmapi_events_retry);
#endif
{
unsigned long flags;
spin_lock_irqsave(&nv_rs_gpu_nice_sched_lock, flags);
atomic_set(&nv_rs_gpu_nice_stopping, 1);
spin_unlock_irqrestore(&nv_rs_gpu_nice_sched_lock, flags);
}
/* Deregistration waits for no one: open files pin the module, so none exist here. The
* PCI driver removes its GPUs' device nodes before this runs; a node that is still
* live is removed here. */
{
int gpu;
for (gpu = 0; gpu < NV_RS_RMAPI_MAX_GPUS; gpu++) {
if (nv_rs_rmapi_gpu_nodes[gpu].live) {
nv_rs_rmapi_gpu_nodes[gpu].live = false;
nv_rs_rmapi_gpu_nodes[gpu].generation++;
if (nv_rs_compat_gpu_registered && nv_rs_compat_class)
device_destroy(nv_rs_compat_class, MKDEV(NV_RS_COMPAT_MAJOR, (unsigned int)gpu));
misc_deregister(&nv_rs_rmapi_gpu_nodes[gpu].misc);
if (nv_rs_rmapi_gpu_nodes[gpu].release)
nv_rs_rmapi_gpu_nodes[gpu].release(nv_rs_rmapi_gpu_nodes[gpu].cookie);
nv_rs_rmapi_gpu_nodes[gpu].read32 = NULL;
nv_rs_rmapi_gpu_nodes[gpu].release = NULL;
}
}
}
nv_rs_proc_exit();
if (nv_rs_compat_gpu_registered) {
cdev_del(&nv_rs_compat_gpu_cdev);
unregister_chrdev_region(MKDEV(NV_RS_COMPAT_MAJOR, 0), NV_RS_RMAPI_MAX_GPUS);
nv_rs_compat_gpu_registered = false;
}
if (nv_rs_compat_ctl_registered) {
device_destroy(nv_rs_compat_class, MKDEV(NV_RS_COMPAT_MAJOR, NV_RS_COMPAT_CTL_MINOR));
cdev_del(&nv_rs_compat_ctl_cdev);
unregister_chrdev_region(MKDEV(NV_RS_COMPAT_MAJOR, NV_RS_COMPAT_CTL_MINOR), 1);
nv_rs_compat_ctl_registered = false;
}
if (nv_rs_compat_class) {
class_destroy(nv_rs_compat_class);
nv_rs_compat_class = NULL;
}
misc_deregister(&nv_rs_rmapi_device);
cancel_delayed_work_sync(&nv_rs_gpu_nice_work);
/* Every file is released by now, and with it every client and its memory objects: the
* Rust registry is empty and no record exists. Anything else is a leak: report and drain. */
{
u64 leaked = nv_rs_alloc_reg_total_pages();
void *rem;
if (leaked)
pr_err("nvidia_rs: rmapi memory: %llu pages still allocated at node exit\n",
leaked);
while ((rem = nv_rs_alloc_reg_pop_any()) != NULL)
nv_rs_rmapi_alloc_destroy(rem);
nv_rs_alloc_reg_release_storage();
}
if (nv_rs_ext_release_wq) {
destroy_workqueue(nv_rs_ext_release_wq);
nv_rs_ext_release_wq = NULL;
}
/* every dma-buf is released (each holds the module); drop the pins the last ones handed back */
nv_rs_dmabuf_flush_unpins();
nv_rs_rmapi_close(nv_rs_rmapi_state, U64_MAX);
nv_rs_rmapi_trim_page_pools(0);
mutex_lock(&nv_rs_sysmem_pool_lock);
nv_rs_sysmem_pool_release_storage();
mutex_unlock(&nv_rs_sysmem_pool_lock);
kvfree(nv_rs_rmapi_state);
nv_rs_rmapi_state = NULL;
if (atomic64_read(&nv_rs_rmapi_kvalloc_live) != 0)
pr_err("nvidia_rs: rmapi slab: %lld dynamic allocations still live at node exit\n",
(long long)atomic64_read(&nv_rs_rmapi_kvalloc_live));
}