Skip to content
Closed
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
94c0b01
add primary context accounting state
iemAnshuman Aug 3, 2026
1dc5556
measure primary context memory lazily
iemAnshuman Aug 3, 2026
a86c547
add bounded host pid broker client
iemAnshuman Aug 3, 2026
b7196ed
use the host pid broker during init
iemAnshuman Aug 3, 2026
90bdcac
enforce the host pid broker deadline
iemAnshuman Aug 3, 2026
35acc72
suppress fallback probe accounting warning
iemAnshuman Aug 3, 2026
49c754c
harden the host PID broker client
iemAnshuman Aug 5, 2026
758c2ea
harden forked process accounting
iemAnshuman Aug 5, 2026
95ecfc7
complete broker accounting lifecycle
iemAnshuman Aug 6, 2026
507d140
map visible CUDA devices by PCI identity
iemAnshuman Aug 6, 2026
c0dc37c
keep device accounting indexes explicit
iemAnshuman Aug 6, 2026
973a989
reject unaccounted primary-context retains
iemAnshuman Aug 6, 2026
e52afdf
build: remove duplicate CUDA hook source
iemAnshuman Aug 7, 2026
317553c
test: keep context accounting assertions active
iemAnshuman Aug 7, 2026
eacaafb
fix: initialize missing utilization samples
iemAnshuman Aug 7, 2026
3037196
fix: synchronize host PID monitor reset
iemAnshuman Aug 7, 2026
596e354
fix: preserve merged process memory usage
iemAnshuman Aug 7, 2026
f08b8bc
fix: bound NVML process allocation
iemAnshuman Aug 7, 2026
078a2d2
fix: bound CUDA device mapping lookups
iemAnshuman Aug 7, 2026
6d780e2
fix: set broker socket flags atomically
iemAnshuman Aug 7, 2026
ada4328
test: bound broker socket paths
iemAnshuman Aug 7, 2026
2a5a311
fix: isolate context measurement by device
iemAnshuman Aug 7, 2026
64356b9
docs: distinguish broker and fallback locking
iemAnshuman Aug 7, 2026
80771e3
docs: require cache mapping checks
iemAnshuman Aug 7, 2026
0e328a7
docs: link post init lock migration
iemAnshuman Aug 7, 2026
f65b6df
fix: use fixed width memory measurements
iemAnshuman Aug 8, 2026
3bfaf67
fix: use fixed width broker timing types
iemAnshuman Aug 8, 2026
9a5f602
fix: name broker socket path capacity
iemAnshuman Aug 8, 2026
d2d49d2
style: space CUDA mapping function brace
iemAnshuman Aug 8, 2026
08d1d90
test: use fixed width broker timing
iemAnshuman Aug 8, 2026
5a19ebf
test: bound broker directory template copy
iemAnshuman Aug 8, 2026
f60d70b
test: name overlong broker path size
iemAnshuman Aug 8, 2026
f5b2093
docs: hyphenate post init lock
iemAnshuman Aug 8, 2026
5f1c805
docs: list broker fallback conditions
iemAnshuman Aug 8, 2026
aba801d
docs: update host PID client status
iemAnshuman Aug 8, 2026
8d59bf9
docs: clarify broker mount contract
iemAnshuman Aug 8, 2026
8218aef
fix: serialize host PID fallback across caches
iemAnshuman Aug 8, 2026
e3ff7d6
test: size fallback descriptor paths safely
iemAnshuman Aug 8, 2026
b0df70a
fix: use trusted host PID fallback mount
iemAnshuman Aug 8, 2026
bc74844
fix: bound postinit lock acquisition
iemAnshuman Aug 11, 2026
17e5b8d
fix: harden host PID fallback locking
iemAnshuman Aug 11, 2026
4c8a114
test: cover host PID fallback hardening
iemAnshuman Aug 11, 2026
c302258
fix: share the host PID fallback deadline
iemAnshuman Aug 11, 2026
607d7e8
docs: describe hardened fallback locking
iemAnshuman Aug 11, 2026
ea310b1
docs: state the broker transaction timeout
iemAnshuman Aug 11, 2026
2a87ae1
docs: align fallback selection with the gate
iemAnshuman Aug 11, 2026
276e98c
test: extend the fallback lock timeout
iemAnshuman Aug 11, 2026
af203b2
test: widen the fallback deadline margin
iemAnshuman Aug 11, 2026
f62a6e9
test: guard fallback pipe cleanup
iemAnshuman Aug 11, 2026
363d46f
test: release an unexpected cache lock
iemAnshuman Aug 11, 2026
08c7542
style: fix the fallback lock header guard
iemAnshuman Aug 11, 2026
0598f11
style: order the fallback test includes
iemAnshuman Aug 11, 2026
46bccc2
test: use the cache path extent
iemAnshuman Aug 11, 2026
4421b09
style: use fixed width fallback types
iemAnshuman Aug 11, 2026
6d67df3
Merge remote-tracking branch 'origin/main' into pr251-conflict-resolu…
iemAnshuman Aug 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions docs/hostpid-broker-client.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Host PID broker client

