Share/Copy memory between two CUDA contexts in the same GPU and process

After reading the documentation for CUDA Driver API, the programming guide (Section 3.3.1) and some previous discussions here such as link1, it was clear that memory allocated in one context should not be accessible by another context in any case. However, I’m working on a library that uses custom context in most of the time, but I need to use the primary context for some cufft calls due to a bug on cuda 11.x (fixed on cuda 12), so I need to share memory somehow.

I thought about two solutions, copying to and from host before and after FFT or using some mechanism in Driver API to copy between two different contexts, but I don’t know if cuMemcpyPeer is suitable for two contexts in the same device and same process (because cuCtxEnablePeerAccess returns error CUDA_ERROR_PEER_ACCESS_UNSUPPORTED).
cuMemcpyPeer worked when I used without enable peer access, but it also worked to just don’t copy at all and use it raw.

Below I’m sending a code that I used to test the behavior of accessing memory allocated by a different context, and access both buffers using a kernel.
I’m also performing some tests to check if the device ptr is accessible by that context using cuPointerGetAttribute with CU_POINTER_ATTRIBUTE_DEVICE_POINTER, even though cuPointerGetAttribute with CU_POINTER_ATTRIBUTE_CONTEXT is returning the other context. I’m also checking the address range with cuMemGetAddressRange.

cuCtxDestroy worked as expected, if I call it before launching the kernel I get a CUDA_ERROR_ILLEGAL_ADDRESS in the memory copy. But while both context exists, seems like each one can access data from the other.

I don’t know if this behavior is due to UVA, or some other feature. I tested only on cuda 12.4 and cuda 11.6 (with driver matching runtime version), in both cases the printed resulted was equal (except by the addresses).

kernel.cu:

extern "C" {
__global__ void mtp2(int *d1, int *d2, size_t N){
    size_t id = blockIdx.x * blockDim.x + threadIdx.x;
    for(size_t i = id; i < N; i += blockDim.x * gridDim.x){
        d2[i] = 2 * d1[i];
    }
}
}
//compile using nvcc -ptx -c kernel.cu -o kernel

main.cu:

#include <cuda.h>
#include <cstdio>

//Note: Memory isn't freed.
//This assumes sizeof(int) = 4 

int main(){
    int ier = 0;
    CUcontext ctx1, ctx2, aux;
    CUdevice dev;
    CUdeviceptr d1, d2;
    int *h1, *h2;
    h1 = (int *) malloc(1 << 30);
    h2 = (int *) malloc(1 << 30);
    for(int i=0;i<(1 << 28); i++){
        h1[i] = i;
    }
    cuInit(0);
    ier |= cuDeviceGet(&dev, 0);
    ier |= cuCtxCreate(&ctx1, CU_CTX_MAP_HOST | CU_CTX_SCHED_AUTO, dev); 
    ier |= cuMemAlloc(&d1, 1 << 30);
    ier |= cuMemcpyHtoD(d1, h1, 1 << 30);
    ier |= cuCtxGetCurrent(&aux);
    printf("first context is %p and cur %p\n", (void *)ctx1, (void *) aux); //equal
    //Synchronizing before context switch.
    ier |= cuCtxSynchronize();

    ier |= cuCtxCreate(&ctx2, CU_CTX_MAP_HOST | CU_CTX_SCHED_AUTO, dev);
    ier |= cuCtxGetCurrent(&aux);
    ier |= cuMemAlloc(&d2, 1 << 30);
    printf("second context is %p and cur %p\n", (void *)ctx2, (void *)aux); //equal 
    ier |= cuCtxSynchronize();
    printf("addresses are %p and %p\n", (void *)d1, (void *)d2); //different 

    CUdeviceptr accessible_ptr = 0;
    CUcontext accessible_ctx = 0;

    ier |= cuPointerGetAttribute(
        &accessible_ctx,
        CU_POINTER_ATTRIBUTE_CONTEXT,
        (CUdeviceptr)d1
    );

    ier |= cuCtxGetCurrent(&aux);

    //different as expected.
    printf("accesible ctx %p, cur context %p\n", (void *)accessible_ctx, (void *)aux);

    printf("until here, no error => %d\n", ier);

    ier |= cuPointerGetAttribute(
        &accessible_ptr,
        CU_POINTER_ATTRIBUTE_DEVICE_POINTER,
        (CUdeviceptr)d1
    );

    printf("pointer query: %d, accessible pointer: %p\n",
        (int)ier, (void *)accessible_ptr);
    
    //As can be seen above, the pointer is made by the first context (which isn't current).
    CUdeviceptr d3 = d1 + (1 << 25); //Sum 2^25 just to test.
    accessible_ptr = 0;
    size_t size = 0;

    printf("address of d3 is %p and accessible_ptr set to NULL => %p\n", (void *)d3, (void *)accessible_ptr);

    ier |= cuMemGetAddressRange(
        &accessible_ptr,
        &size,
        d3
    );
    
    //This is the d1 range.
    printf("accessible_ptr is %p, range size is %zu\n", (void *)accessible_ptr, size);
 
    //Finally launching a kernel.
    size_t N = 1 << 28;
    CUmodule mod;
    CUfunction kernel;
    ier |= cuModuleLoad(&mod, "kernel");
    ier |= cuModuleGetFunction(&kernel, mod, "mtp2");
    void* args[] = {
        &d1,
        &d2,
        &N
    };
    ier |= cuLaunchKernel(kernel, 1024, 1, 1, 1024, 1, 1, 0, nullptr, args, nullptr);
    ier |= cuCtxSynchronize();
    ier |= cuMemcpyDtoH(h2, d2, 1 << 30);
    //printing first 20
    for(int i = 0; i < 20; i++){
        printf("%d ", h2[i]);
    }
    printf("\n");

    long long sum1 = 0, sum2 = 0;
    bool ok = true;
    for(int i = 0;i < (1 << 28); i++){
        sum1 += h1[i];
        sum2 += h2[i];
        if(h1[i] * 2 != h2[i]) ok = false;
    }
    printf("h1: %lld is a half of h2: %lld\n", sum1, sum2);

    printf("after all that, the error is => %d\n", ier);

    printf("result is:[%s]\n", ok && (!ier) ? "PASS" : "FAIL");
}

Result:

first context is 0x55e0c4795480 and cur 0x55e0c4795480
second context is 0x55e0c5055260 and cur 0x55e0c5055260
addresses are 0x7f2698000000 and 0x7f264a000000
accesible ctx 0x55e0c4795480, cur context 0x55e0c5055260
until here, no error => 0
pointer query: 0, accessible pointer: 0x7f2698000000
address of d3 is 0x7f269a000000 and accessible_ptr set to NULL => (nil)
accessible_ptr is 0x7f2698000000, range size is 1073741824
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
h1: 36028796884746240 is a half of h2: 72057593769492480
after all that, the error is => 0
result is:[PASS]