Host-to-Device Data Transfer

Host-to-device data transfer is implemented by using the memory copy API.

Data Transfer Using Synchronous Memory Copy

Following the API calls, add exception handling branches and specify log printing of error and information levels. The following is a code snippet of key steps only, which is not ready to be built or run.

//1. Allocate memory.
uint64_t size = 1 * 1024 * 1024;
void* hostPtrA = NULL;
void* devPtrB = NULL;
aclrtMallocHost(&hostPtrA, size);
aclrtMalloc(&devPtrB, size, ACL_MEM_MALLOC_NORMAL_ONLY);

//2. After the memory is allocated, load data into the memory and implement the user-defined function ReadFile.
ReadFile(fileName, hostPtrA, size);

//3. Perform synchronous or asynchronous memory copy.
//Copy memory synchronously. hostPtrA indicates the pointer to the source memory address on the host. devPtrB indicates the pointer to the destination memory address on the device. size indicates the memory size.
aclrtMemcpy(devPtrB, size, hostPtrA, size, ACL_MEMCPY_HOST_TO_DEVICE);

//4. Destroy allocations in a timely manner.
aclrtFreeHost(hostPtrA);
aclrtFree(devPtrB);

// ......

Data Transfer Using Asynchronous Memory Copy

Following the API calls, add exception handling branches and specify log printing of error and information levels. The following is a code snippet of key steps only, which is not ready to be built or run.

//1. Allocate memory.
uint64_t size = 1 * 1024 * 1024;
void* hostAddr = NULL;
void* devAddr = NULL;
//Asynchronous memory copy requires that the start address be 64-byte aligned.
aclrtMallocHost(&hostAddr, size + 64);
//The aclrtMalloc call ensures that the memory address is 64-byte aligned. Therefore, you do not need to care about the alignment logic.
aclrtMalloc(&devAddr, size, ACL_MEM_MALLOC_NORMAL_ONLY);

//2. Copy memory asynchronously.
aclrtStream stream = NULL;
aclrtCreateStream(&stream);
//Obtain the 64-byte-aligned address.
char *hostAlignAddr =(char *)hostAddr + 64 - ((uintptr_t)hostAddr % 64);
//After the memory is allocated, load data into the memory and implement the user-defined function ReadFile.
ReadFile(fileName, hostAlignAddr, size);
aclrtMemcpyAsync(devAddr, size, hostAlignAddr, size, ACL_MEMCPY_HOST_TO_DEVICE, stream);
aclrtSynchronizeStream(stream);

//3. Destroy allocations.
aclrtDestroyStream(stream);
aclrtFreeHost(hostAddr);
aclrtFree(devAddr);

// ......