Motivation

I was analyzing the executable produced by nvcc when compiling CUDA C++ code containing a simple vector addition kernel. At some point, out of curiosity, I wanted to check how the CUDA Driver API communicates with the GPU device. Specifically, what Linux kernel system calls are used for this communication.

Analysis

Analyzing static/dynamic linkages

The CUDA Driver API is a user-space program whereas the GPU device, just as other peripheral device, is managed by the Linux kernel. Let us start by writing the kernel:

#include <iostream>
#include <cuda_runtime.h>
 
__global__ void addVectors(
    const float* vecA,
    const float* vecB,
    float* sum,
    long n
) {
    int globalIdx = blockIdx.x * blockDim.x + threadIdx.x;
    if (globalIdx < n) {
        sum[globalIdx] = vecA[globalIdx] + vecB[globalIdx];
    }
}
 
int main() {
    long n = 1000000;
    long vecSize = n * sizeof(float);
    float* hostVecA = new float[n];
    float* hostVecB = new float[n];
    for (int i = 0; i < n; i++) {
        hostVecA[i] = 1.0f;
        hostVecB[i] = 2.0f;
    }
    float* hostSum = new float[n]{0};
    float* deviceVecA;
    float* deviceVecB;
    float* deviceSum;
    cudaMalloc(&deviceVecA, vecSize);
    cudaMalloc(&deviceVecB, vecSize);
    cudaMalloc(&deviceSum, vecSize);
    cudaMemcpy(deviceVecA, hostVecA, vecSize, cudaMemcpyHostToDevice);
    cudaMemcpy(deviceVecB, hostVecB, vecSize, cudaMemcpyHostToDevice);
    int threadsPerBlock = 256;
    int blocksPerGrid = (n + threadsPerBlock - 1) / threadsPerBlock;
    addVectors<<<blocksPerGrid, threadsPerBlock>>>(deviceVecA, deviceVecB, deviceSum, n);
    cudaDeviceSynchronize();
 
    cudaMemcpy(hostSum, deviceSum, vecSize, cudaMemcpyDeviceToHost);
 
    for (int i = 0; i < 10; i++) {
        std::cout << hostSum[i] << ' ';
    }
    std::cout << '\n';
    return 0;
}

We compile it with nvcc:

nvcc vecadd.cu -o vecadd

Checking file details of the executable vecadd with file:

$ file vecadd
vecadd: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=44f7dc1517f5c5b8760cb08a5d1cda3cf2c6ac43, for GNU/Linux 3.2.0, not stripped

Let us check the dynamic linkages of the executable with ldd:

$ ldd vecadd
	linux-vdso.so.1 (0x00007ffcfacf0000)
	libstdc++.so.6 => /lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007ed05be81000)
	libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007ed05be53000)
	libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007ed05bc40000)
	/lib64/ld-linux-x86-64.so.2 (0x00007ed05c1be000)
	libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007ed05bb57000)

There seem to be no dynamic linkages connecting vecadd with CUDA or Nvidia shared libraries. Let us check the symbols present in the executable and look for cuda in their names:

$ nm vecadd | grep "cuda" | head -n 20
000000000004fbb0 T cudaArrayGetInfo
0000000000050050 T cudaArrayGetMemoryRequirements
000000000004fe20 T cudaArrayGetPlane
00000000000504b0 T cudaArrayGetSparseProperties
00000000000449c0 T cudaChooseDevice
000000000005a170 T cudaCreateChannelDesc
000000000005ae40 T cudaCreateSurfaceObject
000000000005a3f0 T cudaCreateTextureObject
0000000000046590 T cudaCtxResetPersistingL2Cache
0000000000049f40 T cudaDestroyExternalMemory
000000000004a7b0 T cudaDestroyExternalSemaphore
000000000005b050 T cudaDestroySurfaceObject
000000000005a660 T cudaDestroyTextureObject
0000000000058ae0 T cudaDeviceCanAccessPeer
0000000000058ef0 T cudaDeviceDisablePeerAccess
0000000000058cf0 T cudaDeviceEnablePeerAccess
0000000000042460 T cudaDeviceFlushGPUDirectRDMAWrites
00000000000438b0 T cudaDeviceGetAttribute
0000000000041570 T cudaDeviceGetByPCIBusId
0000000000040fa0 T cudaDeviceGetCacheConfig

