# cudaMallocManaged with cudaMemAttachHost

**URL:** <https://forums.developer.nvidia.com/t/cudamallocmanaged-with-cudamemattachhost/230318>\
**Category:** Jetson AGX Orin\
**Tags:** cuda\
**Created:** [October 10, 2022, 9:08am UTC](https://forums.developer.nvidia.com/t/cudamallocmanaged-with-cudamemattachhost/230318 "2022-10-10T09:08:04Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![user54598](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@user54598](https://forums.developer.nvidia.com/u/user54598)\
**Post date:** [October 10, 2022, 9:08am UTC](https://forums.developer.nvidia.com/t/cudamallocmanaged-with-cudamemattachhost/230318/1 "2022-10-10T09:08:04Z")

</div>

As the Cuda document says, “It is not permitted for the CPU to access any managed allocations or variables while the GPU is active for devices with concurrentManagedAccess property set to 0. On these systems concurrent CPU/GPU accesses, even to different managed memory allocations, will cause a segmentation fault because the page is considered inaccessible to the CPU”.

I have a simple test code, memory is allocated with cudaMallocManaged and cudaMemAttachHost, CPU and GPU can concurrent access the managed memory and the code works fine。  
so, why not this test code case segmentation fault ? Is it correct to use cudaMallocManaged like that?

```auto
#include <stdio.h>
#include <thread>
#include <unistd.h>

// error checking macro
#define cudaCheckErrors(msg) \
    do { \
        cudaError_t __err = cudaGetLastError(); \
        if (__err != cudaSuccess) { \
            fprintf(stderr, "Fatal error: %s (%s at %s:%d)\n", \
                msg, cudaGetErrorString(__err), \
                __FILE__ , __LINE__ ); \
            fprintf(stderr, "*** FAILED - ABORTING\n"); \
            exit(1); \
        } \
    } while (0)

const int DSIZE = 4096;
const int block_size = 256; // CUDA maximum is 1024
// vector add kernel: C = A + B
__global__ void vadd(const float *A, const float *B, float *C, int ds){

  int idx = threadIdx.x+blockDim.x*blockIdx.x;
  if (idx < ds)
    C[idx] = A[idx] + B[idx];
}

float *h_A, *h_B, *h_C, *d_A, *d_B, *d_C;

void loop1 () {
  cudaStream_t stream;
  cudaStreamCreate(&stream);
  while(1) {
    vadd<<<(DSIZE+block_size-1)/block_size, block_size,1>>>(h_A, h_B, h_C, DSIZE);
    cudaCheckErrors("kernel launch failure");
    printf("A[0] = %f\n", h_A[0]);
    printf("B[0] = %f\n", h_B[0]);
    printf("C[0] = %f\n", h_C[0]);
  }
}

int main(){

  cudaMallocManaged(&h_A,DSIZE*sizeof(float),cudaMemAttachHost);
  cudaMallocManaged(&h_B,DSIZE*sizeof(float),cudaMemAttachHost);
  cudaMallocManaged(&h_C,DSIZE*sizeof(float),cudaMemAttachHost);

  cudaMallocManaged(&d_A,DSIZE*sizeof(float),cudaMemAttachHost);
  cudaMallocManaged(&d_B,DSIZE*sizeof(float),cudaMemAttachHost);
  
  cudaCheckErrors("cudaMallocManaged fail");
  for (int i = 0; i < DSIZE; i++){
    h_A[i] = rand()/(float)RAND_MAX;
    h_B[i] = rand()/(float)RAND_MAX;
    h_C[i] = 0;}
  
  std::thread thr(loop1);
  sleep(1);
  while(1) {
    d_A[0] ++;
    d_B[0] ++;
    printf("---- A[0] = %f\n", h_A[0]);
    printf("---- B[0] = %f\n", h_B[0]);
    printf("---- C[0] = %f\n", h_C[0]);
    printf("---- A[0] = %f\n", d_A[0]);
    printf("---- B[0] = %f\n", d_B[0]);
  }

  while(1) {
	  sleep(1000);
  }
  return 0;
}

```

---

<div class="post-metadata">

**Author:** ![neel\_patel](https://sea2.discourse-cdn.com/nvidia/user_avatar/forums.developer.nvidia.com/neel_patel/32/14047_2.png) [@neel\_patel](https://forums.developer.nvidia.com/u/neel_patel)\
**Post date:** [October 13, 2022, 12:58am UTC](https://forums.developer.nvidia.com/t/cudamallocmanaged-with-cudamemattachhost/230318/3 "2022-10-13T00:58:57Z")

</div>

Hi ,  
It seems the reason you’re getting a behavior that seems different than the usual “seg fault” behavior is that passing the `cudaMemAttachHost` flag to `cudaMallocManaged` changes the default behavior of an allocation. The default behavior is (automatic) migratable. But when you pass that particular flag, the default behavior is **not** migratable. Since it is not migratable, you don’t get a seg fault (it is still accessible from host code), but it is **not** accessible from device code until you do something specific, **even if you launch a kernel.** You can read more about that in the runtime API description of cudaMallocManaged [here](https://docs.nvidia.com/cuda/cuda-runtime-api/group __CUDART__ MEMORY.html#group __CUDART__ MEMORY_1gd228014f19cc0975ebe3e0dd2af6dd1b). So the code is illegal in the sense that it has not allowed an allocation to migrate to the GPU, before attempting to use that allocation on the GPU. If it did allow that migration, you would witness a seg fault.

here is the relevant quote: “If [cudaMemAttachHost](https://docs.nvidia.com/cuda/cuda-runtime-api/group __CUDART__ TYPES.html#group __CUDART__ TYPES_1g4f9a428d18fdd89a99441d0dd27131c0) is specified, then the allocation should not be accessed from devices that have a zero value for the device attribute [cudaDevAttrConcurrentManagedAccess](https://docs.nvidia.com/cuda/cuda-runtime-api/group __CUDART__ TYPES.html#group __CUDART__ TYPES_1gg49e2f8c2c0bd6fe264f2fc970912e5cdc88178f29891f2c18fe67361cc80de09); an explicit call to [cudaStreamAttachMemAsync](https://docs.nvidia.com/cuda/cuda-runtime-api/group __CUDART__ HIGHLEVEL.html#group __CUDART__ HIGHLEVEL_1g496353d630c29c44a2e33f531a3944d1) will be required to enable access on such devices.” Your code never makes that call. And its not a simple matter of making that call (properly), you would also have to add in the `cudaDeviceSynchronize()` that we normally expect to see, to make non-illegal code.

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/nvidia/user_avatar/forums.developer.nvidia.com/system/32/68080_2.png) [@system](https://forums.developer.nvidia.com/u/system)\
**Post date:** [November 2, 2022, 4:32am UTC](https://forums.developer.nvidia.com/t/cudamallocmanaged-with-cudamemattachhost/230318/5 "2022-11-02T04:32:25Z")

</div>

Closed on November 2, 2022, 4:32am UTC

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