Status: local draft. The feature is disabled by default.

## Purpose

The client lets HAMi-core learn its host PID without creating a temporary CUDA primary context during `postInit()`. It uses the version 1 Unix socket protocol documented by HAMi and preserves the existing NVML discovery path as its fallback. A successful broker lookup still initializes NVML before utilization and context accounting use it.

## Enablement

The client is enabled only when `LIBVGPU_HOSTPID_BROKER` is the exact string `1`. Every other value leaves the current behavior unchanged.

The expected container socket is fixed at `/tmp/vgpulock/hostpid/broker.sock`. A caller cannot redirect the production client to another path.

## Trust checks

Before using a reply, the client verifies all of the following:

1. The socket path is the fixed production path.

2. The immediate directory is a real directory owned by root and is not writable by group or other users.

3. The socket is a real Unix socket owned by root.

4. The directory is visible through a read only mount.

5. The connected server peer has UID 0 according to `SO_PEERCRED`.

6. The reply has the expected magic, version, success status, and a positive PID that fits in `pid_t`.

One monotonic deadline covers connect, request write, and response read. A trickle response cannot renew the deadline.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

## Fallback

If the gate is disabled or any trust, connection, deadline, or protocol check fails, `postInit()` acquires the existing process death safe lock and runs the current NVML discovery path. The broker failure does not supply a PID and does not bypass the fallback.

## CUDA context accounting

The old discovery path obtains both the host PID and the primary context size from a temporary context. The broker path skips that retain and release probe, then measures memory when the application first retains the real primary context.

After NVML starts, the broker path maps each visible CUDA device to its physical NVML index by PCI identity. This mapping does not parse `CUDA_VISIBLE_DEVICES`, so an index list and a GPU UUID use the same driver supplied identity. Devices outside the CUDA visibility set remain unmapped.

Per device limits, monitored memory, and utilization remain indexed by the visible CUDA ordinal because they describe the workload's device view. Allocation and primary context usage are indexed by physical NVML device so processes with different visibility orders still aggregate against the same GPU. Reverse lookup scans only visible CUDA devices, and an invalid or missing mapping fails closed before shared memory access.

Accounting state is kept per visible CUDA device. A nested retain adds one context charge, and the final successful release removes it. A failed add can be retried by a later retain. A failed removal stays recorded so a later retain and final release cycle can retry without adding the same charge twice. Fork handlers clear inherited accounting state and the cached parent slot before the child repeats initialization.

Hardware validation must prove that the context appears in NVML within the bounded measurement window and that the final shared region charge matches the observed primary context memory. The matrix must include a nonzero physical GPU selected by UUID and must verify the CUDA ordinal, NVML index, and primary context accounting index.

## Compatibility

1. New HAMi-core with no server uses the existing fallback.

2. Old HAMi-core ignores the new environment value and mount.

3. A rejected or unknown protocol version uses the existing fallback.

4. Existing workloads do not receive the broker mount until they are recreated.

The separate post init lock migration from PR 248 has a different mixed binary constraint and is not changed by this client.
54 changes: 54 additions & 0 deletions docs/postinit-lock-upgrade.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Post init lock upgrade contract

Status: required for upgrades across the semaphore to record lock boundary.

## Why a rolling upgrade is unsafe

Older HAMi-core processes serialize host PID discovery with
`sem_postinit`, a process shared unnamed semaphore inside the shared cache.
Newer processes keep that field for layout compatibility but serialize with a
POSIX record lock at a fixed offset in the cache file.

The two primitives do not observe each other. An old process can hold the
semaphore while a new process holds the record lock, so both can execute host
PID discovery at the same time. The cache version fields do not prevent this.
Existing binaries only report a version mismatch and continue.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

The local mixed protocol probe reproduces the overlap directly. It is under
`evidence/issue-1662/lock-benchmark/mixed_protocol_probe.c` in the companion
evidence tree.

## Required upgrade

1. Cordon the node and stop every GPU workload that can map the affected
shared cache.

2. Confirm that no old HAMi-core process still has the cache open. Check every
effective `CUDA_DEVICE_MEMORY_SHARED_CACHE` path, including generated
per-container `usage.cache` files and the `/tmp/cudevshr.cache` fallback.

3. Remove each cache only after all processes that mapped it have exited.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

4. Install one HAMi-core revision across the node.

5. Restart the device plugin and recreate workloads.

6. Validate one low-density workload before uncordoning the node. Confirm host
PID detection, memory accounting, and record lock acquisition.

Do not delete or replace a cache while a process still maps it. Unlinking the
path does not move an existing mapping to the new file and can split accounting
between two cache objects.

## Required rollback

Rollback across this boundary uses the same drain procedure. Stopping only the
device plugin is insufficient because workload processes contain HAMi-core and
retain their cache mappings.

## Deployment guarantee

The current implementation does not support a mixed-version grace period and
does not fail closed when an old process joins. Cluster rollout policy must
prevent mixed HAMi-core revisions on a shared cache. A future rolling protocol
would need an enforced version handshake that both old and new binaries obey.
2 changes: 1 addition & 1 deletion src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ add_subdirectory(cuda)
add_subdirectory(nvml)

set(LIBVGPU vgpu)
add_library(${LIBVGPU} SHARED libvgpu.c utils.c log_utils.c $<TARGET_OBJECTS:nvml_mod> $<TARGET_OBJECTS:cuda_mod> $<TARGET_OBJECTS:allocator_mod> $<TARGET_OBJECTS:multiprocess_mod>)
add_library(${LIBVGPU} SHARED libvgpu.c utils.c hostpid_broker.c log_utils.c $<TARGET_OBJECTS:nvml_mod> $<TARGET_OBJECTS:cuda_mod> $<TARGET_OBJECTS:allocator_mod> $<TARGET_OBJECTS:multiprocess_mod>)
target_compile_options(${LIBVGPU} PUBLIC ${LIBRARY_COMPILE_FLAGS})
target_link_libraries(${LIBVGPU} PUBLIC -lcuda -lnvidia-ml)