It looks like libcudart is statically linked to the executable. Static linking means that the compiled code of CUDA Runtime and CUDA Driver API is a part of the executable, rather than only containing references to them (which is the case in dynamic linking). According to this answer, static linking of CUDA Runtime is the default behavior of nvcc.

Analyzing System Calls

Let us now use strace to determine which system calls were invoked when running the executable vecadd:

$ strace -c ./vecadd
3 3 3 3 3 3 3 3 3 3 
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- -----------------------
 97.81    0.322083         483       666           ioctl
  1.15    0.003796          29       129           mmap
  0.34    0.001117           8       128        18 openat
  0.10    0.000317           3        90           fcntl
  0.09    0.000301           6        45           read
  0.09    0.000297           3        91           close
  0.08    0.000261           7        33         8 stat
  0.08    0.000254           4        63           brk
  0.05    0.000156           7        20           write

The executable spends most of its time invoking the ioctl system call. This was a new system call for me and it was not known to me before. Checking man ioctl leads to the following description:

     The ioctl() function manipulates the underlying device parameters of
     special files.  In particular, many operating characteristics of
     character special files (e.g. terminals) may be controlled with ioctl()
     requests.  The argument fildes must be an open file descriptor.rs of
     special files.  In particular, many operating characteristics of
     An  ioctl request has encoded in it whether the argument is an “in”tl()
     parameter or “out” parameter, and the size of the argument argp in bytes.
     Macros and defines used in specifying an ioctl request are located in the
     file ⟨sys/ioctl.h⟩.as encoded in it whether the argument is an “in”
     parameter or “out” parameter, and the size of the argument argp in bytes.

The function prototype looks like:

       #include <sys/ioctl.h>

       int ioctl(int fd, unsigned long op, ...);  /* glibc, BSD */
       int ioctl(int fd, int op, ...);            /* musl, other UNIX */

With ioctl, a programmer can control an IO device by passing in the device’s file-descriptor (fd) and an unsigned long variable op indicating the operation that the IO device will perform when this system call is invoked. The Wikipedia page also has some nice information:

Userspace applications typically make requests to the kernel by means of system calls, whose code lies in the kernel layer. A system call usually takes the form of a “system call vector”, in which the desired system call is indicated with an index number. For instance, exit() might be system call number 1, and write() number 4. The system call vector is then used to find the desired kernel function for the request. In this way, conventional operating systems typically provide several hundred system calls to the userspace.

Though an expedient design for accessing standard kernel facilities, system calls are sometimes inappropriate for accessing non-standard hardware peripherals. By necessity, most hardware peripherals (aka devices) are directly addressable only within the kernel. But user code may need to communicate directly with devices; for instance, an administrator might configure the media type on an Ethernet interface. Modern operating systems support diverse devices, many of which offer a large collection of facilities. Some of these facilities may not be foreseen by the kernel designer, and as a consequence it is difficult for a kernel to provide system calls for using the devices.

To solve this problem, the kernel is designed to be extensible, and may accept an extra module called a device driverwhich runs in kernel space and can directly address the device. An ioctl interface is a single system call by which userspace may communicate with device drivers. Requests on a device driver are vectored with respect to this ioctlsystem call, typically by a handle to the device and a request number. The basic kernel can thus allow the userspace to access a device driver without knowing anything about the facilities supported by the device, and without needing an unmanageably large collection of system calls.

This means ioctl must be communicating with some device driver that manages the Nvidia GPU. This device driver is not a part of the kernel itself, but extends it with additional capabilities. Before diving into this kernel extension, let us first see what file-descriptors does vecadd hold when executing. This will help us check which fd is being passed to the ioctl invocation.

I added the following line before return 0; in the kernel to ensure the process does not exit before I can check the file-descriptors held by the vecadd process.

#include <thread>
// wait for 2 seconds
std::this_thread::sleep_for(std::chrono::seconds(2));
$ ./vecadd
$ ps aux | grep "aux" # get the pid
$ lsof -p <pid>

List of file-descriptors held by the process:

COMMAND   PID USER   FD      TYPE             DEVICE SIZE/OFF    NODE NAME
vecadd  42582 root  cwd       DIR               0,56     4096 7340038 /content
vecadd  42582 root  rtd       DIR               0,56     4096 5242913 /
vecadd  42582 root  txt       REG               0,56   995104 5248604 /content/vecadd
vecadd  42582 root  mem       CHR              195,0               14 /dev/nvidia0
vecadd  42582 root  mem       CHR            195,255               15 /dev/nvidiactl
vecadd  42582 root  mem       CHR              241,0               12 /dev/nvidia-uvm
vecadd  42582 root  mem       REG                7,0          5248604 /content/vecadd (path dev=0,56)
vecadd  42582 root  DEL       REG                0,1             5132 /dev/zero
vecadd  42582 root  DEL       REG                0,1             5133 /dev/zero
vecadd  42582 root  DEL       REG                0,1             5135 /dev/zero
vecadd  42582 root  DEL       REG                0,1             5134 /dev/zero
vecadd  42582 root  mem       REG                8,1 96276264  143973 /usr/lib64-nvidia/libcuda.so.580.82.07
vecadd  42582 root  mem       REG                7,0          1737206 /usr/lib/x86_64-linux-gnu/librt.so.1 (path dev=0,56)
vecadd  42582 root  mem       REG                7,0          1737158 /usr/lib/x86_64-linux-gnu/libpthread.so.0 (path dev=0,56)
vecadd  42582 root  mem       REG                7,0          1736407 /usr/lib/x86_64-linux-gnu/libdl.so.2 (path dev=0,56)
vecadd  42582 root  mem       REG                7,0          1736803 /usr/lib/x86_64-linux-gnu/libm.so.6 (path dev=0,56)
vecadd  42582 root  mem       REG                7,0          1736315 /usr/lib/x86_64-linux-gnu/libc.so.6 (path dev=0,56)
vecadd  42582 root  mem       REG                7,0          1311630 /usr/lib/x86_64-linux-gnu/libgcc_s.so.1 (path dev=0,56)
vecadd  42582 root  mem       REG                7,0          1311698 /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.33 (path dev=0,56)
vecadd  42582 root  mem       REG                7,0          1736120 /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 (path dev=0,56)
vecadd  42582 root    0u      CHR              136,2      0t0       5 /dev/pts/2
vecadd  42582 root    1u      CHR              136,2      0t0       5 /dev/pts/2
vecadd  42582 root    2u      CHR              136,2      0t0       5 /dev/pts/2
vecadd  42582 root    3u  a_inode               0,15        0    2057 [eventfd:49]
vecadd  42582 root    4r     FIFO               0,14      0t0  579355 pipe
vecadd  42582 root    5w     FIFO               0,14      0t0  579355 pipe
vecadd  42582 root    6r     FIFO               0,14      0t0  579356 pipe
vecadd  42582 root    7w     FIFO               0,14      0t0  579356 pipe
vecadd  42582 root    8u      CHR            195,255      0t0      15 /dev/nvidiactl
vecadd  42582 root    9u      CHR              241,0      0t0      12 /dev/nvidia-uvm
vecadd  42582 root   10u      CHR              241,0      0t0      12 /dev/nvidia-uvm
vecadd  42582 root   11u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   12u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   13u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   14u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   15u     unix 0x0000000000000000      0t0  579365 @cuda-uvmfd-4026532689-42582@ type=SEQPACKET (LISTEN)
vecadd  42582 root   16u  a_inode               0,15        0    2057 [eventfd:50]
vecadd  42582 root   17u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   18u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   19u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   20u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   21u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   22u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   23u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   24u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   25u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   26u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   27u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   28u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   29u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   30u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   31u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   32u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   33u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   34u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   35u  a_inode               0,15        0    2057 [eventfd:52]
vecadd  42582 root   36u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   37u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   38u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   39u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   40u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   41u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   42u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   43u      CHR              195,0      0t0      14 /dev/nvidia0
vecadd  42582 root   44r     FIFO               0,14      0t0  579368 pipe
vecadd  42582 root   45w     FIFO               0,14      0t0  579368 pipe

With strace we can further print each ioctl invocation:

strace -e ioctl ./vecadd

The most common invocations that we can observe is:

ioctl(8, _IOC(_IOC_READ|_IOC_WRITE, 0x46, 0x2a, 0x20), 0x7fff9af77fc0) = 0
ioctl(8, _IOC(_IOC_READ|_IOC_WRITE, 0x46, 0x2a, 0x20), 0x7fff9af78070) = 0
ioctl(8, _IOC(_IOC_READ|_IOC_WRITE, 0x46, 0x2a, 0x20), 0x7fff9af78110) = 0
ioctl(8, _IOC(_IOC_READ|_IOC_WRITE, 0x46, 0x2b, 0x30), 0x7fff9af78640) = 0

The fd of 8 corresponds to the nvidiactl device, as observed from the list of open file-descriptors above. The arg parameter, which is, 0x7fff9ef27190, in the first line above, points to an opaque structure in the host memory that the kernel driver reads. This structure contains additional details of the operation that has to be performed. Assuming the arg parameters as seen above, like, 0x7fff9af78110, is a pointer to user-space memory, let us check the virtual address space of the process for this pointer:

0000716c0eca8000      8K r---- ld-linux-x86-64.so.2
0000716c0ecaa000      8K rw--- ld-linux-x86-64.so.2
00007fff9af5b000    132K rw---   [ stack ]
00007fff9afb7000     16K r----   [ anon ]
00007fff9afbb000      8K r-x--   [ anon ]
ffffffffff600000      4K --x--   [ anon ]

As we observe, the address 0x7fff9af78110 becomes to the stack memory of the process. Meaning, some structure has been initialized at this address in the stack memory, and this structure is being read by the kernel driver through the ioctl system calls. The ioctl system calls are intercepted by the Nvidia kernel modules. As mentioned in linux-kernel-labs.github.io

A kernel module (or loadable kernel mode) is an object file that contains code that can extend the kernel functionality at runtime (it is loaded as needed); When a kernel module is no longer needed, it can be unloaded. Most of the device drivers are used in the form of kernel modules.

We can check this ourselves using the lsmod utility in Google Colab (with GPU runtime):

lsmod
Module                  Size  Used by
veth                   36864  0
xt_nat                 12288  12
nvidia_drm            135168  0
drm_kms_helper        188416  1 nvidia_drm
nvidia_modeset       1916928  1 nvidia_drm
nvidia_uvm           1871872  0
nvidia              15151104  7 nvidia_uvm,nvidia_modeset
drm                   679936  4 drm_kms_helper,nvidia,nvidia_drm
i2c_core              102400  3 drm_kms_helper,nvidia,drm
drm_panel_orientation_quirks    28672  1 drm
cls_u32                32768  2
sch_htb                36864  1
nft_chain_nat          12288  6
xt_MASQUERADE          12288  2
nf_nat                 53248  3 xt_nat,nft_chain_nat,xt_MASQUERADE
xt_addrtype            12288  2
nft_compat             20480  21
nf_tables             344064  374 nft_compat,nft_chain_nat
crc32c_intel           16384  6
aesni_intel           360448  0
crypto_simd            16384  1 aesni_intel
virtio_balloon         24576  0
cryptd                 28672  1 crypto_simd
loadpin_trigger         8192  0
fuse                  184320  3

The code for those nvidia-* kernel modules is open-sourced by Nvidia at open-gpu-kernel-modules on GitHub.

Nvidia GPU Kernel Modules

The nvidia kernel module registers the two devices /dev/nvidia and /dev/nvidiactl that we saw in the list of file-descriptors held by the process running the vecadd program in file nv.c:

/*  
 * Register char devices for both the region of regular devices  
 * as well as the control device.  
 *  
 * NOTE: THIS SHOULD BE DONE LAST.  
 */  
rc = nv_register_chrdev(0, NV_MINOR_DEVICE_NUMBER_REGULAR_MAX + 1,  
        &nv_linux_devices_cdev, "nvidia", &nvidia_fops);  
if (rc < 0)  
{  
    goto drivers_exit;  
}  
  
rc = nv_register_chrdev(NV_MINOR_DEVICE_NUMBER_CONTROL_DEVICE, 1,  
        &nv_linux_control_device_cdev, "nvidiactl", &nvidia_fops);  
if (rc < 0)  
{  
    goto partial_chrdev_exit;  
}

The nv_register_chrdev registers a character (chr) device at /dev/nvidia and /dev/nvidiactl with the given nvidia_fops (instance of file_operations). The structure file_operations comes from the Linux kernel (linux/fs.h) and controls how the device will implement system calls like mmap, open and the one we are interested in, ioctl. The structure holds function pointers for each system call as described in Linux Kernel Module Programming Guide:

    struct file_operations {
       struct module *owner;
       loff_t (*llseek) (struct file *, loff_t, int);
       ssize_t (*read) (struct file *, char *, size_t, loff_t *);
       ssize_t (*write) (struct file *, const char *, size_t, loff_t *);
       int (*readdir) (struct file *, void *, filldir_t);
       unsigned int (*poll) (struct file *, struct poll_table_struct *);
       int (*ioctl) (struct inode *, struct file *, unsigned int, unsigned long);
       int (*mmap) (struct file *, struct vm_area_struct *);
       int (*open) (struct inode *, struct file *);
       int (*flush) (struct file *);
       int (*release) (struct inode *, struct file *);
       int (*fsync) (struct file *, struct dentry *, int datasync);
       int (*fasync) (int, struct file *, int);
       int (*lock) (struct file *, int, struct file_lock *);
    	 ssize_t (*readv) (struct file *, const struct iovec *, unsigned long,
          loff_t *);
    	 ssize_t (*writev) (struct file *, const struct iovec *, unsigned long,
          loff_t *);
    };

The file_operations structure is defined in linux/fs.h, and holds pointers to functions defined by the driver that perform various operations on the device. Each field of the structure corresponds to the address of some function defined by the driver to handle a requested operation.

In the Nvidia kernel modules, the following instance of file_operations is passed to register_chrdev:

/* character device entry points*/
static struct file_operations nvidia_fops = {
    .owner     = THIS_MODULE,
    .poll      = nvidia_poll,
    .unlocked_ioctl = nvidia_unlocked_ioctl,
#if NVCPU_IS_X86_64 || NVCPU_IS_AARCH64
    .compat_ioctl = nvidia_unlocked_ioctl,
#endif
    .mmap      = nvidia_mmap,
    .open      = nvidia_open,
    .release   = nvidia_close,
};

Instead of .ioctl, the nvidia_fops object contains implementations for .unlocked_ioctl and .compact_ioctl (for x64 and arm64 devices). Exploring the difference between unlocked_ioctl and ioctl brings us to the following SO answer:

Explanation: When ioctl was executed, it took the Big Kernel Lock (BKL), so nothing else could execute at the same time. This is very bad on a multiprocessor machine, so there was a big effort to get rid of the BKL. First, unlocked_ioctl was introduced. It lets each driver writer choose what lock to use instead. This can be difficult, so there was a period of transition during which old drivers still worked (using ioctl) but new drivers could use the improved interface (unlocked_ioctl). Eventually all drivers were converted and ioctl could be removed.

