Skip to content

Instantly share code, notes, and snippets.

@edawson
Forked from sjolsen/cudamap.cc
Created April 3, 2020 19:29
Show Gist options
  • Save edawson/a75b7e49e05ce8412f0d7fe7cb828e9c to your computer and use it in GitHub Desktop.
Save edawson/a75b7e49e05ce8412f0d7fe7cb828e9c to your computer and use it in GitHub Desktop.
Combining memory-mapped I/O and CUDA mapped memory
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <cuda_runtime.h>
#include <cerrno>
#include <cstring>
#include <memory>
#include <stdexcept>
struct cuda_mmap_deleter
{
std::size_t filesize;
cuda_mmap_deleter (std::size_t length)
: filesize (length)
{
}
void operator () (char* ptr)
{
cudaHostUnregister (ptr);
munmap (static_cast <void*> (ptr), filesize);
}
};
std::unique_ptr <char [], cuda_mmap_deleter> map_file (std::string filename,
std::size_t filesize)
{
int fd = open (filename.c_str (), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if (fd == -1)
throw std::runtime_error (std::strerror (errno) + std::string (" (open)"));
ftruncate (fd, filesize);
auto fmem = mmap (nullptr, filesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
close (fd);
if (fmem == MAP_FAILED)
throw std::runtime_error (std::strerror (errno) + std::string (" (mmap)"));
decltype (map_file ("", 0))
mapped_file (static_cast <char*> (fmem), filesize);
auto cuda_retval = cudaHostRegister (fmem, filesize, cudaHostRegisterMapped);
if (cuda_retval != cudaSuccess)
throw std::runtime_error (cudaGetErrorString (cuda_retval) + std::string (" (cudaHostRegister)"));
return mapped_file;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment