aboutsummaryrefslogtreecommitdiffstats
path: root/science/linux-ai-ml-env/files/uvm_ioctl_override.c
blob: 843c8df762afbabe9a0beb7390dcac5feb98726f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Downloaded from https://gist.github.com/shkhln/40ef290463e78fb2b0000c60f4ad797e

#define _GNU_SOURCE

#include <assert.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <string.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>

// pkg install linux-c7-devtools
// /compat/linux/bin/cc --sysroot=/compat/linux -m64 -std=c99 -Wall -ldl -fPIC -shared -o dummy-uvm.so uvm_ioctl_override.c
// env LD_PRELOAD=$PWD/dummy-uvm.so <cmd>

#define NV_UVM_INITIALIZE   0x30000001
#define NV_UVM_DEINITIALIZE 0x30000002

#define NV_ERR_NOT_SUPPORTED 0x56

struct NvUvmInitParams
{
  uint64_t flags __attribute__((aligned(8)));
  uint32_t status;
};

int (*libc_ioctl)(int fd, unsigned long request, ...) = NULL;

int ioctl(int fd, unsigned long request, ...) {

  if (!libc_ioctl) {
    libc_ioctl = dlsym(RTLD_NEXT, "ioctl");
  }

  va_list _args_;
  va_start(_args_, request);
  void* data = va_arg(_args_, void*);
  va_end(_args_);

  if (request == NV_UVM_INITIALIZE) {
    struct NvUvmInitParams* params = (struct NvUvmInitParams*)data;
    params->status = NV_ERR_NOT_SUPPORTED;
    return 0;
  }

  if (request == NV_UVM_DEINITIALIZE) {
    return 0;
  }

  return libc_ioctl(fd, request, data);
}

int (*libc_open)(const char* path, int flags, ...) = NULL;

int open(const char* path, int flags, ...) {

  if (!libc_open) { libc_open = dlsym(RTLD_NEXT, "open"); }

  mode_t mode = 0;

  va_list _args_;
  va_start(_args_, flags);

  if (flags & O_CREAT) {
    mode = va_arg(_args_, int);
  }

  va_end(_args_);

  if (strcmp("/dev/nvidia-uvm", path) == 0) {
    return libc_open("/dev/null", flags, mode);
  }

  return libc_open(path, flags, mode);
}

FILE* (*libc_fopen)(const char* path, const char* mode) = NULL;

FILE* fopen(const char* path, const char* mode) {

  if (!libc_fopen) { libc_fopen = dlsym(RTLD_NEXT, "fopen"); }

  if (strncmp(path, "/proc/self/task/", sizeof("/proc/self/task/") - 1) == 0) {
    char* tail = strchr(path + sizeof("/proc/self/task/"), '/');
    if (tail != NULL && strcmp(tail, "/comm") == 0) {
      assert(strcmp(mode, "wb") == 0);
      return libc_fopen("/dev/null", mode);
    }
  }

  return libc_fopen(path, mode);
}