The same SO answer also explains what compact_ioctl means:

compat_ioctl is actually unrelated, even though it was added at the same time. Its purpose is to allow 32-bit userland programs to make ioctl calls on a 64-bit kernel. The meaning of the last argument to ioctl depends on the driver, so there is no way to do a driver-independent conversion.

The reasons to use unlocked_ioctl and compact_ioctl seem to be closely related to the internal machinery of the Linux kernel, hence we can treat them as ioctl calls in our mental model of understanding how userspace CUDA programs communicate with Nvidia GPUs.

Tracing the nvidia_unlocked_ioctl call

Let us check what nvidia_unlocked_ioctl does when invoked for the .unlocked_ioctl operation. Within the kernel module, the following chain of functions is called for allocating memory on the GPU device (VRAM/Video RAM):

userspace ioctl()
  └─ nvidia_unlocked_ioctl / nvidia_ioctl        (nv.c: validate, copy_from_user, altstack)
       └─ rm_ioctl → RmIoctl                     (osapi.c → escape.c: RM runtime & secInfo)
            └─ rmapiAllocWithSecInfoTls          (alloc_free.c: TLS, locks, Resource Server)
                 └─ vidmemConstruct_IMPL         (video_mem.c: PMA/heap VRAM reservation)
                      └─ NV_RM_RPC_ALLOC_MEMORY  (mem.c: serialize RPC for GSP-RM)
                           └─ GspMsgQueueSendCommand → WRITE_REG(regTxHead)  (PCIe MMIO → GSP)
  • The control flow enters an important component of the kernel module, called RM (Resource Manager), that manages the resources of the GPU device.
  • GPUs following the Nvidia Turing and newer architectures include a GSP (GPU System Processor) which is a RISC-V CPU within the GPU device. GPU initialization and management operations for offloaded to the GSP. The GSP uses a proprietary firmware embedded within the GPU device.
  • The messages from the CPU (kernel module) to the GSP are sent via RPC (Remote Procedure Call).

The RPC system consists of two queues, a command and a status queue. These queues are present in the region of memory shared by the GPU and the CPU.

When submitting a message to the queue, the txWritePtr is incremented and written in the NV_PGSP_QUEUE_HEAD(i) registers of the GPU device. These registers (physically present in the GPU device) are memory-mapped to shared region where the CPU writes in them. A similar register, NV_PGSP_QUEUE_TAIL tell the GSP where the tail of the queue is in CPU’s RAM (shared region). These registers are architecture-specific present in the swref directory of the project.

WRITE_REG(pQueue->pGpu, pQueue->regTxHead, pQueue->txWritePtr);

In Linux, the shared memory region where the CPU and GPU collaborate is defined the BAR registers. The registers hold addresses of the shared memory region. Any read/write to this region will be physically communicated via the PCIe bus. The following SO answer summarizes it well.

  1. When the CPU’s MMIO write lands in NV_PGSP_QUEUE_HEAD, the GPU hardware raises an interrupt on the GSP.
  2. The GSP wakes up, DMA-reads the new command elements from host RAM over PCIe, executes the RPC in firmware RM, DMA-writes the response into the Status Queue in host RAM, and updates NV_PGSP_MSGQ_HEAD.
  3. The CPU then reads the response from host RAM and advances NV_PGSP_MSGQ_TAIL via another BAR0 MMIO write.

This shared memory + interrupts mechanism is used by the GPU and CPU to pass data/commands back-and-forth.

Conclusion

Understanding how a Nvidia GPU communicates with the driver and userspace programs is a good exercise to understand different OS and Linux concepts. The following concepts were covered:

  1. System calls in Linux, specifically ioctl
  2. Userspace vs. kernel drivers
  3. Messages queues for GSP and PCIe communication

Have a nice day ahead!