CUDA Runtime API Reference Manual (Release 13.5, 2026) - page 8

 

  Index      Manuals     CUDA Runtime API Reference Manual (Release 13.5, 2026)

 

Search            copyright infringement  

 

   

 

   

 

Content      ..     6      7      8      9     ..

 

 

 

CUDA Runtime API Reference Manual (Release 13.5, 2026) - page 8

 

 

CUDA Runtime API Reference Manual, Release 13.5
▶ hOffset - - Source starting Y offset (rows)
▶ count - - Size in bytes to copy
▶ kind - - Type of transfer
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidMemcpyDirection
__host__ cudaError_t cudaMemcpyFromArrayAsync(void *dst, cudaArray_const_t src, size_t
wOffset, size_t hOffset, size_t count, enum
cudaMemcpyKind kind, cudaStream_t stream =
0)
Copies data between host and device.
Deprecated:
Copies count bytes from the CUDA array src starting at hOffset rows and wOffset bytes from
the upper left corner to the memory area pointed to by dst, where kind specifies the direction
of the copy, and must be one of cudaMemcpyHostToHost, cudaMemcpyHostToDevice, cudaMem-
cpyDeviceToHost, cudaMemcpyDeviceToDevice, or cudaMemcpyDefault. Passing cudaMemcpy-
Default is recommended, in which case the type of transfer is inferred from the pointer values.
However, cudaMemcpyDefault is only allowed on systems that support unified virtual addressing.
cudaMemcpyFromArrayAsync() is asynchronous with respect to the host, so the call may return
before the copy is complete. The copy can optionally be associated to a stream by passing a
non-zero stream argument. If kind is cudaMemcpyHostToDevice or cudaMemcpyDeviceToHost
and stream is non-zero, the copy may overlap with operations in other streams.
See also:
cudaMemcpy, cudaMemcpy2D, cudaMemcpyToArray, cudaMemcpy2DToArray, cudaMemcpyFro-
mArray, cudaMemcpy2DFromArray, cudaMemcpyArrayToArray, cudaMemcpy2DArrayToArray, cu-
daMemcpyToSymbol, cudaMemcpyFromSymbol, cudaMemcpyAsync, cudaMemcpy2DAsync, cu-
daMemcpyToArrayAsync, cudaMemcpy2DToArrayAsync, cudaMemcpy2DFromArrayAsync, cud-
aMemcpyToSymbolAsync, cudaMemcpyFromSymbolAsync,
::cuMemcpyAtoHAsync,
::cuMem-
cpy2DAsync
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: This function exhibits asynchronous behavior for most use cases.
Note: This function uses standard default stream semantics.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
6.26. Memory Management [DEPRECATED]
511
CUDA Runtime API Reference Manual, Release 13.5
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ dst - - Destination memory address
▶ src - - Source memory address
▶ wOffset - - Source starting X offset (columns in bytes)
▶ hOffset - - Source starting Y offset (rows)
▶ count - - Size in bytes to copy
▶ kind - - Type of transfer
▶ stream - - Stream identifier
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidMemcpyDirection
__host__ cudaError_t cudaMemcpyToArray(cudaArray_t dst, size_t wOffset, size_t hOffset, const
void *src, size_t count, enum cudaMemcpyKind kind)
Copies data between host and device.
Deprecated:
Copies count bytes from the memory area pointed to by src to the CUDA array dst starting at
hOffset rows and wOffset bytes from the upper left corner, where kind specifies the direction
of the copy, and must be one of cudaMemcpyHostToHost, cudaMemcpyHostToDevice, cudaMem-
cpyDeviceToHost, cudaMemcpyDeviceToDevice, or cudaMemcpyDefault. Passing cudaMemcpy-
Default is recommended, in which case the type of transfer is inferred from the pointer values.
However, cudaMemcpyDefault is only allowed on systems that support unified virtual addressing.
See also:
cudaMemcpy, cudaMemcpy2D, cudaMemcpy2DToArray, cudaMemcpyFromArray, cudaMem-
cpy2DFromArray,
cudaMemcpyArrayToArray,
cudaMemcpy2DArrayToArray,
cudaMemcpy-
ToSymbol, cudaMemcpyFromSymbol, cudaMemcpyAsync, cudaMemcpy2DAsync, cudaMem-
cpyToArrayAsync,
cudaMemcpy2DToArrayAsync,
cudaMemcpyFromArrayAsync,
cudaMem-
cpy2DFromArrayAsync, cudaMemcpyToSymbolAsync, cudaMemcpyFromSymbolAsync, ::cuMem-
cpyHtoA, ::cuMemcpyDtoA
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: This function exhibits synchronous behavior for most use cases.
512
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ dst - - Destination memory address
▶ wOffset - - Destination starting X offset (columns in bytes)
▶ hOffset - - Destination starting Y offset (rows)
▶ src - - Source memory address
▶ count - - Size in bytes to copy
▶ kind - - Type of transfer
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidMemcpyDirection
__host__ cudaError_t cudaMemcpyToArrayAsync(cudaArray_t dst, size_t wOffset, size_t hOffset,
const void *src, size_t count, enum
cudaMemcpyKind kind, cudaStream_t stream = 0)
Copies data between host and device.
Deprecated:
Copies count bytes from the memory area pointed to by src to the CUDA array dst starting at
hOffset rows and wOffset bytes from the upper left corner, where kind specifies the direction
of the copy, and must be one of cudaMemcpyHostToHost, cudaMemcpyHostToDevice, cudaMem-
cpyDeviceToHost, cudaMemcpyDeviceToDevice, or cudaMemcpyDefault. Passing cudaMemcpy-
Default is recommended, in which case the type of transfer is inferred from the pointer values.
However, cudaMemcpyDefault is only allowed on systems that support unified virtual addressing.
cudaMemcpyToArrayAsync() is asynchronous with respect to the host, so the call may return be-
fore the copy is complete. The copy can optionally be associated to a stream by passing a non-
zero stream argument. If kind is cudaMemcpyHostToDevice or cudaMemcpyDeviceToHost and
stream is non-zero, the copy may overlap with operations in other streams.
See also:
cudaMemcpy, cudaMemcpy2D, cudaMemcpyToArray, cudaMemcpy2DToArray, cudaMemcpyFro-
mArray, cudaMemcpy2DFromArray, cudaMemcpyArrayToArray, cudaMemcpy2DArrayToArray, cu-
daMemcpyToSymbol, cudaMemcpyFromSymbol, cudaMemcpyAsync, cudaMemcpy2DAsync, cu-
daMemcpy2DToArrayAsync, cudaMemcpyFromArrayAsync, cudaMemcpy2DFromArrayAsync, cu-
daMemcpyToSymbolAsync, cudaMemcpyFromSymbolAsync,
::cuMemcpyHtoAAsync,
::cuMem-
cpy2DAsync
6.26. Memory Management [DEPRECATED]
513
CUDA Runtime API Reference Manual, Release 13.5
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: This function exhibits asynchronous behavior for most use cases.
Note: This function uses standard default stream semantics.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ dst - - Destination memory address
▶ wOffset - - Destination starting X offset (columns in bytes)
▶ hOffset - - Destination starting Y offset (rows)
▶ src - - Source memory address
▶ count - - Size in bytes to copy
▶ kind - - Type of transfer
▶ stream - - Stream identifier
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidMemcpyDirection
6.27. Occupancy
This section describes the occupancy calculation functions of the CUDA runtime application program-
ming interface.
Besides the occupancy calculator functions (cudaOccupancyMaxActiveBlocksPerMultiprocessor and
cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags), there are also C++ only occupancy-
based launch configuration functions documented in C++ API Routines module.
See cudaOccupancyMaxPotentialBlockSize (C++ API), cudaOccupancyMaxPotentialBlockSize (C++ API),
cudaOccupancyMaxPotentialBlockSizeVariableSMem (C++ API), cudaOccupancyMaxPotentialBlockSize-
VariableSMem (C++ API) cudaOccupancyAvailableDynamicSMemPerBlock (C++ API),
514
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Functions
__host__ cudaError_t cudaOccupancyAvailableDynamicSMemPerBlock(size_t *dynamicSmemSize,
const void *func, int numBlocks, int blockSize)
Returns dynamic shared memory available per block when launching numBlocks blocks on SM.
__host__ cudaError_t cudaOccupancyMaxActiveBlocksPerMultiprocessor(int *numBlocks, const void
*func, int blockSize, size_t dynamicSMemSize)
Returns occupancy for a device function.
__host__ cudaError_t cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags(int *numBlocks,
const void *func, int blockSize, size_t dynamicSMemSize, unsigned int flags)
Returns occupancy for a device function with the specified flags.
__host__ cudaError_t cudaOccupancyMaxActiveClusters(int *numClusters, const void *func, const
cudaLaunchConfig_t *launchConfig)
Given the kernel function ( func ) and launch configuration ( config ), return the maximum
number of clusters that could co-exist on the target device in *numClusters .
__host__ cudaError_t cudaOccupancyMaxPotentialClusterSize(int *clusterSize, const void *func,
const cudaLaunchConfig_t *launchConfig)
Given the kernel function ( func ) and launch configuration ( config ), return the maximum clus-
ter size in *clusterSize .
6.27.1. Functions
__host__ cudaError_t cudaOccupancyAvailableDynamicSMemPerBlock(size_t
*dynamicSmemSize,
const void *func, int
numBlocks, int
blockSize)
Returns dynamic shared memory available per block when launching numBlocks blocks on SM.
Returns in *dynamicSmemSize the maximum size of dynamic shared memory to allow num-
Blocks blocks per SM.
See also:
cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags,
cudaOccupancyMaxPotential-
BlockSize (C++ API), cudaOccupancyMaxPotentialBlockSizeWithFlags (C++ API), cudaOccupan-
cyMaxPotentialBlockSizeVariableSMem (C++ API), cudaOccupancyMaxPotentialBlockSizeVari-
ableSMemWithFlags (C++ API), cudaOccupancyAvailableDynamicSMemPerBlock
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
6.27. Occupancy
515
CUDA Runtime API Reference Manual, Release 13.5
such case.
Note: The API can also be used with a kernel cudaKernel_t by querying the handle using cudaLi-
braryGetKernel() or cudaGetKernel and then passing it to the API by casting to void*. The symbol
entryFuncAddr passed to cudaGetKernel should be a symbol that is registered with the same
CUDA Runtime instance.
Note: Passing a symbol that belongs that belongs to a different runtime instance will result in
undefined behavior. The only type that can be reliably passed to a different runtime instance is
cudaKernel_t
Parameters
▶ dynamicSmemSize - - Returned maximum dynamic shared memory
▶ func - - Kernel function for which occupancy is calculated
▶ numBlocks - - Number of blocks to fit on SM
▶ blockSize - - Size of the block
Returns
cudaSuccess, cudaErrorInvalidDevice, cudaErrorInvalidDeviceFunction, cudaErrorIn-
validValue, cudaErrorUnknown,
__host__ cudaError_t cudaOccupancyMaxActiveBlocksPerMultiprocessor(int *numBlocks,
const void *func, int
blockSize, size_t dy-
namicSMemSize)
Returns occupancy for a device function.
Returns in *numBlocks the maximum number of active blocks per streaming multiprocessor for
the device function.
See also:
cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags,
cudaOccupancyMaxPotential-
BlockSize (C++ API), cudaOccupancyMaxPotentialBlockSizeWithFlags (C++ API), cudaOccupan-
cyMaxPotentialBlockSizeVariableSMem (C++ API), cudaOccupancyMaxPotentialBlockSizeVari-
ableSMemWithFlags (C++ API), cudaOccupancyAvailableDynamicSMemPerBlock (C++ API),
::cuOccupancyMaxActiveBlocksPerMultiprocessor
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
516
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Note: The API can also be used with a kernel cudaKernel_t by querying the handle using cudaLi-
braryGetKernel() or cudaGetKernel and then passing it to the API by casting to void*. The symbol
entryFuncAddr passed to cudaGetKernel should be a symbol that is registered with the same
CUDA Runtime instance.
Note: Passing a symbol that belongs that belongs to a different runtime instance will result in
undefined behavior. The only type that can be reliably passed to a different runtime instance is
cudaKernel_t
Parameters
▶ numBlocks - - Returned occupancy
▶ func - - Kernel function for which occupancy is calculated
▶ blockSize - - Block size the kernel is intended to be launched with
▶ dynamicSMemSize - - Per-block dynamic shared memory usage intended, in
bytes
Returns
cudaSuccess, cudaErrorInvalidDevice, cudaErrorInvalidDeviceFunction, cudaErrorIn-
validValue, cudaErrorUnknown,
__host__ cudaError_t cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags(int
*num-
Blocks,
const
void
*func,
int
block-
Size,
size_t
dynam-
ic-
SMem-
Size,
un-
signed
int
flags)
Returns occupancy for a device function with the specified flags.
Returns in *numBlocks the maximum number of active blocks per streaming multiprocessor for
the device function.
6.27. Occupancy
517
CUDA Runtime API Reference Manual, Release 13.5
The flags parameter controls how special cases are handled. Valid flags include:
▶ cudaOccupancyDefault: keeps the default behavior as cudaOccupancyMaxActiveBlocksPer-
Multiprocessor
▶ cudaOccupancyDisableCachingOverride: This flag suppresses the default behavior on plat-
form where global caching affects occupancy. On such platforms, if caching is enabled, but
per-block SM resource usage would result in zero occupancy, the occupancy calculator will
calculate the occupancy as if caching is disabled. Setting this flag makes the occupancy
calculator to return 0 in such cases. More information can be found about this feature in
the “Unified L1/Texture Cache” section of the Maxwell tuning guide.
See also:
cudaOccupancyMaxActiveBlocksPerMultiprocessor, cudaOccupancyMaxPotentialBlockSize (C++
API), cudaOccupancyMaxPotentialBlockSizeWithFlags (C++ API), cudaOccupancyMaxPotential-
BlockSizeVariableSMem (C++ API), cudaOccupancyMaxPotentialBlockSizeVariableSMemWithFlags
(C++ API), cudaOccupancyAvailableDynamicSMemPerBlock (C++ API), ::cuOccupancyMaxActive-
BlocksPerMultiprocessorWithFlags
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Note: The API can also be used with a kernel cudaKernel_t by querying the handle using cudaLi-
braryGetKernel() or cudaGetKernel and then passing it to the API by casting to void*. The symbol
entryFuncAddr passed to cudaGetKernel should be a symbol that is registered with the same
CUDA Runtime instance.
Note: Passing a symbol that belongs that belongs to a different runtime instance will result in
undefined behavior. The only type that can be reliably passed to a different runtime instance is
cudaKernel_t
Parameters
▶ numBlocks - - Returned occupancy
▶ func - - Kernel function for which occupancy is calculated
▶ blockSize - - Block size the kernel is intended to be launched with
518
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ dynamicSMemSize - - Per-block dynamic shared memory usage intended, in
bytes
▶ flags - - Requested behavior for the occupancy calculator
Returns
cudaSuccess, cudaErrorInvalidDevice, cudaErrorInvalidDeviceFunction, cudaErrorIn-
validValue, cudaErrorUnknown,
__host__ cudaError_t cudaOccupancyMaxActiveClusters(int *numClusters, const void *func,
const cudaLaunchConfig_t
*launchConfig)
Given the kernel function (func) and launch configuration (config), return the maximum number
of clusters that could co-exist on the target device in *numClusters.
If the function has required cluster size already set (see cudaFuncGetAttributes), the cluster size
from config must either be unspecified or match the required size. Without required sizes, the
cluster size must be specified in config, else the function will return an error.
Note that various attributes of the kernel function may affect occupancy calculation. Runtime
environment may affect how the hardware schedules the clusters, so the calculated occupancy
is not guaranteed to be achievable.
See also:
cudaFuncGetAttributes cudaOccupancyMaxActiveClusters (C++ API),
::cuOccupancyMaxAc-
tiveClusters
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Note: The API can also be used with a kernel cudaKernel_t by querying the handle using cudaLi-
braryGetKernel() or cudaGetKernel and then passing it to the API by casting to void*. The symbol
entryFuncAddr passed to cudaGetKernel should be a symbol that is registered with the same
CUDA Runtime instance.
Note: Passing a symbol that belongs that belongs to a different runtime instance will result in
undefined behavior. The only type that can be reliably passed to a different runtime instance is
cudaKernel_t
Parameters
6.27. Occupancy
519
CUDA Runtime API Reference Manual, Release 13.5
▶ numClusters - - Returned maximum number of clusters that could co-exist on
the target device
▶ func - - Kernel function for which maximum number of clusters are calculated
▶ config - - Launch configuration for the given kernel function
Returns
cudaSuccess, cudaErrorInvalidDeviceFunction, cudaErrorInvalidValue, cudaErrorIn-
validClusterSize, cudaErrorUnknown,
__host__ cudaError_t cudaOccupancyMaxPotentialClusterSize(int *clusterSize, const void
*func, const
cudaLaunchConfig_t
*launchConfig)
Given the kernel function (func) and launch configuration (config), return the maximum cluster
size in *clusterSize.
The cluster dimensions in config are ignored. If func has a required cluster size set (see cuda-
FuncGetAttributes),*clusterSize will reflect the required cluster size.
By default this function will always return a value that’s portable on future hardware. A higher
value may be returned if the kernel function allows non-portable cluster sizes.
This function will respect the compile time launch bounds.
See also:
cudaFuncGetAttributes cudaOccupancyMaxPotentialClusterSize (C++ API), ::cuOccupancyMax-
PotentialClusterSize
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Note: The API can also be used with a kernel cudaKernel_t by querying the handle using cudaLi-
braryGetKernel() or cudaGetKernel and then passing it to the API by casting to void*. The symbol
entryFuncAddr passed to cudaGetKernel should be a symbol that is registered with the same
CUDA Runtime instance.
Note: Passing a symbol that belongs that belongs to a different runtime instance will result in
undefined behavior. The only type that can be reliably passed to a different runtime instance is
cudaKernel_t
520
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Parameters
▶ clusterSize - - Returned maximum cluster size that can be launched for the
given kernel function and launch configuration
▶ func - - Kernel function for which maximum cluster size is calculated
▶ config - - Launch configuration for the given kernel function
Returns
cudaSuccess, cudaErrorInvalidDeviceFunction, cudaErrorInvalidValue, cudaErrorUnk-
nown,
6.28. OpenGL Interoperability
impl_private
This section describes the OpenGL interoperability functions of the CUDA runtime application pro-
gramming interface. Note that mapping of OpenGL resources is performed with the graphics API
agnostic, resource mapping interface described in Graphics Interopability.
Enumerations
cudaGLDeviceList
CUDA devices corresponding to the current OpenGL context.
Functions
__host__ cudaError_t cudaGLGetDevices(unsigned int *pCudaDeviceCount, int *pCudaDevices, un-
signed int cudaDeviceCount, enum cudaGLDeviceList deviceList)
Gets the CUDA devices associated with the current OpenGL context.
__host__ cudaError_t cudaGraphicsGLRegisterBuffer(struct cudaGraphicsResource
**resource,
GLuint buffer, unsigned int flags)
Registers an OpenGL buffer object.
__host__ cudaError_t cudaGraphicsGLRegisterImage(struct cudaGraphicsResource
**resource,
GLuint image, GLenum target, unsigned int flags)
Register an OpenGL texture or renderbuffer object.
__host__ cudaError_t cudaWGLGetDevice(int *device, HGPUNV hGpu)
Gets the CUDA device associated with hGpu.
6.28. OpenGL Interoperability
521
CUDA Runtime API Reference Manual, Release 13.5
Typedefs
HGPUNV
6.28.1. Enumerations
enum cudaGLDeviceList
CUDA devices corresponding to the current OpenGL context.
Values:
enumerator cudaGLDeviceListAll = 1
The CUDA devices for all GPUs used by the current OpenGL context.
enumerator cudaGLDeviceListCurrentFrame = 2
The CUDA devices for the GPUs used by the current OpenGL context in its currently render-
ing frame.
enumerator cudaGLDeviceListNextFrame = 3
The CUDA devices for the GPUs to be used by the current OpenGL context in the next frame
6.28.2. Functions
__host__ cudaError_t cudaGLGetDevices(unsigned int *pCudaDeviceCount, int *pCudaDevices,
unsigned int cudaDeviceCount, enum cudaGLDeviceList
deviceList)
Gets the CUDA devices associated with the current OpenGL context.
Returns in *pCudaDeviceCount the number of CUDA-compatible devices corresponding to the
current OpenGL context. Also returns in *pCudaDevices at most cudaDeviceCount of the
CUDA-compatible devices corresponding to the current OpenGL context. If any of the GPUs
being used by the current OpenGL context are not CUDA capable then the call will return cud-
aErrorNoDevice.
See also:
cudaGraphicsUnregisterResource,
cudaGraphicsMapResources,
cudaGraphicsSubRe-
sourceGetMappedArray, cudaGraphicsResourceGetMappedPointer, ::cuGLGetDevices
Note: This function is not supported on Mac OS X.
Note: Note that this function may also return error codes from previous, asynchronous launches.
522
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Parameters
▶ pCudaDeviceCount - - Returned number of CUDA devices corresponding to
the current OpenGL context
▶ pCudaDevices - - Returned CUDA devices corresponding to the current
OpenGL context
▶ cudaDeviceCount - - The size of the output device array pCudaDevices
▶ deviceList - - The set of devices to return. This set may be cudaGLDe-
viceListAll for all devices, cudaGLDeviceListCurrentFrame for the devices used
to render the current frame (in SLI), or cudaGLDeviceListNextFrame for the de-
vices used to render the next frame (in SLI).
Returns
cudaSuccess, cudaErrorNoDevice, cudaErrorInvalidGraphicsContext, cudaErrorOper-
atingSystem, cudaErrorUnknown
__host__ cudaError_t cudaGraphicsGLRegisterBuffer(struct cudaGraphicsResource **resource,
GLuint buffer, unsigned int flags)
Registers an OpenGL buffer object.
Registers the buffer object specified by buffer for access by CUDA. A handle to the registered
object is returned as resource. The register flags flags specify the intended usage, as follows:
▶ cudaGraphicsRegisterFlagsNone: Specifies no hints about how this resource will be used. It
is therefore assumed that this resource will be read from and written to by CUDA. This is the
default value.
▶ cudaGraphicsRegisterFlagsReadOnly: Specifies that CUDA will not write to this resource.
▶ cudaGraphicsRegisterFlagsWriteDiscard: Specifies that CUDA will not read from this re-
source and will write over the entire contents of the resource, so none of the data previously
stored in the resource will be preserved.
See also:
cudaGraphicsUnregisterResource,
cudaGraphicsMapResources,
cudaGraphicsRe-
sourceGetMappedPointer, ::cuGraphicsGLRegisterBuffer
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ resource - - Pointer to the returned object handle
▶ buffer - - name of buffer object to be registered
▶ flags - - Register flags
Returns
cudaSuccess,
cudaErrorInvalidDevice,
cudaErrorInvalidValue,
cudaErrorIn-
validResourceHandle, cudaErrorOperatingSystem, cudaErrorUnknown
6.28. OpenGL Interoperability
523
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaGraphicsGLRegisterImage(struct cudaGraphicsResource **resource,
GLuint image, GLenum target, unsigned int
flags)
Register an OpenGL texture or renderbuffer object.
Registers the texture or renderbuffer object specified by image for access by CUDA. A handle to
the registered object is returned as resource.
target must match the type of the object, and must be one of
::GL_TEXTURE_2D,
::GL_TEXTURE_RECTANGLE,
::GL_TEXTURE_CUBE_MAP,
::GL_TEXTURE_3D,
::GL_TEXTURE_2D_ARRAY, or ::GL_RENDERBUFFER.
The register flags flags specify the intended usage, as follows:
▶ cudaGraphicsRegisterFlagsNone: Specifies no hints about how this resource will be used. It
is therefore assumed that this resource will be read from and written to by CUDA. This is the
default value.
▶ cudaGraphicsRegisterFlagsReadOnly: Specifies that CUDA will not write to this resource.
▶ cudaGraphicsRegisterFlagsWriteDiscard: Specifies that CUDA will not read from this re-
source and will write over the entire contents of the resource, so none of the data previously
stored in the resource will be preserved.
▶ cudaGraphicsRegisterFlagsSurfaceLoadStore: Specifies that CUDA will bind this resource to
a surface reference.
▶ cudaGraphicsRegisterFlagsTextureGather: Specifies that CUDA will perform texture gather
operations on this resource.
The following image formats are supported. For brevity’s sake, the list is abbreviated. For ex.,
{GL_R, GL_RG} X {8, 16} would expand to the following 4 formats {GL_R8, GL_R16, GL_RG8,
GL_RG16} :
▶ GL_RED, GL_RG, GL_RGBA, GL_LUMINANCE, GL_ALPHA, GL_LUMINANCE_ALPHA,
GL_INTENSITY
▶ {GL_R, GL_RG, GL_RGBA} X {8, 16, 16F, 32F, 8UI, 16UI, 32UI, 8I, 16I, 32I}
▶ {GL_LUMINANCE, GL_ALPHA, GL_LUMINANCE_ALPHA, GL_INTENSITY} X {8, 16, 16F_ARB,
32F_ARB, 8UI_EXT, 16UI_EXT, 32UI_EXT, 8I_EXT, 16I_EXT, 32I_EXT}
The following image classes are currently disallowed:
▶ Textures with borders
▶ Multisampled renderbuffers
See also:
cudaGraphicsUnregisterResource,
cudaGraphicsMapResources,
cudaGraphicsSubRe-
sourceGetMappedArray, ::cuGraphicsGLRegisterImage
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ resource - - Pointer to the returned object handle
524
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ image - - name of texture or renderbuffer object to be registered
▶ target - - Identifies the type of object specified by image
▶ flags - - Register flags
Returns
cudaSuccess,
cudaErrorInvalidDevice,
cudaErrorInvalidValue,
cudaErrorIn-
validResourceHandle, cudaErrorOperatingSystem, cudaErrorUnknown
__host__ cudaError_t cudaWGLGetDevice(int *device, HGPUNV hGpu)
Gets the CUDA device associated with hGpu.
Returns the CUDA device associated with a hGpu, if applicable.
See also:
::WGL_NV_gpu_affinity, ::cuWGLGetDevice
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ device - - Returns the device associated with hGpu, or -1 if hGpu is not a com-
pute device.
▶ hGpu - - Handle to a GPU, as queried via WGL_NV_gpu_affinity
Returns
cudaSuccess
6.28.3. Typedefs
typedef void *HGPUNV
6.29. OpenGL Interoperability [DEPRECATED]
This section describes deprecated OpenGL interoperability functionality.
6.29. OpenGL Interoperability [DEPRECATED]
525
CUDA Runtime API Reference Manual, Release 13.5
Enumerations
cudaGLMapFlags
CUDA GL Map Flags.
Functions
__host__ cudaError_t cudaGLMapBufferObject(void **devPtr, GLuint bufObj)
Maps a buffer object for access by CUDA.
__host__ cudaError_t cudaGLMapBufferObjectAsync(void **devPtr, GLuint bufObj, cudaStream_t
stream)
Maps a buffer object for access by CUDA.
__host__ cudaError_t cudaGLRegisterBufferObject(GLuint bufObj)
Registers a buffer object for access by CUDA.
__host__ cudaError_t cudaGLSetBufferObjectMapFlags(GLuint bufObj, unsigned int flags)
Set usage flags for mapping an OpenGL buffer.
__host__ cudaError_t cudaGLSetGLDevice(int device)
Sets a CUDA device to use OpenGL interoperability.
__host__ cudaError_t cudaGLUnmapBufferObject(GLuint bufObj)
Unmaps a buffer object for access by CUDA.
__host__ cudaError_t cudaGLUnmapBufferObjectAsync(GLuint bufObj, cudaStream_t stream)
Unmaps a buffer object for access by CUDA.
__host__ cudaError_t cudaGLUnregisterBufferObject(GLuint bufObj)
Unregisters a buffer object for access by CUDA.
6.29.1. Enumerations
enum cudaGLMapFlags
CUDA GL Map Flags.
Values:
enumerator cudaGLMapFlagsNone = 0
Default; Assume resource can be read/written.
enumerator cudaGLMapFlagsReadOnly = 1
CUDA kernels will not write to this resource.
enumerator cudaGLMapFlagsWriteDiscard = 2
CUDA kernels will only write to and will not read from this resource.
526
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
6.29.2. Functions
__host__ cudaError_t cudaGLMapBufferObject(void **devPtr, GLuint bufObj)
Maps a buffer object for access by CUDA.
Deprecated:
This function is deprecated as of CUDA 3.0.
Maps the buffer object of ID bufObj into the address space of CUDA and returns in *devPtr
the base pointer of the resulting mapping. The buffer must have previously been registered by
calling cudaGLRegisterBufferObject(). While a buffer is mapped by CUDA, any OpenGL operation
which references the buffer will result in undefined behavior. The OpenGL context used to create
the buffer, or another context from the same share group, must be bound to the current thread
when this is called.
All streams in the current thread are synchronized with the current GL context.
See also:
cudaGraphicsMapResources
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ devPtr - - Returned device pointer to CUDA object
▶ bufObj - - Buffer object ID to map
Returns
cudaSuccess, cudaErrorMapBufferObjectFailed
__host__ cudaError_t cudaGLMapBufferObjectAsync(void **devPtr, GLuint bufObj, cudaStream_t
stream)
Maps a buffer object for access by CUDA.
Deprecated:
This function is deprecated as of CUDA 3.0.
Maps the buffer object of ID bufObj into the address space of CUDA and returns in *devPtr
the base pointer of the resulting mapping. The buffer must have previously been registered by
calling cudaGLRegisterBufferObject(). While a buffer is mapped by CUDA, any OpenGL operation
which references the buffer will result in undefined behavior. The OpenGL context used to create
the buffer, or another context from the same share group, must be bound to the current thread
when this is called.
Stream /p stream is synchronized with the current GL context.
6.29. OpenGL Interoperability [DEPRECATED]
527
CUDA Runtime API Reference Manual, Release 13.5
See also:
cudaGraphicsMapResources
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ devPtr - - Returned device pointer to CUDA object
▶ bufObj - - Buffer object ID to map
▶ stream - - Stream to synchronize
Returns
cudaSuccess, cudaErrorMapBufferObjectFailed
__host__ cudaError_t cudaGLRegisterBufferObject(GLuint bufObj)
Registers a buffer object for access by CUDA.
Deprecated:
This function is deprecated as of CUDA 3.0.
Registers the buffer object of ID bufObj for access by CUDA. This function must be called before
CUDA can map the buffer object. The OpenGL context used to create the buffer, or another
context from the same share group, must be bound to the current thread when this is called.
See also:
cudaGraphicsGLRegisterBuffer
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
bufObj - - Buffer object ID to register
Returns
cudaSuccess, cudaErrorInitializationError
__host__ cudaError_t cudaGLSetBufferObjectMapFlags(GLuint bufObj, unsigned int flags)
Set usage flags for mapping an OpenGL buffer.
Deprecated:
This function is deprecated as of CUDA 3.0.
Set flags for mapping the OpenGL buffer bufObj
Changes to flags will take effect the next time bufObj is mapped. The flags argument may be
any of the following:
528
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ cudaGLMapFlagsNone: Specifies no hints about how this buffer will be used. It is therefore
assumed that this buffer will be read from and written to by CUDA kernels. This is the default
value.
▶ cudaGLMapFlagsReadOnly: Specifies that CUDA kernels which access this buffer will not
write to the buffer.
▶ cudaGLMapFlagsWriteDiscard: Specifies that CUDA kernels which access this buffer will not
read from the buffer and will write over the entire contents of the buffer, so none of the
data previously stored in the buffer will be preserved.
If bufObj has not been registered for use with CUDA, then cudaErrorInvalidResourceHandle is
returned. If bufObj is presently mapped for access by CUDA, then cudaErrorUnknown is returned.
See also:
cudaGraphicsResourceSetMapFlags
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ bufObj - - Registered buffer object to set flags for
▶ flags - - Parameters for buffer mapping
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle, cudaErrorUn-
known
__host__ cudaError_t cudaGLSetGLDevice(int device)
Sets a CUDA device to use OpenGL interoperability.
Deprecated:
This function is deprecated as of CUDA 5.0.
This function is deprecated and should no longer be used. It is no longer necessary to associate a
CUDA device with an OpenGL context in order to achieve maximum interoperability performance.
This function will immediately initialize the primary context on device if needed.
See also:
cudaGraphicsGLRegisterBuffer, cudaGraphicsGLRegisterImage
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
device - - Device to use for OpenGL interoperability
Returns
cudaSuccess, cudaErrorInvalidDevice, cudaErrorSetOnActiveProcess
6.29. OpenGL Interoperability [DEPRECATED]
529
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaGLUnmapBufferObject(GLuint bufObj)
Unmaps a buffer object for access by CUDA.
Deprecated:
This function is deprecated as of CUDA 3.0.
Unmaps the buffer object of ID bufObj for access by CUDA. When a buffer is unmapped, the
base address returned by cudaGLMapBufferObject() is invalid and subsequent references to the
address result in undefined behavior. The OpenGL context used to create the buffer, or another
context from the same share group, must be bound to the current thread when this is called.
All streams in the current thread are synchronized with the current GL context.
See also:
cudaGraphicsUnmapResources
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
bufObj - - Buffer object to unmap
Returns
cudaSuccess, cudaErrorUnmapBufferObjectFailed
__host__ cudaError_t cudaGLUnmapBufferObjectAsync(GLuint bufObj, cudaStream_t stream)
Unmaps a buffer object for access by CUDA.
Deprecated:
This function is deprecated as of CUDA 3.0.
Unmaps the buffer object of ID bufObj for access by CUDA. When a buffer is unmapped, the
base address returned by cudaGLMapBufferObject() is invalid and subsequent references to the
address result in undefined behavior. The OpenGL context used to create the buffer, or another
context from the same share group, must be bound to the current thread when this is called.
Stream /p stream is synchronized with the current GL context.
See also:
cudaGraphicsUnmapResources
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ bufObj - - Buffer object to unmap
▶ stream - - Stream to synchronize
530
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Returns
cudaSuccess, cudaErrorUnmapBufferObjectFailed
__host__ cudaError_t cudaGLUnregisterBufferObject(GLuint bufObj)
Unregisters a buffer object for access by CUDA.
Deprecated:
This function is deprecated as of CUDA 3.0.
Unregisters the buffer object of ID bufObj for access by CUDA and releases any CUDA resources
associated with the buffer. Once a buffer is unregistered, it may no longer be mapped by CUDA.
The GL context used to create the buffer, or another context from the same share group, must
be bound to the current thread when this is called.
See also:
cudaGraphicsUnregisterResource
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
bufObj - - Buffer object to unregister
Returns
cudaSuccess
6.30. Peer Device Memory Access
This section describes the peer device memory access functions of the CUDA runtime application
programming interface.
Functions
__host__ cudaError_t cudaDeviceCanAccessPeer(int *canAccessPeer, int device, int peerDevice)
Queries if a device may directly access a peer device's memory.
__host__ cudaError_t cudaDeviceDisablePeerAccess(int peerDevice)
Disables direct access to memory allocations on a peer device.
__host__ cudaError_t cudaDeviceEnablePeerAccess(int peerDevice, unsigned int flags)
Enables direct access to memory allocations on a peer device.
6.30. Peer Device Memory Access
531
CUDA Runtime API Reference Manual, Release 13.5
6.30.1. Functions
__host__ cudaError_t cudaDeviceCanAccessPeer(int *canAccessPeer, int device, int peerDevice)
Queries if a device may directly access a peer device’s memory.
Returns in *canAccessPeer a value of 1 if device device is capable of directly accessing mem-
ory from peerDevice and 0 otherwise. If direct access of peerDevice from device is possible,
then access may be enabled by calling cudaDeviceEnablePeerAccess().
See also:
cudaDeviceEnablePeerAccess, cudaDeviceDisablePeerAccess, ::cuDeviceCanAccessPeer
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ canAccessPeer - - Returned access capability
▶ device - - Device from which allocations on peerDevice are to be directly ac-
cessed.
▶ peerDevice - - Device on which the allocations to be directly accessed by de-
vice reside.
Returns
cudaSuccess, cudaErrorInvalidDevice
__host__ cudaError_t cudaDeviceDisablePeerAccess(int peerDevice)
Disables direct access to memory allocations on a peer device.
Returns cudaErrorPeerAccessNotEnabled if direct access to memory on peerDevice has not yet
been enabled from the current device.
See also:
cudaDeviceCanAccessPeer, cudaDeviceEnablePeerAccess, ::cuCtxDisablePeerAccess
Note: Note that this function may also return error codes from previous, asynchronous launches.
532
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
peerDevice - - Peer device to disable direct access to
Returns
cudaSuccess, cudaErrorPeerAccessNotEnabled, cudaErrorInvalidDevice
__host__ cudaError_t cudaDeviceEnablePeerAccess(int peerDevice, unsigned int flags)
Enables direct access to memory allocations on a peer device.
On success, all allocations from peerDevice will immediately be accessible by the current device.
They will remain accessible until access is explicitly disabled using cudaDeviceDisablePeerAccess()
or either device is reset using cudaDeviceReset().
Note that access granted by this call is unidirectional and that in order to access memory on the
current device from peerDevice, a separate symmetric call to cudaDeviceEnablePeerAccess() is
required.
Note that there are both device-wide and system-wide limitations per system configuration, as
noted in the CUDA Programming Guide under the section “Peer-to-Peer Memory Access”.
Returns cudaErrorInvalidDevice if cudaDeviceCanAccessPeer() indicates that the current device
cannot directly access memory from peerDevice.
Returns cudaErrorPeerAccessAlreadyEnabled if direct access of peerDevice from the current
device has already been enabled.
Returns cudaErrorInvalidValue if flags is not 0.
See also:
cudaDeviceCanAccessPeer, cudaDeviceDisablePeerAccess, ::cuCtxEnablePeerAccess
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
6.30. Peer Device Memory Access
533
CUDA Runtime API Reference Manual, Release 13.5
Parameters
▶ peerDevice - - Peer device to enable direct access to from the current device
▶ flags - - Reserved for future use and must be set to 0
Returns
cudaSuccess, cudaErrorInvalidDevice, cudaErrorPeerAccessAlreadyEnabled, cudaEr-
rorInvalidValue
6.31. Profiler Control
This section describes the profiler control functions of the CUDA runtime application programming
interface.
Functions
__host__ cudaError_t cudaProfilerStart(void)
Enable profiling.
__host__ cudaError_t cudaProfilerStop(void)
Disable profiling.
6.31.1. Functions
__host__ cudaError_t cudaProfilerStart(void)
Enable profiling.
Enables profile collection by the active profiling tool for the current context. If profiling is already
enabled, then cudaProfilerStart() has no effect.
cudaProfilerStart and cudaProfilerStop APIs are used to programmatically control the profiling
granularity by allowing profiling to be done only on selective pieces of code.
See also:
cudaProfilerStop, ::cuProfilerStart
Note: Note that this function may also return error codes from previous, asynchronous launches.
Returns
cudaSuccess
__host__ cudaError_t cudaProfilerStop(void)
Disable profiling.
Disables profile collection by the active profiling tool for the current context. If profiling is already
disabled, then cudaProfilerStop() has no effect.
534
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
cudaProfilerStart and cudaProfilerStop APIs are used to programmatically control the profiling
granularity by allowing profiling to be done only on selective pieces of code.
See also:
cudaProfilerStart, ::cuProfilerStop
Note: Note that this function may also return error codes from previous, asynchronous launches.
Returns
cudaSuccess
6.32. Stream Management
This section describes the stream management functions of the CUDA runtime application program-
ming interface.
Functions
__host__ cudaError_t cudaCtxResetPersistingL2Cache(void)
Resets all persisting lines in cache to normal status.
__host__ cudaError_t cudaStreamAddCallback(cudaStream_t stream, cudaStreamCallback_t call-
back, void *userData, unsigned int flags)
Add a callback to a compute stream.
__host__ cudaError_t cudaStreamAttachMemAsync(cudaStream_t stream, void *devPtr, size_t
length=0, unsigned int flags=0x04)
Attach memory to a stream asynchronously.
__host__ cudaError_t cudaStreamBeginCapture(cudaStream_t stream, enum cudaStreamCapture-
Mode mode)
Begins graph capture on a stream.
__host__ cudaError_t cudaStreamBeginCaptureToGraph(cudaStream_t stream, cudaGraph_t graph,
const cudaGraphNode_t *dependencies, const cudaGraphEdgeData *dependencyData, size_t
numDependencies, enum cudaStreamCaptureMode mode)
Begins graph capture on a stream to an existing graph.
__host__ cudaError_t cudaStreamBeginRecaptureToGraph(cudaStream_t stream, enum cudaS-
treamCaptureMode mode, cudaGraph_t graph, struct cudaGraphRecaptureCallbackData *call-
backData=0)
Begin graph capture on a stream to an existing graph.
__host__ cudaError_t cudaStreamCopyAttributes(cudaStream_t dst, cudaStream_t src)
Copies attributes from source stream to destination stream.
__host__ cudaError_t cudaStreamCreate(cudaStream_t *pStream)
Create an asynchronous stream.
__host__ cudaError_t cudaStreamCreateWithFlags(cudaStream_t *pStream, unsigned int flags)
Create an asynchronous stream.
6.32. Stream Management
535
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaStreamCreateWithPriority(cudaStream_t *pStream, unsigned int flags,
int priority)
Create an asynchronous stream with the specified priority.
__host__ cudaError_t cudaStreamDestroy(cudaStream_t stream)
Destroys and cleans up an asynchronous stream.
__host__ cudaError_t cudaStreamEndCapture(cudaStream_t stream, cudaGraph_t *pGraph)
Ends capture on a stream, returning the captured graph.
__host__ cudaError_t cudaStreamGetAttribute(cudaStream_t hStream, cudaLaunchAttributeID
attr, cudaLaunchAttributeValue *value_out)
Queries stream attribute.
__host__ cudaError_t cudaStreamGetCaptureInfo(cudaStream_t stream, enum cudaStreamCap-
tureStatus *captureStatus_out, unsigned long long *id_out=0, cudaGraph_t *graph_out=0,
const cudaGraphNode_t
**dependencies_out=0,
const cudaGraphEdgeData
**edge-
Data_out=0, size_t *numDependencies_out=0)
Query a stream's capture state.
__host__ cudaError_t cudaStreamGetDevice(cudaStream_t hStream, int *device)
Query the device of a stream.
__host__ cudaError_t cudaStreamGetFlags(cudaStream_t hStream, unsigned int *flags)
Query the flags of a stream.
__host__ cudaError_t cudaStreamGetId(cudaStream_t hStream, unsigned long long *streamId)
Query the Id of a stream.
__host__ cudaError_t cudaStreamGetPriority(cudaStream_t hStream, int *priority)
Query the priority of a stream.
__host__ cudaError_t cudaStreamIsCapturing(cudaStream_t stream, enum cudaStreamCap-
tureStatus *pCaptureStatus)
Returns a stream's capture status.
__host__ cudaError_t cudaStreamQuery(cudaStream_t stream)
Queries an asynchronous stream for completion status.
__host__ cudaError_t cudaStreamSetAttribute(cudaStream_t hStream, cudaLaunchAttributeID
attr, const cudaLaunchAttributeValue *value)
Sets stream attribute.
__host__ cudaError_t cudaStreamSynchronize(cudaStream_t stream)
Waits for stream tasks to complete.
__host__ cudaError_t cudaStreamUpdateCaptureDependencies(cudaStream_t stream, cuda-
GraphNode_t *dependencies, const cudaGraphEdgeData *dependencyData, size_t numDe-
pendencies, unsigned int flags=0)
Update the set of dependencies in a capturing stream.
__host__ cudaError_t cudaStreamWaitEvent(cudaStream_t stream, cudaEvent_t event, unsigned int
flags=0)
Make a compute stream wait on an event.
__host__ cudaError_t cudaThreadExchangeStreamCaptureMode(enum cudaStreamCaptureMode
*mode)
Swaps the stream capture interaction mode for a thread.
536
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Structs
cudaGraphRecaptureCallbackData
Struct of user callback data that is invoked when node parameter mismatches are detected while
recapturing to an existing graph.
Typedefs
cudaGraphRecaptureCallback_t
Callback function invoked when node parameter mismatches are detected while recapturing to
an existing graph.
cudaStreamCallback_t
Type of stream callback functions.
6.32.1. Functions
__host__ cudaError_t cudaCtxResetPersistingL2Cache(void)
Resets all persisting lines in cache to normal status.
Resets all persisting lines in cache to normal status. Takes effect on function return.
See also:
cudaAccessPolicyWindow
Note: Note that this function may also return error codes from previous, asynchronous launches.
Returns
cudaSuccess,
__host__ cudaError_t cudaStreamAddCallback(cudaStream_t stream, cudaStreamCallback_t
callback, void *userData, unsigned int flags)
Add a callback to a compute stream.
Adds a callback to be called on the host after all currently enqueued items in the stream have
completed. For each cudaStreamAddCallback call, a callback will be executed exactly once. The
callback will block later work in the stream until it is finished.
The callback may be passed cudaSuccess or an error code. In the event of a device error, all
subsequently executed callbacks will receive an appropriate cudaError_t.
Callbacks must not make any CUDA API calls. Attempting to use CUDA APIs may result in cud-
aErrorNotPermitted. Callbacks must not perform any synchronization that may depend on out-
standing device work or other callbacks that are not mandated to run earlier. Callbacks without
a mandated order (in independent streams) execute in undefined order and may be serialized.
For the purposes of Unified Memory, callback execution makes a number of guarantees:
6.32. Stream Management
537
CUDA Runtime API Reference Manual, Release 13.5
▶ The callback stream is considered idle for the duration of the callback. Thus, for example, a
callback may always use memory attached to the callback stream.
▶ The start of execution of a callback has the same effect as synchronizing an event recorded
in the same stream immediately prior to the callback. It thus synchronizes streams which
have been “joined” prior to the callback.
▶ Adding device work to any stream does not have the effect of making the stream active
until all preceding callbacks have executed. Thus, for example, a callback might use global
attached memory even if work has been added to another stream, if it has been properly
ordered with an event.
▶ Completion of a callback does not cause a stream to become active except as described
above. The callback stream will remain idle if no device work follows the callback, and will
remain idle across consecutive callbacks without device work in between. Thus, for example,
stream synchronization can be done by signaling from a callback at the end of the stream.
See also:
cudaStreamCreate, cudaStreamCreateWithFlags, cudaStreamQuery, cudaStreamSynchronize, cu-
daStreamWaitEvent, cudaStreamDestroy, cudaMallocManaged, cudaStreamAttachMemAsync, cu-
daLaunchHostFunc, ::cuStreamAddCallback
Note: This function is slated for eventual deprecation and removal. If you do not require the
callback to execute in case of a device error, consider using cudaLaunchHostFunc. Additionally,
this function is not supported with cudaStreamBeginCapture and cudaStreamEndCapture, unlike
cudaLaunchHostFunc.
Note: This function uses standard default stream semantics.
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ stream - - Stream to add callback to
▶ callback - - The function to call once preceding stream operations are com-
plete
▶ userData - - User specified data to be passed to the callback function
538
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ flags - - Reserved for future use, must be 0
Returns
cudaSuccess, cudaErrorInvalidResourceHandle, cudaErrorInvalidValue, cudaEr-
rorNotSupported
__host__ cudaError_t cudaStreamAttachMemAsync(cudaStream_t stream, void *devPtr, size_t
length = 0, unsigned int flags = 0x04)
Attach memory to a stream asynchronously.
Enqueues an operation in stream to specify stream association of length bytes of memory
starting from devPtr. This function is a stream-ordered operation, meaning that it is depen-
dent on, and will only take effect when, previous work in stream has completed. Any previous
association is automatically replaced.
devPtr must point to an one of the following types of memories:
▶ managed memory declared using the managed keyword or allocated with cudaMallocMan-
aged.
▶ a valid host-accessible region of system-allocated pageable memory. This type of memory
may only be specified if the device associated with the stream reports a non-zero value for
the device attribute cudaDevAttrPageableMemoryAccess.
For managed allocations, length must be either zero or the entire allocation’s size. Both indicate
that the entire allocation’s stream association is being changed. Currently, it is not possible to
change stream association for a portion of a managed allocation.
For pageable allocations, length must be non-zero.
The stream association is specified using flags which must be one of cudaMemAttachGlobal,
cudaMemAttachHost or cudaMemAttachSingle. The default value for flags is cudaMemAttachS-
ingle If the cudaMemAttachGlobal flag is specified, the memory can be accessed by any stream
on any device. If the cudaMemAttachHost flag is specified, the program makes a guarantee that
it won’t access the memory on the device from any stream on a device that has a zero value for
the device attribute cudaDevAttrConcurrentManagedAccess. If the cudaMemAttachSingle flag is
specified and stream is associated with a device that has a zero value for the device attribute
cudaDevAttrConcurrentManagedAccess, the program makes a guarantee that it will only access
the memory on the device from stream. It is illegal to attach singly to the NULL stream, because
the NULL stream is a virtual global stream and not a specific stream. An error will be returned in
this case.
When memory is associated with a single stream, the Unified Memory system will allow CPU
access to this memory region so long as all operations in stream have completed, regardless of
whether other streams are active. In effect, this constrains exclusive ownership of the managed
memory region by an active GPU to per-stream activity instead of whole-GPU activity.
Accessing memory on the device from streams that are not associated with it will produce un-
defined results. No error checking is performed by the Unified Memory system to ensure that
kernels launched into other streams do not access this region.
It is a program’s responsibility to order calls to cudaStreamAttachMemAsync via events, synchro-
nization or other means to ensure legal access to memory at all times. Data visibility and co-
herency will be changed appropriately for all kernels which follow a stream-association change.
If stream is destroyed while data is associated with it, the association is removed and the asso-
ciation reverts to the default visibility of the allocation as specified at cudaMallocManaged. For
managed variables, the default association is always cudaMemAttachGlobal. Note that destroy-
ing a stream is an asynchronous operation, and as a result, the change to default association
won’t happen until all work in the stream has completed.
6.32. Stream Management
539
CUDA Runtime API Reference Manual, Release 13.5
See also:
cudaStreamCreate, cudaStreamCreateWithFlags, cudaStreamWaitEvent, cudaStreamSynchronize,
cudaStreamAddCallback, cudaStreamDestroy, cudaMallocManaged, ::cuStreamAttachMemAsync
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ flags - Memory can only be accessed by a single stream on the associated
device
▶ stream - - Stream in which to enqueue the attach operation
▶ devPtr - - Pointer to memory (must be a pointer to managed memory or to a
valid host-accessible region of system-allocated memory)
▶ length - - Length of memory (defaults to zero)
▶ flags - - Must be one of cudaMemAttachGlobal, cudaMemAttachHost or cud-
aMemAttachSingle (defaults to cudaMemAttachSingle)
Returns
cudaSuccess, cudaErrorNotReady, cudaErrorInvalidValue, cudaErrorInvalidResource-
Handle
__host__ cudaError_t cudaStreamBeginCapture(cudaStream_t stream, enum
cudaStreamCaptureMode mode)
Begins graph capture on a stream.
Begin graph capture on stream. When a stream is in capture mode, all operations pushed into
the stream will not be executed, but will instead be captured into a graph, which will be returned
via cudaStreamEndCapture. Capture may not be initiated if stream is cudaStreamLegacy. Cap-
ture must be ended on the same stream in which it was initiated, and it may only be initiated if
the stream is not already in capture mode. The capture mode may be queried via cudaStreamIs-
Capturing. A unique id representing the capture sequence may be queried via cudaStreamGet-
CaptureInfo.
If mode is not cudaStreamCaptureModeRelaxed, cudaStreamEndCapture must be called on this
stream from the same thread.
540
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
See also:
cudaStreamCreate,
cudaStreamIsCapturing,
cudaStreamEndCapture,
cudaThreadEx-
changeStreamCaptureMode
Note: Kernels captured using this API must not use texture and surface references. Reading or
writing through any texture or surface reference is undefined behavior. This restriction does not
apply to texture and surface objects.
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ stream - - Stream in which to initiate capture
▶ mode - - Controls the interaction of this capture sequence with other API calls
that are potentially unsafe. For more details see cudaThreadExchangeStream-
CaptureMode.
Returns
cudaSuccess, cudaErrorInvalidValue
__host__ cudaError_t cudaStreamBeginCaptureToGraph(cudaStream_t stream, cudaGraph_t
graph, const cudaGraphNode_t
*dependencies, const
cudaGraphEdgeData *dependencyData,
size_t numDependencies, enum
cudaStreamCaptureMode mode)
Begins graph capture on a stream to an existing graph.
Begin graph capture on stream. When a stream is in capture mode, all operations pushed into
the stream will not be executed, but will instead be captured into graph, which will be returned
via cudaStreamEndCapture.
Capture may not be initiated if stream is cudaStreamLegacy. Capture must be ended on the same
stream in which it was initiated, and it may only be initiated if the stream is not already in capture
mode. The capture mode may be queried via cudaStreamIsCapturing. A unique id representing
the capture sequence may be queried via cudaStreamGetCaptureInfo.
If mode is not cudaStreamCaptureModeRelaxed, cudaStreamEndCapture must be called on this
stream from the same thread.
See also:
cudaStreamCreate,
cudaStreamIsCapturing,
cudaStreamEndCapture,
cudaThreadEx-
changeStreamCaptureMode
Note: Kernels captured using this API must not use texture and surface references. Reading or
writing through any texture or surface reference is undefined behavior. This restriction does not
apply to texture and surface objects.
6.32. Stream Management
541
CUDA Runtime API Reference Manual, Release 13.5
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ stream - - Stream in which to initiate capture.
▶ graph - - Graph to capture into.
▶ dependencies - - Dependencies of the first node captured in the stream. Can
be NULL if numDependencies is 0.
▶ dependencyData - - Optional array of data associated with each dependency.
▶ numDependencies - - Number of dependencies.
▶ mode - - Controls the interaction of this capture sequence with other API calls
that are potentially unsafe. For more details see cudaThreadExchangeStream-
CaptureMode.
Returns
cudaSuccess, cudaErrorInvalidValue
__host__ cudaError_t cudaStreamBeginRecaptureToGraph(cudaStream_t stream, enum
cudaStreamCaptureMode mode,
cudaGraph_t graph, struct
cudaGraphRecaptureCallbackData
*callbackData = 0)
Begin graph capture on a stream to an existing graph.
Begin graph capture on stream to the existing graph. The node creation order while recapturing
the graph must be identical to the original graph. The recapture will fail immediately for:
▶ Topology mismatches between the existing graph and the recaptured graph
▶ Parameter mismatches for memory allocation or free nodes
Any other node parameter mismatches during recapture can be configured to call the function
provided in callbackFunc. The recapture will fail immediately if the callback returns anything
other than cudaSuccess.
If the recapture fails for any reason, the graph will be in an undefined state and should be de-
stroyed.
See cudaStreamBeginCapture for additional detail on beginning the capture.
See also:
cudaStreamCreate, cudaStreamBeginCapture, cudaStreamIsCapturing, cudaStreamEndCapture,
cudaThreadExchangeStreamCaptureMode
Note: Any user objects associated with graph will be released prior to the recapture.
Note: Note that this function may also return error codes from previous, asynchronous launches.
542
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Parameters
▶ stream - - Stream in which to initiate capture
▶ mode - - Controls the interaction of this capture sequence with other API calls
that are potentially unsafe. For more details see cudaThreadExchangeStream-
CaptureMode.
▶ graph - - Existing CUDA graph to be captured into
▶ callbackData - - Optional struct of callback data that will be invoked for all
parameter mismatches from the original graph
Returns
cudaSuccess, ::cudaErrorDeinitialized, ::cudaErrorNotInitialized, cudaErrorInvalid-
Value,
__host__ cudaError_t cudaStreamCopyAttributes(cudaStream_t dst, cudaStream_t src)
Copies attributes from source stream to destination stream.
Copies attributes from source stream src to destination stream dst. Both streams must have
the same context.
See also:
cudaAccessPolicyWindow
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ dst - [out] Destination stream
▶ src - [in] Source stream For attributes see cudaStreamAttrID
Returns
cudaSuccess, cudaErrorNotSupported
__host__ cudaError_t cudaStreamCreate(cudaStream_t *pStream)
Create an asynchronous stream.
Creates a new asynchronous stream on the context that is current to the calling host thread. If
no context is current to the calling host thread, then the primary context for a device is selected,
made current to the calling thread, and initialized before creating a stream on it.
See also:
cudaStreamCreateWithPriority,
cudaStreamCreateWithFlags,
cudaStreamGetPriority,
cud-
aStreamGetFlags,
cudaStreamGetDevice,
cudaStreamGetDevResource,
cudaStreamQuery,
cudaStreamSynchronize, cudaStreamWaitEvent, cudaStreamAddCallback, cudaSetDevice, cudaS-
treamDestroy, ::cuStreamCreate
Note: Note that this function may also return error codes from previous, asynchronous launches.
6.32. Stream Management
543
CUDA Runtime API Reference Manual, Release 13.5
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
pStream - - Pointer to new stream identifier
Returns
cudaSuccess, cudaErrorInvalidValue cudaErrorExternalDevice
__host__ cudaError_t cudaStreamCreateWithFlags(cudaStream_t *pStream, unsigned int flags)
Create an asynchronous stream.
Creates a new asynchronous stream on the context that is current to the calling host thread. If
no context is current to the calling host thread, then the primary context for a device is selected,
made current to the calling thread, and initialized before creating a stream on it. The flags
argument determines the behaviors of the stream. Valid values for flags are
▶ cudaStreamDefault: Default stream creation flag.
▶ cudaStreamNonBlocking: Specifies that work running in the created stream may run concur-
rently with work in stream 0 (the NULL stream), and that the created stream should perform
no implicit synchronization with stream 0.
See also:
cudaStreamCreate, cudaStreamCreateWithPriority, cudaStreamGetFlags, cudaStreamGetDevice,
cudaStreamGetDevResource, cudaStreamQuery, cudaStreamSynchronize, cudaStreamWaitEvent,
cudaStreamAddCallback, cudaSetDevice, cudaStreamDestroy, ::cuStreamCreate
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ pStream - - Pointer to new stream identifier
▶ flags - - Parameters for stream creation
544
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Returns
cudaSuccess, cudaErrorInvalidValue cudaErrorExternalDevice
__host__ cudaError_t cudaStreamCreateWithPriority(cudaStream_t *pStream, unsigned int
flags, int priority)
Create an asynchronous stream with the specified priority.
Creates a stream with the specified priority and returns a handle in pStream. The stream is
created on the context that is current to the calling host thread. If no context is current to
the calling host thread, then the primary context for a device is selected, made current to the
calling thread, and initialized before creating a stream on it. This affects the scheduling priority
of work in the stream. Priorities provide a hint to preferentially run work with higher priority when
possible, but do not preempt already-running work or provide any other functional guarantee on
execution order.
priority follows a convention where lower numbers represent higher priorities. ‘0’ represents
default priority. The range of meaningful numerical priorities can be queried using cudaDe-
viceGetStreamPriorityRange. If the specified priority is outside the numerical range returned by
cudaDeviceGetStreamPriorityRange, it will automatically be clamped to the lowest or the highest
number in the range.
See also:
cudaStreamCreate, cudaStreamCreateWithFlags, cudaDeviceGetStreamPriorityRange, cudaS-
treamGetPriority, cudaStreamQuery, cudaStreamWaitEvent, cudaStreamAddCallback, cudaS-
treamSynchronize, cudaSetDevice, cudaStreamDestroy, ::cuStreamCreateWithPriority
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Note: Stream priorities are supported only on GPUs with compute capability 3.5 or higher.
Note: In the current implementation, only compute kernels launched in priority streams are
affected by the stream’s priority. Stream priorities have no effect on host-to-device and device-
to-host memory operations.
Parameters
▶ pStream - - Pointer to new stream identifier
6.32. Stream Management
545
CUDA Runtime API Reference Manual, Release 13.5
▶ flags - - Flags for stream creation. See cudaStreamCreateWithFlags for a list
of valid flags that can be passed
▶ priority - - Priority of the stream. Lower numbers represent higher priorities.
See cudaDeviceGetStreamPriorityRange for more information about the mean-
ingful stream priorities that can be passed.
Returns
cudaSuccess, cudaErrorInvalidValue cudaErrorExternalDevice
__host__ cudaError_t cudaStreamDestroy(cudaStream_t stream)
Destroys and cleans up an asynchronous stream.
Destroys and cleans up the asynchronous stream specified by stream.
In case the device is still doing work in the stream stream when cudaStreamDestroy() is called,
the function will return immediately and the resources associated with stream will be released
automatically once the device has completed all work in stream.
See also:
cudaStreamCreate, cudaStreamCreateWithFlags, cudaStreamQuery, cudaStreamWaitEvent, cud-
aStreamSynchronize, cudaStreamAddCallback, ::cuStreamDestroy
Note: This function uses standard default stream semantics.
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Note: Use of the handle after this call is undefined behavior.
Parameters
stream - - Stream identifier
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle
__host__ cudaError_t cudaStreamEndCapture(cudaStream_t stream, cudaGraph_t *pGraph)
Ends capture on a stream, returning the captured graph.
End capture on stream, returning the captured graph via pGraph. Capture must have been ini-
tiated on stream via a call to cudaStreamBeginCapture. If capture was invalidated, due to a vio-
lation of the rules of stream capture, then a NULL graph will be returned.
546
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
If the mode argument to cudaStreamBeginCapture was not cudaStreamCaptureModeRelaxed,
this call must be from the same thread as cudaStreamBeginCapture.
See also:
cudaStreamCreate, cudaStreamBeginCapture, cudaStreamIsCapturing, cudaGraphDestroy
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ stream - - Stream to query
▶ pGraph - - The captured graph
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorStreamCaptureWrongThread
__host__ cudaError_t cudaStreamGetAttribute(cudaStream_t hStream, cudaLaunchAttributeID
attr, cudaLaunchAttributeValue *value_out)
Queries stream attribute.
Queries attribute attr from hStream and stores it in corresponding member of value_out.
See also:
cudaAccessPolicyWindow
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ hStream - [in]
▶ attr - [in]
▶ value_out -
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle
__host__ cudaError_t cudaStreamGetCaptureInfo(cudaStream_t stream, enum
cudaStreamCaptureStatus *captureStatus_out,
unsigned long long *id_out = 0, cudaGraph_t
*graph_out = 0, const cudaGraphNode_t
**dependencies_out = 0, const
cudaGraphEdgeData **edgeData_out = 0, size_t
*numDependencies_out = 0)
Query a stream’s capture state.
Query stream state related to stream capture.
6.32. Stream Management
547
CUDA Runtime API Reference Manual, Release 13.5
If called on cudaStreamLegacy (the “null stream”) while a stream not created with cudaStream-
NonBlocking is capturing, returns cudaErrorStreamCaptureImplicit.
Valid data (other than capture status) is returned only if both of the following are true:
▶ the call returns cudaSuccess
▶ the returned capture status is cudaStreamCaptureStatusActive
If edgeData_out is non-NULL then dependencies_out must be as well. If dependencies_out
is non-NULL and edgeData_out is NULL, but there is non-zero edge data for one or more of the
current stream dependencies, the call will return cudaErrorLossyQuery.
See also:
cudaStreamBeginCapture, cudaStreamIsCapturing, cudaStreamUpdateCaptureDependencies
Note: Graph objects are not threadsafe. More here.
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ stream - - The stream to query
▶ captureStatus_out - - Location to return the capture status of the stream;
required
▶ id_out - - Optional location to return an id for the capture sequence, which is
unique over the lifetime of the process
▶ graph_out - - Optional location to return the graph being captured into. All
operations other than destroy and node removal are permitted on the graph
while the capture sequence is in progress. This API does not transfer owner-
ship of the graph, which is transferred or destroyed at cudaStreamEndCapture.
Note that the graph handle may be invalidated before end of capture for cer-
tain errors. Nodes that are or become unreachable from the original stream at
cudaStreamEndCapture due to direct actions on the graph do not trigger cud-
aErrorStreamCaptureUnjoined.
▶ dependencies_out - - Optional location to store a pointer to an array of nodes.
The next node to be captured in the stream will depend on this set of nodes,
absent operations such as event wait which modify this set. The array pointer
is valid until the next API call which operates on the stream or until the capture
is terminated. The node handles may be copied out and are valid until they or
the graph is destroyed. The driver-owned array may also be passed directly to
APIs that operate on the graph (not the stream) without copying.
▶ edgeData_out - - Optional location to store a pointer to an array of graph edge
data. This array parallels dependencies_out; the next node to be added has
an edge to dependencies_out[i] with annotation edgeData_out[i] for each
i. The array pointer is valid until the next API call which operates on the stream
or until the capture is terminated.
548
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ numDependencies_out - - Optional location to store the size of the array re-
turned in dependencies_out.
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorStreamCaptureImplicit, cudaError-
LossyQuery
__host__ cudaError_t cudaStreamGetDevice(cudaStream_t hStream, int *device)
Query the device of a stream.
Returns in *device the device of the stream.
See also:
cudaSetDevice, cudaGetDevice, cudaStreamCreate, cudaStreamGetPriority, cudaStreamGetFlags,
::cuStreamGetId
Note: This function uses standard default stream semantics.
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ hStream - - Handle to the stream to be queried
▶ device - - Returns the device to which the stream belongs
Returns
cudaSuccess, cudaErrorInvalidValue, ::cudaErrorDeviceUnavailable,
__host__ cudaError_t cudaStreamGetFlags(cudaStream_t hStream, unsigned int *flags)
Query the flags of a stream.
Query the flags of a stream. The flags are returned in flags. See cudaStreamCreateWithFlags
for a list of valid flags.
See also:
cudaStreamCreateWithPriority, cudaStreamCreateWithFlags, cudaStreamGetPriority, cudaS-
treamGetDevice, ::cuStreamGetFlags
6.32. Stream Management
549
CUDA Runtime API Reference Manual, Release 13.5
Note: This function uses standard default stream semantics.
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ hStream - - Handle to the stream to be queried
▶ flags - - Pointer to an unsigned integer in which the stream’s flags are returned
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle
__host__ cudaError_t cudaStreamGetId(cudaStream_t hStream, unsigned long long *streamId)
Query the Id of a stream.
Query the Id of a stream. The Id is returned in streamId. The Id is unique for the life of the
program.
The stream handle hStream can refer to any of the following:
▶ a stream created via any of the CUDA runtime APIs such as cudaStreamCreate, cudaStream-
CreateWithFlags and cudaStreamCreateWithPriority, or their driver API equivalents such as
::cuStreamCreate or ::cuStreamCreateWithPriority. Passing an invalid handle will result in
undefined behavior.
▶ any of the special streams such as the NULL stream, cudaStreamLegacy and cudaStream-
PerThread respectively. The driver API equivalents of these are also accepted which are
NULL, ::CU_STREAM_LEGACY and ::CU_STREAM_PER_THREAD.
See also:
cudaStreamCreateWithPriority, cudaStreamCreateWithFlags, cudaStreamGetPriority, cudaS-
treamGetFlags, ::cuStreamGetId
Note: This function uses standard default stream semantics.
Note: Note that this function may also return error codes from previous, asynchronous launches.
550
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ hStream - - Handle to the stream to be queried
▶ streamId - - Pointer to an unsigned long long in which the stream Id is returned
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle
__host__ cudaError_t cudaStreamGetPriority(cudaStream_t hStream, int *priority)
Query the priority of a stream.
Query the priority of a stream. The priority is returned in in priority. Note that if the stream
was created with a priority outside the meaningful numerical range returned by cudaDeviceGet-
StreamPriorityRange, this function returns the clamped priority. See cudaStreamCreateWithPri-
ority for details about priority clamping.
See also:
cudaStreamCreateWithPriority, cudaDeviceGetStreamPriorityRange, cudaStreamGetFlags, cudaS-
treamGetDevice, cudaStreamGetDevResource, ::cuStreamGetPriority
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ hStream - - Handle to the stream to be queried
▶ priority - - Pointer to a signed integer in which the stream’s priority is re-
turned
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle
6.32. Stream Management
551
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaStreamIsCapturing(cudaStream_t stream, enum
cudaStreamCaptureStatus *pCaptureStatus)
Returns a stream’s capture status.
Return the capture status of stream via pCaptureStatus. After a successful call, *pCap-
tureStatus will contain one of the following:
▶ cudaStreamCaptureStatusNone: The stream is not capturing.
▶ cudaStreamCaptureStatusActive: The stream is capturing.
▶ cudaStreamCaptureStatusInvalidated: The stream was capturing but an error has invalidated
the capture sequence. The capture sequence must be terminated with cudaStreamEndCap-
ture on the stream where it was initiated in order to continue using stream.
Note that, if this is called on cudaStreamLegacy (the “null stream”) while a blocking stream on the
same device is capturing, it will return cudaErrorStreamCaptureImplicit and *pCaptureStatus
is unspecified after the call. The blocking stream capture is not invalidated.
When a blocking stream is capturing, the legacy stream is in an unusable state until the block-
ing stream capture is terminated. The legacy stream is not supported for stream capture, but
attempted use would have an implicit dependency on the capturing stream(s).
See also:
cudaStreamCreate, cudaStreamBeginCapture, cudaStreamEndCapture
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ stream - - Stream to query
▶ pCaptureStatus - - Returns the stream’s capture status
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorStreamCaptureImplicit
__host__ cudaError_t cudaStreamQuery(cudaStream_t stream)
Queries an asynchronous stream for completion status.
Returns cudaSuccess if all operations in stream have completed, or cudaErrorNotReady if not.
For the purposes of Unified Memory, a return value of cudaSuccess is equivalent to having called
cudaStreamSynchronize().
See also:
cudaStreamCreate, cudaStreamCreateWithFlags, cudaStreamWaitEvent, cudaStreamSynchronize,
cudaStreamAddCallback, cudaStreamDestroy, ::cuStreamQuery
Note: This function uses standard default stream semantics.
552
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
stream - - Stream identifier
Returns
cudaSuccess, cudaErrorNotReady, cudaErrorInvalidResourceHandle
__host__ cudaError_t cudaStreamSetAttribute(cudaStream_t hStream, cudaLaunchAttributeID
attr, const cudaLaunchAttributeValue *value)
Sets stream attribute.
Sets attribute attr on hStream from corresponding attribute of value. The updated attribute
will be applied to subsequent work submitted to the stream. It will not affect previously submit-
ted work.
See also:
cudaAccessPolicyWindow
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ hStream - [out]
▶ attr - [in]
▶ value -
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle
__host__ cudaError_t cudaStreamSynchronize(cudaStream_t stream)
Waits for stream tasks to complete.
Blocks until stream has completed all operations. If the cudaDeviceScheduleBlockingSync flag
was set for this device, the host thread will block until the stream is finished with all of its tasks.
6.32. Stream Management
553
CUDA Runtime API Reference Manual, Release 13.5
See also:
cudaStreamCreate, cudaStreamCreateWithFlags, cudaStreamQuery, cudaStreamWaitEvent, cud-
aStreamAddCallback, cudaStreamDestroy, ::cuStreamSynchronize
Note: This function uses standard default stream semantics.
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
stream - - Stream identifier
Returns
cudaSuccess, cudaErrorInvalidResourceHandle
__host__ cudaError_t cudaStreamUpdateCaptureDependencies(cudaStream_t stream,
cudaGraphNode_t
*dependencies, const
cudaGraphEdgeData
*dependencyData, size_t
numDependencies, unsigned int
flags = 0)
Update the set of dependencies in a capturing stream.
Modifies the dependency set of a capturing stream. The dependency set is the set of nodes that
the next captured node in the stream will depend on.
Valid flags are cudaStreamAddCaptureDependencies and cudaStreamSetCaptureDependencies.
These control whether the set passed to the API is added to the existing set or replaces it. A
flags value of 0 defaults to cudaStreamAddCaptureDependencies.
Nodes that are removed from the dependency set via this API do not result in cudaErrorStream-
CaptureUnjoined if they are unreachable from the stream at cudaStreamEndCapture.
Returns cudaErrorIllegalState if the stream is not capturing.
See also:
cudaStreamBeginCapture, cudaStreamGetCaptureInfo,
Note: Note that this function may also return error codes from previous, asynchronous launches.
554
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Parameters
▶ stream - - The stream to update
▶ dependencies - - The set of dependencies to add
▶ dependencyData - - Optional array of data associated with each dependency.
▶ numDependencies - - The size of the dependencies array
▶ flags - - See above
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorIllegalState
__host__ cudaError_t cudaStreamWaitEvent(cudaStream_t stream, cudaEvent_t event, unsigned
int flags = 0)
Make a compute stream wait on an event.
Makes all future work submitted to stream wait for all work captured in event. See cudaEven-
tRecord() for details on what is captured by an event. The synchronization will be performed
efficiently on the device when applicable. event may be from a different device than stream.
flags include:
▶ cudaEventWaitDefault: Default event creation flag.
▶ cudaEventWaitExternal: Event is captured in the graph as an external event node when per-
forming stream capture.
See also:
cudaStreamCreate, cudaStreamCreateWithFlags, cudaStreamQuery, cudaStreamSynchronize, cu-
daStreamAddCallback, cudaStreamDestroy, ::cuStreamWaitEvent
Note: This function uses standard default stream semantics.
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ stream - - Stream to wait
▶ event - - Event to wait on
6.32. Stream Management
555
CUDA Runtime API Reference Manual, Release 13.5
▶ flags - - Parameters for the operation(See above)
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle
__host__ cudaError_t cudaThreadExchangeStreamCaptureMode(enum cudaStreamCaptureMode
*mode)
Swaps the stream capture interaction mode for a thread.
Sets the calling thread’s stream capture interaction mode to the value contained in *mode, and
overwrites *mode with the previous mode for the thread. To facilitate deterministic behavior
across function or module boundaries, callers are encouraged to use this API in a push-pop fash-
ion:
cudaStreamCaptureMode mode = desiredMode;
cudaThreadExchangeStreamCaptureMode(&mode);
cudaThreadExchangeStreamCaptureMode(&mode); ∕∕ restore previous mode
During stream capture (see cudaStreamBeginCapture), some actions, such as a call to cudaMalloc,
may be unsafe. In the case of cudaMalloc, the operation is not enqueued asynchronously to a
stream, and is not observed by stream capture. Therefore, if the sequence of operations captured
via cudaStreamBeginCapture depended on the allocation being replayed whenever the graph is
launched, the captured graph would be invalid.
Therefore, stream capture places restrictions on API calls that can be made within or concurrently
to a cudaStreamBeginCapture-cudaStreamEndCapture sequence. This behavior can be controlled
via this API and flags to cudaStreamBeginCapture.
A thread’s mode is one of the following:
▶ cudaStreamCaptureModeGlobal: This is the default mode. If the local thread has an on-
going capture sequence that was not initiated with cudaStreamCaptureModeRelaxed at
cuStreamBeginCapture, or if any other thread has a concurrent capture sequence initi-
ated with cudaStreamCaptureModeGlobal, this thread is prohibited from potentially un-
safe API calls.
▶ cudaStreamCaptureModeThreadLocal: If the local thread has an ongoing capture se-
quence not initiated with cudaStreamCaptureModeRelaxed, it is prohibited from poten-
tially unsafe API calls. Concurrent capture sequences in other threads are ignored.
▶ cudaStreamCaptureModeRelaxed: The local thread is not prohibited from potentially un-
safe API calls. Note that the thread is still prohibited from API calls which necessarily con-
flict with stream capture, for example, attempting cudaEventQuery on an event that was
last recorded inside a capture sequence.
See also:
cudaStreamBeginCapture
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
mode - - Pointer to mode value to swap with the current mode
556
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Returns
cudaSuccess, cudaErrorInvalidValue
6.32.2. Typedefs
cudaError_t(__stdcall * cudaGraphRecaptureCallback_t )(void *data,
cudaGraphNode_t node, const struct cudaGraphNodeParams *originalParams,
const struct cudaGraphNodeParams *recaptureParams,
enum cudaGraphRecaptureStatus status)
Callback function invoked when node parameter mismatches are detected while recapturing to
an existing graph.
Parameter struct pointers are only valid within the callback.
Param data
User parameter provided at beginning of recapture
Param node
Graph node with the parameter mismatch
Param originalParams
The original node parameters from the graph
Param recaptureParams
The node parameters received during the recapture
Param status
status Status code for the recapture of the node
Return
Error code for the callback. Anything other than cudaSuccess will cause the recap-
ture to fail immediately.
void(__stdcall * cudaStreamCallback_t )(cudaStream_t stream,
cudaError_t status, void *userData)
Type of stream callback functions.
Param stream
The stream as passed to cudaStreamAddCallback, may be NULL.
Param status
cudaSuccess or any persistent error on the stream.
Param userData
User parameter provided at registration.
6.32. Stream Management
557
CUDA Runtime API Reference Manual, Release 13.5
6.33. Stream Ordered Memory Allocator
Functions for controlling the behavior of the underlying allocator.
6.33.1. overview
The asynchronous allocator allows the user to allocate and free in stream order. All asynchronous
accesses of the allocation must happen between the stream executions of the allocation and the free.
If the memory is accessed outside of the promised stream order, a use before allocation / use after
free error will cause undefined behavior.
The allocator is free to reallocate the memory as long as it can guarantee that compliant memory
accesses will not overlap temporally. The allocator may refer to internal stream ordering as well as
inter-stream dependencies (such as CUDA events and null stream dependencies) when establishing
the temporal guarantee. The allocator may also insert inter-stream dependencies to establish the
temporal guarantee.
6.33.2. Supported Platforms
Whether or not a device supports the integrated stream ordered memory allocator may be queried by
calling cudaDeviceGetAttribute() with the device attribute cudaDevAttrMemoryPoolsSupported.
Functions
__host__ cudaError_t cudaFreeAsync(void *devPtr, cudaStream_t hStream)
Frees memory with stream ordered semantics.
__host__ cudaError_t cudaMallocAsync(void **devPtr, size_t size, cudaStream_t hStream)
Allocates memory with stream ordered semantics.
__host__ cudaError_t cudaMallocFromPoolAsync(void **ptr, size_t size, cudaMemPool_t memPool,
cudaStream_t stream)
Allocates memory from a specified pool with stream ordered semantics.
__host__ cudaError_t cudaMemGetDefaultMemPool(cudaMemPool_t *memPool, struct cudaMem-
Location *location, enum cudaMemAllocationType type)
Returns the default memory pool for a given location and allocation type.
__host__ cudaError_t cudaMemGetMemPool(cudaMemPool_t *memPool, struct cudaMemLocation
*location, enum cudaMemAllocationType type)
Gets the current memory pool for a given memory location and allocation type.
__host__ cudaError_t cudaMemPoolCreate(cudaMemPool_t *memPool, const struct cudaMemPool-
Props *poolProps)
Creates a memory pool.
__host__ cudaError_t cudaMemPoolDestroy(cudaMemPool_t memPool)
Destroys the specified memory pool.
558
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaMemPoolExportPointer(struct cudaMemPoolPtrExportData *exportData,
void *ptr)
Export data to share a memory pool allocation between processes.
__host__ cudaError_t cudaMemPoolExportToShareableHandle(void *shareableHandle, cudaMem-
Pool_t memPool, enum cudaMemAllocationHandleType handleType, unsigned int flags)
Exports a memory pool to the requested handle type.
__host__ cudaError_t cudaMemPoolGetAccess(enum cudaMemAccessFlags *flags, cudaMemPool_t
memPool, struct cudaMemLocation *location)
Returns the accessibility of a pool from a device.
__host__ cudaError_t cudaMemPoolGetAttribute(cudaMemPool_t memPool, enum cudaMem-
PoolAttr attr, void *value)
Gets attributes of a memory pool.
__host__ cudaError_t cudaMemPoolImportFromShareableHandle(cudaMemPool_t *memPool, void
*shareableHandle, enum cudaMemAllocationHandleType handleType, unsigned int flags)
imports a memory pool from a shared handle.
__host__ cudaError_t cudaMemPoolImportPointer(void **ptr, cudaMemPool_t memPool, struct cu-
daMemPoolPtrExportData *exportData)
Import a memory pool allocation from another process.
__host__ cudaError_t cudaMemPoolSetAccess(cudaMemPool_t memPool, const struct cud-
aMemAccessDesc *descList, size_t count)
Controls visibility of pools between devices.
__host__ cudaError_t cudaMemPoolSetAttribute(cudaMemPool_t memPool, enum cudaMem-
PoolAttr attr, void *value)
Sets attributes of a memory pool.
__host__ cudaError_t cudaMemPoolTrimTo(cudaMemPool_t memPool, size_t minBytesToKeep)
Tries to release memory back to the OS.
__host__ cudaError_t cudaMemSetMemPool(struct cudaMemLocation *location, enum cudaMemAl-
locationType type, cudaMemPool_t memPool)
Sets the current memory pool for a memory location and allocation type.
6.33.3. Functions
__host__ cudaError_t cudaFreeAsync(void *devPtr, cudaStream_t hStream)
Frees memory with stream ordered semantics.
Inserts a free operation into hStream. The allocation must not be accessed after stream execu-
tion reaches the free. After this API returns, accessing the memory from any subsequent work
launched on the GPU or querying its pointer attributes results in undefined behavior.
See also:
::cuMemFreeAsync, cudaMallocAsync
Note: During stream capture, this function results in the creation of a free node and must
therefore be passed the address of a graph allocation.
6.33. Stream Ordered Memory Allocator
559
CUDA Runtime API Reference Manual, Release 13.5
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: This function uses standard default stream semantics.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ dptr - - memory to free
▶ hStream - - The stream establishing the stream ordering promise
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorNotSupported
__host__ cudaError_t cudaMallocAsync(void **devPtr, size_t size, cudaStream_t hStream)
Allocates memory with stream ordered semantics.
Inserts an allocation operation into hStream. A pointer to the allocated memory is returned
immediately in *dptr. The allocation must not be accessed until the the allocation operation
completes. The allocation comes from the memory pool associated with the stream’s device.
See also:
::cuMemAllocAsync, cudaMallocAsync (C++ API), cudaMallocFromPoolAsync, cudaFreeAsync, cud-
aDeviceSetMemPool, cudaDeviceGetDefaultMemPool, cudaDeviceGetMemPool, cudaMemPoolSe-
tAccess, cudaMemPoolSetAttribute, cudaMemPoolGetAttribute
Note: The default memory pool of a device contains device memory from that device.
Note: Basic stream ordering allows future work submitted into the same stream to use the
allocation. Stream query, stream synchronize, and CUDA events can be used to guarantee that
the allocation operation completes before work submitted in a separate stream runs.
Note: During stream capture, this function results in the creation of an allocation node. In
this case, the allocation is owned by the graph instead of the memory pool. The memory pool’s
properties are used to set the node’s creation parameters.
560
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: This function uses standard default stream semantics.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ devPtr - [out] - Returned device pointer
▶ size - [in] - Number of bytes to allocate
▶ hStream - [in] - The stream establishing the stream ordering contract and the
memory pool to allocate from
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorNotSupported,
::cudaErrorOut-
OfMemory,
__host__ cudaError_t cudaMallocFromPoolAsync(void **ptr, size_t size, cudaMemPool_t memPool,
cudaStream_t stream)
Allocates memory from a specified pool with stream ordered semantics.
Inserts an allocation operation into stream. A pointer to the allocated memory is returned imme-
diately in *dptr. The allocation must not be accessed until the the allocation operation completes.
The allocation comes from the specified memory pool.
See also:
::cuMemAllocFromPoolAsync, cudaMallocAsync (C++ API), cudaMallocAsync, cudaFreeAsync, cud-
aDeviceGetDefaultMemPool, cudaMemPoolCreate, cudaMemPoolSetAccess, cudaMemPoolSetAt-
tribute
Note:
▶ The specified memory pool may be from a device different than that of the specified stream.
▶ Basic stream ordering allows future work submitted into the same stream to use the allo-
cation. Stream query, stream synchronize, and CUDA events can be used to guarantee that
the allocation operation completes before work submitted in a separate stream runs.
6.33. Stream Ordered Memory Allocator
561
CUDA Runtime API Reference Manual, Release 13.5
Note: During stream capture, this function results in the creation of an allocation node. In
this case, the allocation is owned by the graph instead of the memory pool. The memory pool’s
properties are used to set the node’s creation parameters.
Parameters
▶ ptr - [out] - Returned device pointer
▶ bytesize - [in] - Number of bytes to allocate
▶ memPool - [in] - The pool to allocate from
▶ stream - [in] - The stream establishing the stream ordering semantic
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorNotSupported,
::cudaErrorOut-
OfMemory
__host__ cudaError_t cudaMemGetDefaultMemPool(cudaMemPool_t *memPool, struct
cudaMemLocation *location, enum
cudaMemAllocationType type)
Returns the default memory pool for a given location and allocation type.
The memory location can be of one of cudaMemLocationTypeDevice, cudaMemLocationType-
Host, cudaMemLocationTypeHostNuma, or cudaMemLocationTypeDeviceLocalityDomain. The al-
location type can be one of cudaMemAllocationTypePinned or cudaMemAllocationTypeManaged.
When the allocation type is cudaMemAllocationTypeManaged, the location type can also be cu-
daMemLocationTypeNone to indicate no preferred location for the managed memory pool. cud-
aMemAllocationTypeManaged can not be used with cudaMemLocationTypeDeviceLocalityDomain.
In all other cases, the call return cudaErrorInvalidValue
See also:
::cuMemAllocAsync, ::cuMemPoolTrimTo, ::cuMemPoolGetAttribute, ::cuMemPoolSetAttribute,
cuMemPoolSetAccess, ::cuMemGetMemPool, ::cuMemPoolCreate
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorNotSupported,
__host__ cudaError_t cudaMemGetMemPool(cudaMemPool_t *memPool, struct cudaMemLocation
*location, enum cudaMemAllocationType type)
Gets the current memory pool for a given memory location and allocation type.
The memory location can be of one of cudaMemLocationTypeDevice, cudaMemLocationType-
Host, cudaMemLocationTypeHostNuma, or cudaMemLocationTypeDeviceLocalityDomain. The al-
location type can be one of cudaMemAllocationTypePinned or cudaMemAllocationTypeManaged.
When the allocation type is cudaMemAllocationTypeManaged, the location type can also be cu-
daMemLocationTypeNone to indicate no preferred location for the managed memory pool. cud-
aMemAllocationTypeManaged can not be used with cudaMemLocationTypeDeviceLocalityDomain.
In all other cases, the call return cudaErrorInvalidValue
Returns the last pool provided to cudaMemSetMemPool or cudaDeviceSetMemPool for this loca-
tion and allocation type or the location’s default memory pool if cudaMemSetMemPool or cud-
aDeviceSetMemPool for that allocType and location has never been called. By default the current
562
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
mempool of a location is the default mempool for a device that can be obtained via cudaMemGet-
DefaultMemPool Otherwise the returned pool must have been set with cudaDeviceSetMemPool.
See also:
::cuDeviceGetDefaultMemPool, ::cuMemPoolCreate, ::cuDeviceSetMemPool, ::cuMemSetMem-
Pool
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorNotSupported
__host__ cudaError_t cudaMemPoolCreate(cudaMemPool_t *memPool, const struct
cudaMemPoolProps *poolProps)
Creates a memory pool.
Creates a CUDA memory pool and returns the handle in pool. The poolProps determines the
properties of the pool such as the backing device and IPC capabilities.
To create a memory pool for host memory not targeting a specific NUMA node, applications
must set set ::cudaMemPoolProps::cudaMemLocation::type to cudaMemLocationTypeHost. ::cu-
daMemPoolProps::cudaMemLocation::id is ignored for such pools. Pools created with the type
cudaMemLocationTypeHost are not IPC capable and cudaMemPoolProps::handleTypes must be 0,
any other values will result in cudaErrorInvalidValue. To create a memory pool targeting a spe-
cific host NUMA node, applications must set ::cudaMemPoolProps::cudaMemLocation::type to
cudaMemLocationTypeHostNuma and ::cudaMemPoolProps::cudaMemLocation::id must specify
the NUMA ID of the host memory node. Specifying cudaMemLocationTypeHostNumaCurrent as
the ::cudaMemPoolProps::cudaMemLocation::type will result in cudaErrorInvalidValue. To create
a memory pool targeting a specific device locality domain, applications must set ::cudaMem-
PoolProps::cudaMemLocation::type to cudaMemLocationTypeDeviceLocalityDomain, ::cudaMem-
PoolProps::cudaMemLocation::localized.deviceId must specify the device ID, and ::cudaMemPool-
Props::cudaMemLocation::localized.localityDomainId must specify the locality domain ID. The lo-
cality domain ID must be a valid locality domain ID for the specified device. See also cud-
aDeviceGetAttribute with the attribute cudaDevAttrLocalityDomainCount. By default, the pool’s
memory will be accessible from the device it is allocated on. In the case of pools created with cu-
daMemLocationTypeHostNuma or cudaMemLocationTypeHost, their default accessibility will be
from the host CPU. Applications can control the maximum size of the pool by specifying a non-
zero value for cudaMemPoolProps::maxSize. If set to 0, the maximum size of the pool will default
to a system dependent value.
Applications that intend to use ::CU_MEM_HANDLE_TYPE_FABRIC based memory sharing must
ensure: (1) nvidia-caps-imex-channels character device is created by the driver and is listed
under /proc/devices (2) have at least one IMEX channel file accessible by the user launching the
application.
When exporter and importer CUDA processes have been granted access to the same IMEX chan-
nel, they can securely share memory.
The IMEX channel security model works on a per user basis. Which means all processes under a
user can share memory if the user has access to a valid IMEX channel. When multi-user isolation
is desired, a separate IMEX channel is required for each user.
These channel files exist in /dev/nvidia-caps-imex-channels/channel* and can be created us-
ing standard OS native calls like mknod on Linux. For example: To create channel0 with the
major number from /proc/devices users can execute the following command: mknod ∕dev∕
nvidia-caps-imex-channels∕channel0 c <major number> 0
6.33. Stream Ordered Memory Allocator
563
CUDA Runtime API Reference Manual, Release 13.5
To
create
a managed
memory
pool,
applications
must
set
cudaMemPool-
Props:cudaMemAllocationType to
cudaMemAllocationTypeManaged.
::cudaMemPool-
Props::cudaMemAllocationHandleType must also be set to cudaMemHandleTypeNone since
IPC is not supported. For managed memory pools, ::cudaMemPoolProps::cudaMemLocation will
be treated as the preferred location for all allocations created from the pool. An application
can also set cudaMemLocationTypeNone to indicate no preferred location. cudaMemPool-
Props::maxSize must be set to zero for managed memory pools. cudaMemPoolProps::usage
should be zero as decompress for managed memory is not supported. For managed memory
pools, all devices on the system must have non-zero ::concurrentManagedAccess. If not, this call
returns cudaErrorNotSupported
See also:
::cuMemPoolCreate, cudaDeviceSetMemPool, cudaMallocFromPoolAsync, cudaMemPoolExport-
ToShareableHandle, cudaDeviceGetDefaultMemPool, cudaDeviceGetMemPool
Note: Specifying cudaMemHandleTypeNone creates a memory pool that will not support IPC.
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorNotSupported
__host__ cudaError_t cudaMemPoolDestroy(cudaMemPool_t memPool)
Destroys the specified memory pool.
If any pointers obtained from this pool haven’t been freed or the pool has free operations that
haven’t completed when cudaMemPoolDestroy is invoked, the function will return immediately
and the resources associated with the pool will be released automatically once there are no more
outstanding allocations.
Destroying the current mempool of a device sets the default mempool of that device as the
current mempool for that device.
See also:
cuMemPoolDestroy, cudaFreeAsync, cudaDeviceSetMemPool, cudaDeviceGetDefaultMemPool,
cudaDeviceGetMemPool, cudaMemPoolCreate
Note: A device’s default memory pool cannot be destroyed.
Returns
cudaSuccess, cudaErrorInvalidValue
__host__ cudaError_t cudaMemPoolExportPointer(struct cudaMemPoolPtrExportData
*exportData, void *ptr)
Export data to share a memory pool allocation between processes.
Constructs shareData_out for sharing a specific allocation from an already shared memory
pool. The recipient process can import the allocation with the cudaMemPoolImportPointer api.
The data is not a handle and may be shared through any IPC mechanism.
564
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
See also:
::cuMemPoolExportPointer,
cudaMemPoolExportToShareableHandle,
cudaMemPoolImport-
FromShareableHandle, cudaMemPoolImportPointer
Parameters
▶ shareData_out - [out] - Returned export data
▶ ptr - [in] - pointer to memory being exported
Returns
cudaSuccess, cudaErrorInvalidValue, ::cudaErrorOutOfMemory
__host__ cudaError_t cudaMemPoolExportToShareableHandle(void *shareableHandle,
cudaMemPool_t memPool, enum
cudaMemAllocationHandleType
handleType, unsigned int flags)
Exports a memory pool to the requested handle type.
Given an IPC capable mempool, create an OS handle to share the pool with another process. A
recipient process can convert the shareable handle into a mempool with cudaMemPoolImport-
FromShareableHandle. Individual pointers can then be shared with the cudaMemPoolExport-
Pointer and cudaMemPoolImportPointer APIs. The implementation of what the shareable handle
is and how it can be transferred is defined by the requested handle type.
See also:
::cuMemPoolExportToShareableHandle, cudaMemPoolImportFromShareableHandle, cudaMem-
PoolExportPointer, cudaMemPoolImportPointer
Note: : To create an IPC capable mempool, create a mempool with a CUmemAllocationHandle-
Type other than cudaMemHandleTypeNone.
Parameters
▶ handle_out - [out] - pointer to the location in which to store the requested
handle
▶ pool - [in] - pool to export
▶ handleType - [in] - the type of handle to create
▶ flags - [in] - must be 0
Returns
cudaSuccess, cudaErrorInvalidValue, ::cudaErrorOutOfMemory
__host__ cudaError_t cudaMemPoolGetAccess(enum cudaMemAccessFlags *flags, cudaMemPool_t
memPool, struct cudaMemLocation *location)
Returns the accessibility of a pool from a device.
Returns the accessibility of the pool’s memory from the specified location.
6.33. Stream Ordered Memory Allocator
565
CUDA Runtime API Reference Manual, Release 13.5
See also:
::cuMemPoolGetAccess, cudaMemPoolSetAccess
Parameters
▶ flags - [out] - the accessibility of the pool from the specified location
▶ memPool - [in] - the pool being queried
▶ location - [in] - the location accessing the pool
__host__ cudaError_t cudaMemPoolGetAttribute(cudaMemPool_t memPool, enum
cudaMemPoolAttr attr, void *value)
Gets attributes of a memory pool.
Supported attributes are:
▶ cudaMemPoolAttrReleaseThreshold: (value type = cuuint64_t) Amount of reserved memory
in bytes to hold onto before trying to release memory back to the OS. When more than the
release threshold bytes of memory are held by the memory pool, the allocator will try to
release memory back to the OS on the next call to stream, event or context synchronize.
(default 0)
▶ cudaMemPoolReuseFollowEventDependencies: (value type = int) Allow cudaMallocAsync to
use memory asynchronously freed in another stream as long as a stream ordering depen-
dency of the allocating stream on the free action exists. Cuda events and null stream inter-
actions can create the required stream ordered dependencies. (default enabled)
▶ cudaMemPoolReuseAllowOpportunistic: (value type = int) Allow reuse of already completed
frees when there is no dependency between the free and allocation. (default enabled)
▶ cudaMemPoolReuseAllowInternalDependencies: (value type = int) Allow cudaMallocAsync to
insert new stream dependencies in order to establish the stream ordering required to reuse
a piece of memory released by cudaFreeAsync (default enabled).
▶ cudaMemPoolAttrReservedMemCurrent: (value type = cuuint64_t) Amount of backing mem-
ory currently allocated for the mempool.
▶ cudaMemPoolAttrReservedMemHigh: (value type = cuuint64_t) High watermark of backing
memory allocated for the mempool since the last time it was reset.
▶ cudaMemPoolAttrUsedMemCurrent: (value type = cuuint64_t) Amount of memory from the
pool that is currently in use by the application.
▶ cudaMemPoolAttrUsedMemHigh: (value type = cuuint64_t) High watermark of the amount
of memory from the pool that was in use by the application since the last time it was reset.
The following properties can be also be queried on imported and default pools:
▶ cudaMemPoolAttrAllocationType: (value type = cudaMemAllocationType) The allocation type
of the mempool
▶ cudaMemPoolAttrExportHandleTypes: (value type = cudaMemAllocationHandleType) Avail-
able export handle types for the mempool. For imported pools this value is always cud-
aMemHandleTypeNone as an imported pool cannot be re-exported
▶ cudaMemPoolAttrLocationId: (value type = int) The location id for the mempool. If the loca-
tion type for this pool is cudaMemLocationTypeInvisible then ID will be cudaInvalidDeviceId.
566
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ cudaMemPoolAttrLocationType: (value type = cudaMemLocationType) The location type for
the mempool. For imported memory pools where the device is not directly visible to the
importing process or pools imported via fabric handles across nodes this will be cudaMem-
locataionTypeInvisible.
▶ cudaMemPoolAttrLocalityDomainId: (value type = int) The locality domain id for the mempool,
if the mempool is localized to a locality domain. A value of -1 indicates that the mempool is
not localized to a locality domain.
▶ cudaMemPoolAttrMaxPoolSize: (value type = cuuint64_t) Maximum size of the pool in bytes,
this value may be higher than what was initially passed to cuMemPoolCreate due to align-
ment requirements. A value of 0 indicates no maximum size. For cudaMemAllocationType-
Managed and IPC imported pools this value will be system dependent.
▶ cudaMemPoolAttrHwDecompressEnabled: (value type = int) Indicates whether the pool has
hardware compresssion enabled
See also:
::cuMemPoolGetAttribute, cudaMallocAsync, cudaFreeAsync, cudaDeviceGetDefaultMemPool, cu-
daDeviceGetMemPool, cudaMemPoolCreate
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ pool - [in] - The memory pool to get attributes of
▶ attr - [in] - The attribute to get
▶ value - [in] - Retrieved value
Returns
cudaSuccess, cudaErrorInvalidValue
__host__ cudaError_t cudaMemPoolImportFromShareableHandle(cudaMemPool_t *memPool,
void *shareableHandle, enum
cudaMemAllocationHandleType
handleType, unsigned int flags)
imports a memory pool from a shared handle.
Specific allocations can be imported from the imported pool with cudaMemPoolImportPointer.
See also:
::cuMemPoolImportFromShareableHandle, cudaMemPoolExportToShareableHandle, cudaMem-
PoolExportPointer, cudaMemPoolImportPointer
Note: Imported memory pools do not support creating new allocations. As such imported mem-
ory pools may not be used in cudaDeviceSetMemPool or cudaMallocFromPoolAsync calls.
6.33. Stream Ordered Memory Allocator
567
CUDA Runtime API Reference Manual, Release 13.5
Parameters
▶ pool_out - [out] - Returned memory pool
▶ handle - [in] - OS handle of the pool to open
▶ handleType - [in] - The type of handle being imported
▶ flags - [in] - must be 0
Returns
cudaSuccess, cudaErrorInvalidValue, ::cudaErrorOutOfMemory
__host__ cudaError_t cudaMemPoolImportPointer(void **ptr, cudaMemPool_t memPool, struct
cudaMemPoolPtrExportData *exportData)
Import a memory pool allocation from another process.
Returns in ptr_out a pointer to the imported memory. The imported memory must not be ac-
cessed before the allocation operation completes in the exporting process. The imported mem-
ory must be freed from all importing processes before being freed in the exporting process. The
pointer may be freed with cudaFree or cudaFreeAsync. If cudaFreeAsync is used, the free must
be completed on the importing process before the free operation on the exporting process.
See also:
::cuMemPoolImportPointer,
cudaMemPoolExportToShareableHandle,
cudaMemPoolImport-
FromShareableHandle, cudaMemPoolExportPointer
Note: The cudaFreeAsync api may be used in the exporting process before the cudaFreeAsync
operation completes in its stream as long as the cudaFreeAsync in the exporting process specifies
a stream with a stream dependency on the importing process’s cudaFreeAsync.
Parameters
▶ ptr_out - [out] - pointer to imported memory
▶ pool - [in] - pool from which to import
▶ shareData - [in] - data specifying the memory to import
Returns
::CUDA_SUCCESS, ::CUDA_ERROR_INVALID_VALUE, ::CUDA_ERROR_NOT_INITIALIZED,
::CUDA_ERROR_OUT_OF_MEMORY
__host__ cudaError_t cudaMemPoolSetAccess(cudaMemPool_t memPool, const struct
cudaMemAccessDesc *descList, size_t count)
Controls visibility of pools between devices.
See also:
::cuMemPoolSetAccess, cudaMemPoolGetAccess, cudaMallocAsync, cudaFreeAsync
Parameters
568
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ pool - [in] - The pool being modified
▶ map - [in] - Array of access descriptors. Each descriptor instructs the access to
enable for a single gpu
▶ count - [in] - Number of descriptors in the map array.
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorNotSupported
__host__ cudaError_t cudaMemPoolSetAttribute(cudaMemPool_t memPool, enum
cudaMemPoolAttr attr, void *value)
Sets attributes of a memory pool.
Supported attributes are:
▶ cudaMemPoolAttrReleaseThreshold: (value type = cuuint64_t) Amount of reserved memory
in bytes to hold onto before trying to release memory back to the OS. When more than the
release threshold bytes of memory are held by the memory pool, the allocator will try to
release memory back to the OS on the next call to stream, event or context synchronize.
(default 0)
▶ cudaMemPoolReuseFollowEventDependencies: (value type = int) Allow cudaMallocAsync to
use memory asynchronously freed in another stream as long as a stream ordering depen-
dency of the allocating stream on the free action exists. Cuda events and null stream inter-
actions can create the required stream ordered dependencies. (default enabled)
▶ cudaMemPoolReuseAllowOpportunistic: (value type = int) Allow reuse of already completed
frees when there is no dependency between the free and allocation. (default enabled)
▶ cudaMemPoolReuseAllowInternalDependencies: (value type = int) Allow cudaMallocAsync to
insert new stream dependencies in order to establish the stream ordering required to reuse
a piece of memory released by cudaFreeAsync (default enabled).
▶ cudaMemPoolAttrReservedMemHigh: (value type = cuuint64_t) Reset the high watermark
that tracks the amount of backing memory that was allocated for the memory pool. It is
illegal to set this attribute to a non-zero value.
▶ cudaMemPoolAttrUsedMemHigh: (value type = cuuint64_t) Reset the high watermark that
tracks the amount of used memory that was allocated for the memory pool. It is illegal to
set this attribute to a non-zero value.
See also:
::cuMemPoolSetAttribute, cudaMallocAsync, cudaFreeAsync, cudaDeviceGetDefaultMemPool, cu-
daDeviceGetMemPool, cudaMemPoolCreate
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ pool - [in] - The memory pool to modify
▶ attr - [in] - The attribute to modify
6.33. Stream Ordered Memory Allocator
569
CUDA Runtime API Reference Manual, Release 13.5
▶ value - [in] - Pointer to the value to assign
Returns
cudaSuccess, cudaErrorInvalidValue
__host__ cudaError_t cudaMemPoolTrimTo(cudaMemPool_t memPool, size_t minBytesToKeep)
Tries to release memory back to the OS.
Releases memory back to the OS until the pool contains fewer than minBytesToKeep reserved
bytes, or there is no more memory that the allocator can safely release. The allocator cannot
release OS allocations that back outstanding asynchronous allocations. The OS allocations may
happen at different granularity from the user allocations.
See also:
::cuMemPoolTrimTo, cudaMallocAsync, cudaFreeAsync, cudaDeviceGetDefaultMemPool, cudaDe-
viceGetMemPool, cudaMemPoolCreate
Note: : Allocations that have not been freed count as outstanding.
Note: : Allocations that have been asynchronously freed but whose completion has not been
observed on the host (eg. by a synchronize) can count as outstanding.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ pool - [in] - The memory pool to trim
▶ minBytesToKeep - [in] - If the pool has less than minBytesToKeep reserved,
the TrimTo operation is a no-op. Otherwise the pool will be guaranteed to have
at least minBytesToKeep bytes reserved after the operation.
Returns
cudaSuccess, cudaErrorInvalidValue
__host__ cudaError_t cudaMemSetMemPool(struct cudaMemLocation *location, enum
cudaMemAllocationType type, cudaMemPool_t
memPool)
Sets the current memory pool for a memory location and allocation type.
The memory location can be of one of cudaMemLocationTypeDevice, cudaMemLocationType-
Host cudaMemLocationTypeHostNuma, or cudaMemLocationTypeDeviceLocalityDomain. The al-
location type can be one of cudaMemAllocationTypePinned or cudaMemAllocationTypeManaged.
When the allocation type is cudaMemAllocationTypeManaged, the location type can also be cu-
daMemLocationTypeNone to indicate no preferred location for the managed memory pool. cud-
aMemAllocationTypeManaged can not be used with cudaMemLocationTypeDeviceLocalityDomain.
In all other cases, the call return cudaErrorInvalidValue
570
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
When a memory pool is set as the current memory pool, the location parameter should be the
same as the location of the pool. If the location type or index don’t match, the call returns cu-
daErrorInvalidValue. The type of memory pool should also match the parameter allocType. Else
the call returns cudaErrorInvalidValue .
By default, a memory location’s current memory pool is its default memory pool. If the location
type is cudaMemLocationTypeDevice and the allocation type is cudaMemAllocationTypePinned,
then this API is the equivalent of calling cudaDeviceSetMemPool with the location id as the de-
vice. For further details on the implications, please refer to the documentation for cudaDevice-
SetMemPool.
See also:
::cuDeviceGetDefaultMemPool, ::cuDeviceGetMemPool, ::cuMemGetMemPool, ::cuMemPoolCre-
ate, ::cuMemPoolDestroy, ::cuMemAllocFromPoolAsync
Note: Use cudaMallocFromPoolAsync to specify asynchronous allocations from a device different
than the one the stream runs on.
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorNotSupported
6.34. Surface Object Management
This section describes the low level texture object management functions of the CUDA runtime appli-
cation programming interface.
The surface object API is only supported on devices of compute capability 3.0 or higher.
Functions
__host__ cudaError_t cudaCreateSurfaceObject(cudaSurfaceObject_t *pSurfObject, const struct
cudaResourceDesc *pResDesc)
Creates a surface object.
__host__ cudaError_t cudaDestroySurfaceObject(cudaSurfaceObject_t surfObject)
Destroys a surface object.
__host__ cudaError_t cudaGetSurfaceObjectResourceDesc(struct cudaResourceDesc *pResDesc,
cudaSurfaceObject_t surfObject)
Returns a surface object's resource descriptor Returns the resource descriptor for the surface
object specified by surfObject .
6.34. Surface Object Management
571
CUDA Runtime API Reference Manual, Release 13.5
6.34.1. Functions
__host__ cudaError_t cudaCreateSurfaceObject(cudaSurfaceObject_t *pSurfObject, const struct
cudaResourceDesc *pResDesc)
Creates a surface object.
Creates a surface object and returns it in pSurfObject. pResDesc describes the data to per-
form surface load/stores on. cudaResourceDesc::resType must be cudaResourceTypeArray and
::cudaResourceDesc::res::array::array must be set to a valid CUDA array handle.
Surface objects are only supported on devices of compute capability 3.0 or higher. Additionally, a
surface object is an opaque value, and, as such, should only be accessed through CUDA API calls.
See also:
cudaDestroySurfaceObject, ::cuSurfObjectCreate
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ pSurfObject - - Surface object to create
▶ pResDesc - - Resource descriptor
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidChannelDescriptor, cudaError-
InvalidResourceHandle
__host__ cudaError_t cudaDestroySurfaceObject(cudaSurfaceObject_t surfObject)
Destroys a surface object.
Destroys the surface object specified by surfObject.
See also:
cudaCreateSurfaceObject, ::cuSurfObjectDestroy
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
572
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
such case.
Note: Use of the handle after this call is undefined behavior.
Parameters
surfObject - - Surface object to destroy
Returns
cudaSuccess, cudaErrorInvalidValue
__host__ cudaError_t cudaGetSurfaceObjectResourceDesc(struct cudaResourceDesc
*pResDesc, cudaSurfaceObject_t
surfObject)
Returns a surface object’s resource descriptor Returns the resource descriptor for the surface
object specified by surfObject.
See also:
cudaCreateSurfaceObject, ::cuSurfObjectGetResourceDesc
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ pResDesc - - Resource descriptor
▶ surfObject - - Surface object
Returns
cudaSuccess, cudaErrorInvalidValue
6.35. Texture Object Management
This section describes the low level texture object management functions of the CUDA runtime appli-
cation programming interface.
The texture object API is only supported on devices of compute capability 3.0 or higher.
6.35. Texture Object Management
573
CUDA Runtime API Reference Manual, Release 13.5
Functions
__host__ struct cudaChannelFormatDesc cudaCreateChannelDesc(int x, int y, int z, int w, enum cu-
daChannelFormatKind f)
Returns a channel descriptor using the specified format.
__host__ cudaError_t cudaCreateTextureObject(cudaTextureObject_t *pTexObject, const struct cu-
daResourceDesc *pResDesc, const struct cudaTextureDesc *pTexDesc, const struct cudaRe-
sourceViewDesc *pResViewDesc)
Creates a texture object.
__host__ cudaError_t cudaDestroyTextureObject(cudaTextureObject_t texObject)
Destroys a texture object.
__host__ cudaError_t cudaGetChannelDesc(struct cudaChannelFormatDesc *desc, cudaAr-
ray_const_t array)
Get the channel descriptor of an array.
__host__ cudaError_t cudaGetTextureObjectResourceDesc(struct cudaResourceDesc *pResDesc,
cudaTextureObject_t texObject)
Returns a texture object's resource descriptor.
__host__ cudaError_t cudaGetTextureObjectResourceViewDesc(struct cudaResourceViewDesc
*pResViewDesc, cudaTextureObject_t texObject)
Returns a texture object's resource view descriptor.
__host__ cudaError_t cudaGetTextureObjectTextureDesc(struct cudaTextureDesc *pTexDesc, cuda-
TextureObject_t texObject)
Returns a texture object's texture descriptor.
6.35.1. Functions
__host__ struct cudaChannelFormatDesc cudaCreateChannelDesc(int x, int y, int z, int w, enum
cudaChannelFormatKind f)
Returns a channel descriptor using the specified format.
Returns a channel descriptor with format f and number of bits of each component x, y, z, and
w. The cudaChannelFormatDesc is defined as:
struct cudaChannelFormatDesc {
int x, y, z, w;
enum cudaChannelFormatKind f;
};
where cudaChannelFormatKind is one of cudaChannelFormatKindSigned, cudaChannelFormatKin-
dUnsigned, or cudaChannelFormatKindFloat.
See also:
cudaCreateChannelDesc (C++ API), cudaGetChannelDesc, cudaCreateTextureObject, cudaCre-
ateSurfaceObject
Parameters
574
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ x - - X component
▶ y - - Y component
▶ z - - Z component
▶ w - - W component
▶ f - - Channel format
Returns
Channel descriptor with format f
__host__ cudaError_t cudaCreateTextureObject(cudaTextureObject_t *pTexObject, const struct
cudaResourceDesc *pResDesc, const struct
cudaTextureDesc *pTexDesc, const struct
cudaResourceViewDesc *pResViewDesc)
Creates a texture object.
Creates a texture object and returns it in pTexObject. pResDesc describes the data to texture
from. pTexDesc describes how the data should be sampled. pResViewDesc is an optional argu-
ment that specifies an alternate format for the data described by pResDesc, and also describes
the subresource region to restrict access to when texturing. pResViewDesc can only be speci-
fied if the type of resource is a CUDA array or a CUDA mipmapped array not in a block compressed
format.
Texture objects are only supported on devices of compute capability 3.0 or higher. Additionally, a
texture object is an opaque value, and, as such, should only be accessed through CUDA API calls.
The cudaResourceDesc structure is defined as:
struct cudaResourceDesc {
enum cudaResourceType resType;
union {
struct {
cudaArray_t array;
} array;
struct {
cudaMipmappedArray_t mipmap;
} mipmap;
struct {
void *devPtr;
struct cudaChannelFormatDesc desc;
size_t sizeInBytes;
} linear;
struct {
void *devPtr;
struct cudaChannelFormatDesc desc;
size_t width;
size_t height;
size_t pitchInBytes;
} pitch2D;
} res;
};
where:
▶ cudaResourceDesc::resType specifies the type of resource to texture from. CUresourceType
is defined as:
6.35. Texture Object Management
575
CUDA Runtime API Reference Manual, Release 13.5
enum cudaResourceType {
cudaResourceTypeArray
= 0x00,
cudaResourceTypeMipmappedArray = 0x01,
cudaResourceTypeLinear
= 0x02,
cudaResourceTypePitch2D
= 0x03
};
The cudaTextureDesc struct is defined as
struct cudaTextureDesc {
enum cudaTextureAddressMode addressMode[3];
enum cudaTextureFilterMode filterMode;
enum cudaTextureReadMode
readMode;
int
sRGB;
float
borderColor[4];
int
normalizedCoords;
unsigned int
maxAnisotropy;
enum cudaTextureFilterMode
mipmapFilterMode;
float
mipmapLevelBias;
float
minMipmapLevelClamp;
float
maxMipmapLevelClamp;
int
disableTrilinearOptimization;
int
seamlessCubemap;
};
where
▶ cudaTextureDesc::addressMode specifies the addressing mode for each dimension of the
texture data. cudaTextureAddressMode is defined as:
enum cudaTextureAddressMode {
cudaAddressModeWrap
= 0,
cudaAddressModeClamp
= 1,
cudaAddressModeMirror = 2,
cudaAddressModeBorder = 3
};
This is ignored if cudaResourceDesc::resType is cudaResourceTypeLinear. Also, if cuda-
TextureDesc::normalizedCoords is set to zero, cudaAddressModeWrap and cudaAddress-
ModeMirror won’t be supported and will be switched to cudaAddressModeClamp.
▶ cudaTextureDesc::filterMode specifies the filtering mode to be used when fetching from the
texture. cudaTextureFilterMode is defined as:
enum cudaTextureFilterMode {
cudaFilterModePoint
= 0,
cudaFilterModeLinear = 1
};
This is ignored if cudaResourceDesc::resType is cudaResourceTypeLinear.
▶ cudaTextureDesc::readMode specifies whether integer data should be converted to floating
point or not. cudaTextureReadMode is defined as:
enum cudaTextureReadMode {
cudaReadModeElementType
= 0,
(continues on next page)
576
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
(continued from previous page)
cudaReadModeNormalizedFloat = 1
};
Note that this applies only to 8-bit and 16-bit integer formats. 32-bit integer format would
not be promoted, regardless of whether or not this cudaTextureDesc::readMode is set cud-
aReadModeNormalizedFloat is specified.
▶ cudaTextureDesc::sRGB specifies whether sRGB to linear conversion should be performed
during texture fetch.
▶ cudaTextureDesc::borderColor specifies the float values of color. where: cudaTexture-
Desc::borderColor[0] contains value of ‘R’, cudaTextureDesc::borderColor[1] contains value of
‘G’, cudaTextureDesc::borderColor[2] contains value of ‘B’, cudaTextureDesc::borderColor[3]
contains value of ‘A’ Note that application using integer border color values will need to
<reinterpret_cast> these values to float. The values are set only when the addressing mode
specified by cudaTextureDesc::addressMode is cudaAddressModeBorder.
▶ cudaTextureDesc::normalizedCoords specifies whether the texture coordinates will be nor-
malized or not.
▶ cudaTextureDesc::maxAnisotropy specifies the maximum anistropy ratio to be used when
doing anisotropic filtering. This value will be clamped to the range [1,16].
▶ cudaTextureDesc::mipmapFilterMode specifies the filter mode when the calculated mipmap
level lies between two defined mipmap levels.
▶ cudaTextureDesc::mipmapLevelBias specifies the offset to be applied to the calculated
mipmap level.
▶ cudaTextureDesc::minMipmapLevelClamp specifies the lower end of the mipmap level range
to clamp access to.
▶ cudaTextureDesc::maxMipmapLevelClamp specifies the upper end of the mipmap level range
to clamp access to.
▶ cudaTextureDesc::disableTrilinearOptimization specifies whether the trilinear filtering opti-
mizations will be disabled.
▶ cudaTextureDesc::seamlessCubemap specifies whether seamless cube map filtering is en-
abled. This flag can only be specified if the underlying resource is a CUDA array or a CUDA
mipmapped array that was created with the flag cudaArrayCubemap. When seamless cube
map filtering is enabled, texture address modes specified by cudaTextureDesc::addressMode
are ignored. Instead, if the cudaTextureDesc::filterMode is set to cudaFilterModePoint the
address mode cudaAddressModeClamp will be applied for all dimensions. If the cudaTex-
tureDesc::filterMode is set to cudaFilterModeLinear seamless cube map filtering will be per-
formed when sampling along the cube face borders.
If
cudaResourceDesc::resType
is
set
to
cudaResourceTypeArray,
::cudaRe-
sourceDesc::res::array::array must be set to a valid CUDA array handle.
If cudaResourceDesc::resType is set to cudaResourceTypeMipmappedArray,
::cudaRe-
sourceDesc::res::mipmap::mipmap must be set to a valid CUDA mipmapped array handle and
cudaTextureDesc::normalizedCoords must be set to true.
If
cudaResourceDesc::resType
is
set
to
cudaResourceTypeLinear,
::cudaRe-
sourceDesc::res::linear::devPtr must be set to a valid device pointer, that is aligned
to
cudaDeviceProp::textureAlignment.
::cudaResourceDesc::res::linear::desc
de-
scribes the format and the number of components per array element.
::cudaRe-
sourceDesc::res::linear::sizeInBytes specifies the size of the array in bytes.
The to-
6.35. Texture Object Management
577
CUDA Runtime API Reference Manual, Release 13.5
tal number of elements in the linear address range cannot exceed cudaDeviceGet-
Texture1DLinearMaxWidth().
The number of elements is computed as (sizeInBytes /
sizeof(desc)).
If
cudaResourceDesc::resType
is
set
to
cudaResourceTypePitch2D,
::cudaRe-
sourceDesc::res::pitch2D::devPtr must be set to a valid device pointer, that is aligned
to cudaDeviceProp::textureAlignment.
::cudaResourceDesc::res::pitch2D::desc de-
scribes the format and the number of components per array element.
::cudaRe-
sourceDesc::res::pitch2D::width
and
::cudaResourceDesc::res::pitch2D::height
spec-
ify the width and height of the array in elements, and cannot exceed cudaDevice-
Prop::maxTexture2DLinear[0] and cudaDeviceProp::maxTexture2DLinear[1] respectively.
::cudaResourceDesc::res::pitch2D::pitchInBytes specifies the pitch between two rows in
bytes and has to be aligned to cudaDeviceProp::texturePitchAlignment. Pitch cannot exceed
cudaDeviceProp::maxTexture2DLinear[2].
The cudaResourceViewDesc struct is defined as
struct cudaResourceViewDesc {
enum cudaResourceViewFormat format;
size_t
width;
size_t
height;
size_t
depth;
unsigned int
firstMipmapLevel;
unsigned int
lastMipmapLevel;
unsigned int
firstLayer;
unsigned int
lastLayer;
};
where:
▶ cudaResourceViewDesc::format specifies how the data contained in the CUDA array or CUDA
mipmapped array should be interpreted. Note that this can incur a change in size of the
texture data. If the resource view format is a block compressed format, then the underlying
CUDA array or CUDA mipmapped array has to have a 32-bit unsigned integer format with
2 or 4 channels, depending on the block compressed format. For ex., BC1 and BC4 require
the underlying CUDA array to have a 32-bit unsigned int with 2 channels. The other BC
formats require the underlying resource to have the same 32-bit unsigned int format but
with 4 channels.
▶ cudaResourceViewDesc::width specifies the new width of the texture data. If the resource
view format is a block compressed format, this value has to be 4 times the original width of
the resource. For non block compressed formats, this value has to be equal to that of the
original resource.
▶ cudaResourceViewDesc::height specifies the new height of the texture data. If the resource
view format is a block compressed format, this value has to be 4 times the original height of
the resource. For non block compressed formats, this value has to be equal to that of the
original resource.
▶ cudaResourceViewDesc::depth specifies the new depth of the texture data. This value has
to be equal to that of the original resource.
▶ cudaResourceViewDesc::firstMipmapLevel specifies the most detailed mipmap level.
This will be the new mipmap level zero.
For non-mipmapped resources, this
value has to be zero.cudaTextureDesc::minMipmapLevelClamp and cudaTexture-
Desc::maxMipmapLevelClamp will be relative to this value. For ex., if the firstMipmapLevel is
set to 2, and a minMipmapLevelClamp of 1.2 is specified, then the actual minimum mipmap
level clamp will be 3.2.
578
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ cudaResourceViewDesc::lastMipmapLevel specifies the least detailed mipmap level. For non-
mipmapped resources, this value has to be zero.
▶ cudaResourceViewDesc::firstLayer specifies the first layer index for layered textures. This
will be the new layer zero. For non-layered resources, this value has to be zero.
▶ cudaResourceViewDesc::lastLayer specifies the last layer index for layered textures. For non-
layered resources, this value has to be zero.
See also:
cudaDestroyTextureObject, ::cuTexObjectCreate
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ pTexObject - - Texture object to create
▶ pResDesc - - Resource descriptor
▶ pTexDesc - - Texture descriptor
▶ pResViewDesc - - Resource view descriptor
Returns
cudaSuccess, cudaErrorInvalidValue
__host__ cudaError_t cudaDestroyTextureObject(cudaTextureObject_t texObject)
Destroys a texture object.
Destroys the texture object specified by texObject.
See also:
cudaCreateTextureObject, ::cuTexObjectDestroy
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
6.35. Texture Object Management
579
CUDA Runtime API Reference Manual, Release 13.5
Note: Use of the handle after this call is undefined behavior.
Parameters
texObject - - Texture object to destroy
Returns
cudaSuccess, cudaErrorInvalidValue
__host__ cudaError_t cudaGetChannelDesc(struct cudaChannelFormatDesc *desc,
cudaArray_const_t array)
Get the channel descriptor of an array.
Returns in *desc the channel descriptor of the CUDA array array.
See also:
cudaCreateChannelDesc (C API), cudaCreateTextureObject, cudaCreateSurfaceObject
Note: Note that this function may also return error codes from previous, asynchronous launches.
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ desc - - Channel format
▶ array - - Memory array on device
Returns
cudaSuccess, cudaErrorInvalidValue
__host__ cudaError_t cudaGetTextureObjectResourceDesc(struct cudaResourceDesc
*pResDesc, cudaTextureObject_t
texObject)
Returns a texture object’s resource descriptor.
Returns the resource descriptor for the texture object specified by texObject.
See also:
cudaCreateTextureObject, ::cuTexObjectGetResourceDesc
580
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ pResDesc - - Resource descriptor
▶ texObject - - Texture object
Returns
cudaSuccess, cudaErrorInvalidValue
__host__ cudaError_t cudaGetTextureObjectResourceViewDesc(struct cudaResourceViewDesc
*pResViewDesc,
cudaTextureObject_t
texObject)
Returns a texture object’s resource view descriptor.
Returns the resource view descriptor for the texture object specified by texObject. If no re-
source view was specified, cudaErrorInvalidValue is returned.
See also:
cudaCreateTextureObject, ::cuTexObjectGetResourceViewDesc
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ pResViewDesc - - Resource view descriptor
▶ texObject - - Texture object
Returns
cudaSuccess, cudaErrorInvalidValue
__host__ cudaError_t cudaGetTextureObjectTextureDesc(struct cudaTextureDesc *pTexDesc,
cudaTextureObject_t texObject)
6.35. Texture Object Management
581
CUDA Runtime API Reference Manual, Release 13.5
Returns a texture object’s texture descriptor.
Returns the texture descriptor for the texture object specified by texObject.
See also:
cudaCreateTextureObject, ::cuTexObjectGetTextureDesc
Note: Note that this function may also return cudaErrorInitializationError, cudaErrorInsufficient-
Driver or cudaErrorNoDevice if this call tries to initialize internal CUDA RT state.
Note: Note that as specified by cudaStreamAddCallback no CUDA function may be called from
callback. cudaErrorNotPermitted may, but is not guaranteed to, be returned as a diagnostic in
such case.
Parameters
▶ pTexDesc - - Texture descriptor
▶ texObject - - Texture object
Returns
cudaSuccess, cudaErrorInvalidValue
6.36. Unified Addressing
This section describes the unified addressing functions of the CUDA runtime application programming
interface.
6.36.1. Overview
CUDA devices can share a unified address space with the host.
For these devices there is no distinction between a device pointer and a host pointer &#8212; the
same pointer value may be used to access memory from the host program and from a kernel running
on the device (with exceptions enumerated below).
582
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
6.36.2. Supported Platforms
Whether or not a device supports unified addressing may be queried by calling cudaGetDeviceProper-
ties() with the device property cudaDeviceProp::unifiedAddressing.
Unified addressing is automatically enabled in 64-bit processes .
6.36.3. Looking Up Information from Pointer Values
It is possible to look up information about the memory which backs a pointer value. For instance, one
may want to know if a pointer points to host or device memory. As another example, in the case of
device memory, one may want to know on which CUDA device the memory resides. These properties
may be queried using the function cudaPointerGetAttributes()
Since pointers are unique, it is not necessary to specify information about the pointers specified to
cudaMemcpy() and other copy functions.
The copy direction cudaMemcpyDefault may be used to specify that the CUDA runtime should infer
the location of the pointer from its value.
6.36.4. Automatic Mapping of Host Allocated Host
Memory
All host memory allocated through all devices using cudaMallocHost() and cudaHostAlloc() is always
directly accessible from all devices that support unified addressing. This is the case regardless of
whether or not the flags cudaHostAllocPortable and cudaHostAllocMapped are specified.
The pointer value through which allocated host memory may be accessed in kernels on all devices that
support unified addressing is the same as the pointer value through which that memory is accessed
on the host. It is not necessary to call cudaHostGetDevicePointer() to get the device pointer for these
allocations.
Note that this is not the case for memory allocated using the flag cudaHostAllocWriteCombined, as
discussed below.
6.36.5. Direct Access of Peer Memory
Upon enabling direct access from a device that supports unified addressing to another peer device
that supports unified addressing using cudaDeviceEnablePeerAccess() all memory allocated in the peer
device using cudaMalloc() and cudaMallocPitch() will immediately be accessible by the current device.
The device pointer value through which any peer’s memory may be accessed in the current device is
the same pointer value through which that memory may be accessed from the peer device.
6.36. Unified Addressing
583
CUDA Runtime API Reference Manual, Release 13.5
6.36.6. Exceptions, Disjoint Addressing
Not all memory may be accessed on devices through the same pointer value through which they are
accessed on the host. These exceptions are host memory registered using cudaHostRegister() and
host memory allocated using the flag cudaHostAllocWriteCombined. For these exceptions, there exists
a distinct host and device address for the memory. The device address is guaranteed to not overlap
any valid host pointer range and is guaranteed to have the same value across all devices that support
unified addressing.
This device address may be queried using cudaHostGetDevicePointer() when a device using unified
addressing is current. Either the host or the unified device pointer value may be used to refer to this
memory in cudaMemcpy() and similar functions using the cudaMemcpyDefault memory direction.
Functions
__host__ cudaError_t cudaPointerGetAttributes(struct cudaPointerAttributes *attributes, const
void *ptr)
Returns attributes about a specified pointer.
6.36.7. Functions
__host__ cudaError_t cudaPointerGetAttributes(struct cudaPointerAttributes *attributes, const
void *ptr)
Returns attributes about a specified pointer.
Returns in *attributes the attributes of the pointer ptr. If pointer was not allocated in,
mapped by or registered with context supporting unified addressing cudaErrorInvalidValue is re-
turned.
The cudaPointerAttributes structure is defined as:
struct cudaPointerAttributes {
enum cudaMemoryType type;
int device;
void *devicePointer;
void *hostPointer;
int localityDomainOrdinal;
}
In this structure, the individual fields mean
▶ cudaPointerAttributes::type identifies type of memory. It can be cudaMemoryTypeUnregis-
tered for unregistered host memory, cudaMemoryTypeHost for registered host memory, cu-
daMemoryTypeDevice for device memory or cudaMemoryTypeManaged for managed mem-
ory.
▶ device is the device against which ptr was allocated. If ptr has memory type cudaMemory-
TypeDevice then this identifies the device on which the memory referred to by ptr physically
resides. If ptr has memory type cudaMemoryTypeHost then this identifies the device which
584
Chapter 6. APIs

 

 

 

 

 

 

 

Content      ..     6      7      8      9     ..