Files
nvdriver/kernel-open/nvidia/rmapi_node.c

3772 lines
143 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/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/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/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 "rmapi_node.h"
#include "uvm_node.h"
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;
};
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_prepare(void *node, u64 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_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);
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);
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;
};
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 bool nv_rs_file_map_get(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 pci_dev *pdev;
u32 gpu_id;
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 with the kernel's cached
* attribute: the original also changes the page attributes for the uncached and
* write-combined cache types and maps the pages for the GPU's DMA, neither is done here.
*
* 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). 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_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_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;
u64 count;
u64 encoded[]; /* 0 = unmapped; otherwise (u64)dma_addr + 1 */
};
struct nv_rs_rmapi_alloc {
u64 token, count;
u32 cache;
bool user_pinned;
bool writable;
void *kernel;
struct page *pages[];
};
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 void *nv_rs_sysmem_pool_pop(void);
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);
static DEFINE_MUTEX(nv_rs_sysmem_pool_lock);
#ifdef CONFIG_PROC_FS
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)
{
(void)v;
seq_puts(m, "ModifyDeviceFiles: 0\nDeviceFileUID: 0\nDeviceFileGID: 0\nDeviceFileMode: 438\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: nvdriver (clean-room Rust) %s (GSP-RM %s)\n",
ver, (gsp_abi == 580) ? "580.178.04" : "620.70.06");
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;
u16 did = node && node->pdev ? node->pdev->device : 0;
u32 irq = node && node->pdev ? node->pdev->irq : 0;
int rate = node ? atomic_read(&node->tensor_fp32_rate) : 0;
(void)v;
seq_printf(m, "Model: \t\t NVIDIA GPU (0x%04x)\n", did);
seq_printf(m, "IRQ: \t\t %u\n", irq);
seq_printf(m, "Bus Location: \t %s\n", node ? node->bdf : "unknown");
seq_printf(m, "Device Minor: \t %d\n", node ? node->minor_index : -1);
seq_puts(m, "Bus Type: \t PCIe\n");
seq_puts(m, "DMA Size: \t 47 bits\n");
seq_puts(m, "DMA Mask: \t 0x7fffffffffff\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("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 struct page *nv_rs_sysmem_pool_pop_page(void)
{
struct page *page;
mutex_lock(&nv_rs_sysmem_pool_lock);
page = (struct page *)nv_rs_sysmem_pool_pop();
mutex_unlock(&nv_rs_sysmem_pool_lock);
if (page)
clear_highpage(page);
return page;
}
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);
}
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_video(u32 gpu_id, u64 offset, u64 length, s32 descriptor,
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);
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].pdev) {
dev = get_device(&nv_rs_rmapi_gpu_nodes[i].pdev->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].pdev &&
&nv_rs_rmapi_gpu_nodes[i].pdev->dev == dev) {
live = true;
break;
}
}
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
return live;
}
/* 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;
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].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 (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;
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);
}
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);
}
static void nv_rs_rmapi_alloc_unmap(struct nv_rs_rmapi_alloc *alloc)
{
if (alloc->kernel && alloc->count > 1)
vunmap(alloc->kernel);
alloc->kernel = NULL;
}
/* 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;
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);
} 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);
}
/* 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. */
u32 nv_rs_rmapi_os_lock_user_pages(u64 address, u64 count, bool writable, u64 *token)
{
struct nv_rs_rmapi_alloc *alloc;
u64 pinned = 0;
u64 pool;
u64 tok = 0;
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 || (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;
while (pinned < count) {
u64 remain = count - pinned;
int chunk = remain > 1024 ? 1024 : (int)remain;
int got = pin_user_pages_fast((unsigned long)(address + (pinned << PAGE_SHIFT)),
chunk, gup_flags, &alloc->pages[pinned]);
if (got <= 0) {
if (pinned > 0)
unpin_user_pages(alloc->pages, pinned);
kvfree(alloc);
return NV_RS_STATUS_INVALID_ADDRESS;
}
pinned += (u64)got;
}
alloc->count = count;
alloc->cache = 0;
alloc->user_pinned = true;
alloc->writable = writable;
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);
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);
}
/* 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 || (contiguous && count != 1))
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;
for (index = 0; index < count; index++) {
alloc->pages[index] = nv_rs_sysmem_pool_pop_page();
if (!alloc->pages[index])
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;
}
}
alloc->count = count;
alloc->cache = cache;
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) {
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_alloc_kernel_mapping of the whole allocation: the page's own address for one page,
* vmap for more. */
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 || size > alloc->count << PAGE_SHIFT) {
rc = NV_RS_STATUS_INVALID_ARGUMENT;
} else if (!alloc->kernel) {
alloc->kernel = alloc->count == 1 ? page_address(alloc->pages[0])
: vmap(alloc->pages, alloc->count, VM_MAP, PAGE_KERNEL);
if (!alloc->kernel)
rc = NV_RS_STATUS_NO_MEMORY;
}
mutex_unlock(&nv_rs_rmapi_alloc_lock);
return rc;
}
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 = alloc->count == 1
? page_address(alloc->pages[0])
: vmap(alloc->pages, alloc->count, VM_MAP, PAGE_KERNEL);
if (!alloc->kernel)
rc = NV_RS_STATUS_NO_MEMORY;
}
if (!rc)
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
*phys = (u64)page_to_phys(alloc->pages[page_index]);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
return rc;
}
/* Resolves (and lazily IOMMU/DMA-maps) one 4 KiB page of a system-memory allocation for `gpu_id`. */
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, 47);
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 (!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;
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 (!dm->encoded[page_index]) {
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;
}
/* 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 || !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);
for (index = 0; alloc && page_index && 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 || 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;
}
/* 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)
{
struct file *target;
struct nv_rs_rmapi_file *context;
u64 io_phys = 0;
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 (!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 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;
}
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;
}
/* 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)
{
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)
{
/* misc_open left the miscdevice in private_data. */
struct nv_rs_rmapi_gpu_node *node =
container_of(file->private_data, struct nv_rs_rmapi_gpu_node, misc);
int gpu = (int)(node - nv_rs_rmapi_gpu_nodes);
struct nv_rs_rmapi_file *context = nv_rs_rmapi_context(file, gpu);
struct nv_rs_gpu_owner *owner = NULL;
int result;
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 int nv_rs_rmapi_release(struct inode *inode, struct file *file)
{
struct nv_rs_rmapi_file *context = file->private_data;
struct nv_rs_rmapi_alloc *mapped_alloc;
(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);
mapped_alloc = nv_rs_file_map_remove(context->owner);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
if (mapped_alloc)
nv_rs_rmapi_alloc_put(mapped_alloc);
mutex_unlock(&nv_rs_rmapi_lock);
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 (OUT)
* off 24: u64 totalSize (IN)
* off 552: u64 offsets[128] (IN)
* off 1576: u64 sizes[128] (IN)
* off 2600: u32 status (OUT) */
static int nv_rs_rmapi_export_dmabuf(struct file *file, u8 *top, size_t size)
{
struct nv_rs_rmapi_file *context = file->private_data;
struct pci_dev *pdev = NULL;
u64 total_size = 0, offset0 = 0, size0 = 0, export_size;
s32 fd = -1;
u32 status = 0x0000001fu; /* NV_ERR_INVALID_ARGUMENT */
int gpu;
/* Raw BAR1 range export bypasses per-client RM allocation ownership checks,
* so require CAP_SYS_ADMIN now that RMAPI device nodes are 0666. */
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (size != NV_RS_DMABUF_EXPORT_IOCTL_SIZE)
return -EINVAL;
memcpy(&total_size, top + 24, sizeof(total_size));
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) {
int res = nv_rs_dmabuf_export_bar1_fd(pdev, offset0, export_size);
if (res >= 0) {
fd = res;
status = 0;
}
}
if (pdev)
pci_dev_put(pdev);
memcpy(top, &fd, sizeof(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, *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;
struct nv_rs_rmapi_access access = { 0 };
u32 gpu_access;
int result, step;
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);
top = kmalloc(request.size ? request.size : 1, GFP_KERNEL);
if (!top)
return -ENOMEM;
if (copy_from_user(top, user, request.size)) {
kfree(top);
return -EFAULT;
}
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);
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;
}
iterate_fd(current->files, 0, nv_rs_rmapi_match_gpu, &access);
if (mutex_lock_interruptible(&nv_rs_rmapi_lock)) {
kfree(top);
return -ERESTARTSYS;
}
/* A file that registered a control file acts for it (RmIoctl: clientOSInfo is
* nvfp->ctl_nvfp when set), so that an event object can be made through a device file
* under a client of the control file. The association is written once under this lock
* and the control file is held until release. The OS event escapes are handled in
* front of that (rm_ioctl) and record the calling file itself. */
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;
gpu_access = nv_rs_rmapi_gpu_access(&access);
step = nv_rs_rmapi_prepare(nv_rs_rmapi_state, 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) {
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;
}
/* 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);
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)
pr_info_ratelimited("nvidia_rs: rt RM_CONTROL cmd=0x%x status=0x%x\n", cmd, 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. */
if (copy_to_user(user, top, request.size))
result = -EFAULT;
out:
kvfree(nested);
kvfree(params);
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 pages are always mapped
* cached (the original applies the allocation's cache type to the protection, after
* changing the pages' kernel attributes at allocation); 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 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;
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);
}
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
if (!pci && !pdev)
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);
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 || 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);
}
nv_rs_vm_flags_set(vma, VM_DONTEXPAND | VM_DONTDUMP);
vma->vm_ops = &nv_rs_rmapi_vm_operations;
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. */
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 void nv_rs_gpu_events_retry(void *node);
if (!mutex_trylock(&nv_rs_rmapi_lock)) {
schedule_delayed_work(&nv_rs_rmapi_events_retry, msecs_to_jiffies(5));
return;
}
if (nv_rs_rmapi_state)
nv_rs_gpu_events_retry(nv_rs_rmapi_state);
mutex_unlock(&nv_rs_rmapi_lock);
}
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));
}
#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(struct pci_dev *pdev, u32 boot0)
{
struct nv_rs_rmapi_gpu gpu = {
.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, .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),
.subsystem_vendor = pdev->subsystem_vendor, .subsystem = pdev->subsystem_device,
.revision = pdev->revision, .boot0 = boot0,
};
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_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 = NULL;
node->release = NULL;
node->cookie = NULL;
node->minor_index = minor;
{
unsigned long flags;
u32 gpu_id = (((u32)gpu.domain & 0xffffU) << 16) | ((u32)gpu.bus << 8) | (u32)gpu.slot;
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->pdev = pdev;
node->gpu_id = gpu_id;
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 = (boot0 >> 20 & 0x1ff) == 0x130 ||
(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) {
mutex_lock(&nv_rs_rmapi_lock);
node->generation = nv_rs_gpu_slot_deactivate((u32)minor);
node->live = false;
nv_rs_rmapi_gpu_remove(nv_rs_rmapi_state, gpu.domain, gpu.bus, gpu.slot);
mutex_unlock(&nv_rs_rmapi_lock);
return result;
}
nv_rs_modeset_register_gpu(((gpu.domain & 0xffffU) << 16) | ((u32)gpu.bus << 8) | (u32)gpu.slot,
gpu.domain, gpu.bus, gpu.slot, gpu.function, &pdev->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_reader(struct pci_dev *pdev,
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, 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) {
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_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 PCI function 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. */
void nv_rs_rmapi_node_gpu_remove(struct pci_dev *pdev)
{
void (*release)(void *cookie) = NULL;
void *cookie = NULL;
struct nv_rs_gpu_owner *owner = NULL;
u32 generation = 0;
#ifdef CONFIG_PROC_FS
struct proc_dir_entry *caps_dir = NULL;
#endif
int minor;
if (!nv_rs_rmapi_state)
return;
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));
nv_rs_rmapi_gpu_remove(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].live = false;
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 {
minor = -1;
}
mutex_unlock(&nv_rs_rmapi_lock);
if (minor >= 0) {
nv_rs_rmapi_revoke_gpu_userd(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);
nv_rs_rmapi_allocs_unmap_dev(&pdev->dev);
nv_rs_uvm_unmap_gpu_dev(&pdev->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
misc_deregister(&nv_rs_rmapi_gpu_nodes[minor].misc);
}
nv_rs_modeset_unregister_gpu((((u32)pci_domain_nr(pdev->bus) & 0xffffU) << 16) |
((u32)pdev->bus->number << 8) | (u32)PCI_SLOT(pdev->devfn));
if (release)
release(cookie);
}
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)
{
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;
result = nv_rs_rmapi_init(state);
if (result) {
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;
kvfree(state);
} else {
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++;
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();
cancel_delayed_work_sync(&nv_rs_gpu_nice_work);
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();
}
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));
}