Expand Down
31 changes: 26 additions & 5 deletions src/allocator/allocator.c
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,27 @@ size_t round_up(size_t size, size_t unit) {

int oom_check(const int dev, size_t addon) {
CUdevice d;
if (dev==-1)
cuCtxGetDevice(&d);
else
unsigned int mapped_dev;

if (dev == -1) {
if (cuCtxGetDevice(&d) != CUDA_SUCCESS) {
LOG_ERROR("Unable to resolve the current CUDA device in OOM check");
return 1;
}
} else {
d=dev;
}
if (d < 0 || d >= CUDA_DEVICE_MAX_COUNT) {
LOG_ERROR("Invalid CUDA device %d in OOM check", d);
return 1;
}
mapped_dev = cuda_to_nvml_map((unsigned int)d);
if (mapped_dev >= CUDA_DEVICE_MAX_COUNT) {
LOG_ERROR("Invalid NVML mapping for CUDA device %d in OOM check", d);
return 1;
}
uint64_t limit = get_current_device_memory_limit(d);
size_t _usage = get_gpu_memory_usage(d);
size_t _usage = get_gpu_memory_usage((int)mapped_dev);

if (limit == 0) {
return 0;
Expand All @@ -60,6 +75,7 @@ int oom_check(const int dev, size_t addon) {

CUresult view_vgpu_allocator() {
allocated_list_entry *al;
unsigned int mapped_dev;
size_t total;
total=0;
LOG_INFO("[view1]:overallocated:");
Expand All @@ -68,7 +84,12 @@ CUresult view_vgpu_allocator() {
total+=al->entry->length;
}
LOG_INFO("total=%lu",total);
size_t t = get_current_device_memory_usage(0);
mapped_dev = cuda_to_nvml_map(0);
if (mapped_dev >= CUDA_DEVICE_MAX_COUNT) {
LOG_ERROR("Invalid NVML mapping for CUDA device 0");
return CUDA_ERROR_INVALID_DEVICE;
}
size_t t = get_current_device_memory_usage((int)mapped_dev);
LOG_INFO("current_device_memory_usage:%lu",t);
return 0;
}
Expand Down
2 changes: 1 addition & 1 deletion src/cuda/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
add_library(cuda_mod OBJECT context.c device.c hook.c event.c hook.c memory.c stream.c graph.c)
add_library(cuda_mod OBJECT context.c context_accounting.c device.c hook.c event.c hook.c memory.c stream.c graph.c)
target_compile_options(cuda_mod PUBLIC ${LIBRARY_COMPILE_FLAGS})
target_link_libraries(cuda_mod PUBLIC nvidia-ml -lcuda)
161 changes: 149 additions & 12 deletions src/cuda/context.c
Original file line number Diff line number Diff line change
@@ -1,8 +1,37 @@
#include "include/libcuda_hook.h"
#include "include/libvgpu.h"
#include "cuda/context_accounting.h"
#include "multiprocess/multiprocess_memory_limit.h"

extern size_t context_size;
extern int ctx_activate[16];
extern int ctx_activate[CUDA_DEVICE_MAX_COUNT];
extern int pidfound;

static size_t device_context_size[CUDA_DEVICE_MAX_COUNT];
static primary_context_accounting_t
context_accounting[CUDA_DEVICE_MAX_COUNT];
static pthread_mutex_t context_accounting_lock = PTHREAD_MUTEX_INITIALIZER;

void context_accounting_fork_prepare() {
pthread_mutex_lock(&context_accounting_lock);
}

void context_accounting_fork_parent() {
pthread_mutex_unlock(&context_accounting_lock);
}

void context_accounting_fork_child() {
int dev;

context_size = 0;
primary_context_accounting_reset(context_accounting,
CUDA_DEVICE_MAX_COUNT);
for (dev = 0; dev < CUDA_DEVICE_MAX_COUNT; dev++) {
device_context_size[dev] = 0;
ctx_activate[dev] = 0;
}
pthread_mutex_unlock(&context_accounting_lock);
}


CUresult cuDevicePrimaryCtxGetState( CUdevice dev, unsigned int* flags, int* active ){
Expand All @@ -11,16 +40,108 @@ CUresult cuDevicePrimaryCtxGetState( CUdevice dev, unsigned int* flags, int* act
return res;
}

static size_t context_charge_for_device(CUdevice dev) {
if (dev >= 0 && dev < CUDA_DEVICE_MAX_COUNT &&
device_context_size[dev] > 0) {
return device_context_size[dev];
}
return dev == 0 ? context_size : 0;
}

static CUresult rollback_unaccounted_retain(CUdevice dev,
int retain_recorded,
size_t bytes_to_add) {
CUresult release_result;

if (retain_recorded &&
primary_context_rollback_retain(&context_accounting[dev],
bytes_to_add) != 0) {
LOG_ERROR("Failed to roll back local context accounting on device %d",
dev);
}
release_result = CUDA_OVERRIDE_CALL(cuda_library_entry,
cuDevicePrimaryCtxRelease_v2, dev);
if (release_result != CUDA_SUCCESS) {
LOG_ERROR("Failed to release an unaccounted primary context on "
"device %d: %d", dev, release_result);
}
ctx_activate[dev] = (int)context_accounting[dev].retain_count;
return CUDA_ERROR_OUT_OF_MEMORY;
}

CUresult cuDevicePrimaryCtxRetain(CUcontext *pctx, CUdevice dev){
LOG_INFO("dev=%d context_size=%ld",dev,context_size);
//for Initialization only
CUresult res = CUDA_OVERRIDE_CALL(cuda_library_entry,cuDevicePrimaryCtxRetain,pctx,dev);
if (ctx_activate[dev] == 0) {
add_gpu_device_memory_usage(getpid(),dev,context_size,0);
unsigned long long before = 0;
unsigned long long after = 0;
int hostpid;
int measure_context = 0;
size_t charge;
size_t bytes_to_add = 0;

if (dev < 0 || dev >= CUDA_DEVICE_MAX_COUNT) {
return CUDA_OVERRIDE_CALL(cuda_library_entry,
cuDevicePrimaryCtxRetain, pctx, dev);
}

pthread_mutex_lock(&context_accounting_lock);
charge = context_charge_for_device(dev);
hostpid = get_current_host_pid();
if (charge == 0 && pidfound == 1 && hostpid > 0 &&
context_accounting[dev].charged_bytes == 0) {
nvmlReturn_t result = get_used_gpu_memory_by_pid(
(unsigned int)hostpid, dev, &before);
if (result == NVML_SUCCESS || result == NVML_ERROR_NOT_FOUND) {
measure_context = 1;
if (result == NVML_ERROR_NOT_FOUND) {
before = 0;
}
}
}

CUresult res = CUDA_OVERRIDE_CALL(cuda_library_entry,
cuDevicePrimaryCtxRetain, pctx, dev);
if (res != CUDA_SUCCESS) {
pthread_mutex_unlock(&context_accounting_lock);
return res;
}
if (context_size>0) {
ctx_activate[dev] = 1;

if (measure_context) {
int attempt;

for (attempt = 0; attempt < 10; attempt++) {
if (get_used_gpu_memory_by_pid((unsigned int)hostpid, dev,
&after) == NVML_SUCCESS &&
after > before) {
device_context_size[dev] = after - before;
charge = device_context_size[dev];
LOG_INFO("Measured primary context size lazily: "
"dev=%d size=%lu", dev, charge);
break;
}
usleep(1000);
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if ((pidfound == 1
? primary_context_record_accounted_retain(
&context_accounting[dev], charge, &bytes_to_add)
: primary_context_record_retain(&context_accounting[dev], charge,
&bytes_to_add)) != 0) {
LOG_ERROR("Cannot account primary context retain on device %d",
dev);
res = rollback_unaccounted_retain(dev, 0, 0);
pthread_mutex_unlock(&context_accounting_lock);
return res;
}
Comment thread
iemAnshuman marked this conversation as resolved.
Resolved
if (bytes_to_add > 0) {
if (add_gpu_device_memory_usage(getpid(), dev, bytes_to_add, 0) != 0) {
LOG_ERROR("Failed to charge primary context memory on device %d",
dev);
res = rollback_unaccounted_retain(dev, 1, bytes_to_add);
pthread_mutex_unlock(&context_accounting_lock);
return res;
}
}
ctx_activate[dev] = (int)context_accounting[dev].retain_count;
pthread_mutex_unlock(&context_accounting_lock);
return res;
}

Expand All @@ -31,11 +152,28 @@ CUresult cuDevicePrimaryCtxSetFlags_v2( CUdevice dev, unsigned int flags ){
}

CUresult cuDevicePrimaryCtxRelease_v2( CUdevice dev ){
if (ctx_activate[dev] == 1) {
rm_gpu_device_memory_usage(getpid(),dev,context_size,0);
size_t bytes_to_remove = 0;

if (dev < 0 || dev >= CUDA_DEVICE_MAX_COUNT) {
return CUDA_OVERRIDE_CALL(cuda_library_entry,
cuDevicePrimaryCtxRelease_v2, dev);
}
ctx_activate[dev] = 0;
pthread_mutex_lock(&context_accounting_lock);
CUresult res = CUDA_OVERRIDE_CALL(cuda_library_entry,cuDevicePrimaryCtxRelease_v2,dev);
if (res == CUDA_SUCCESS) {
if (primary_context_record_release(&context_accounting[dev],
&bytes_to_remove) != 0) {
LOG_WARN("Unbalanced primary context release on device %d", dev);
} else if (bytes_to_remove > 0) {
if (rm_gpu_device_memory_usage(getpid(), dev, bytes_to_remove,
0) != 0) {
primary_context_restore_charge(&context_accounting[dev],
bytes_to_remove);
}
}
ctx_activate[dev] = (int)context_accounting[dev].retain_count;
}
pthread_mutex_unlock(&context_accounting_lock);
return res;
}

Expand Down Expand Up @@ -149,4 +287,3 @@ CUresult cuCtxSynchronize ( void ){
CUresult res = CUDA_OVERRIDE_CALL(cuda_library_entry,cuCtxSynchronize);
return res;
}

Loading