|
|
CUDA Runtime API Reference Manual, Release 13.5
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ device - - Returns the device corresponding to pAdapter
▶ pAdapter - - D3D11 adapter to get device for
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorUnknown
__host__ cudaError_t cudaD3D11GetDevices(unsigned int *pCudaDeviceCount, int *pCudaDevices,
unsigned int cudaDeviceCount, ID3D11Device
*pD3D11Device, enum cudaD3D11DeviceList
deviceList)
Gets the CUDA devices corresponding to a Direct3D 11 device.
Returns in *pCudaDeviceCount the number of CUDA-compatible devices corresponding to the
Direct3D 11 device pD3D11Device. Also returns in *pCudaDevices at most cudaDeviceCount
of the the CUDA-compatible devices corresponding to the Direct3D 11 device pD3D11Device.
If any of the GPUs being used to render pDevice are not CUDA capable then the call will return
cudaErrorNoDevice.
See also:
cudaGraphicsUnregisterResource,
cudaGraphicsMapResources,
cudaGraphicsSubRe-
sourceGetMappedArray, cudaGraphicsResourceGetMappedPointer, ::cuD3D11GetDevices
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ pCudaDeviceCount - - Returned number of CUDA devices corresponding to
pD3D11Device
▶ pCudaDevices - - Returned CUDA devices corresponding to pD3D11Device
▶ cudaDeviceCount - - The size of the output device array pCudaDevices
▶ pD3D11Device - - Direct3D 11 device to query for CUDA devices
▶ deviceList - - The set of devices to return.
This set may be cu-
daD3D11DeviceListAll for all devices, cudaD3D11DeviceListCurrentFrame
for the devices used to render the current frame (in SLI), or cu-
daD3D11DeviceListNextFrame for the devices used to render the next frame
(in SLI).
Returns
cudaSuccess, cudaErrorNoDevice, cudaErrorUnknown
6.7. Direct3D 11 Interoperability
219
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaGraphicsD3D11RegisterResource(struct cudaGraphicsResource
**resource, ID3D11Resource
*pD3DResource, unsigned int
flags)
Register a Direct3D 11 resource for access by CUDA.
Registers the Direct3D 11 resource pD3DResource for access by CUDA.
If this call is successful, then the application will be able to map and unmap this resource until it
is unregistered through cudaGraphicsUnregisterResource(). Also on success, this call will increase
the internal reference count on pD3DResource. This reference count will be decremented when
this resource is unregistered through cudaGraphicsUnregisterResource().
This call potentially has a high-overhead and should not be called every frame in interactive ap-
plications.
The type of pD3DResource must be one of the following.
▶ ::ID3D11Buffer: may be accessed via a device pointer
▶ ::ID3D11Texture1D: individual subresources of the texture may be accessed via arrays
▶ ::ID3D11Texture2D: individual subresources of the texture may be accessed via arrays
▶ ::ID3D11Texture3D: individual subresources of the texture may be accessed via arrays
The flags argument may be used to specify additional parameters at register time. The valid
values for this parameter are
▶ cudaGraphicsRegisterFlagsNone: Specifies no hints about how this resource will be used.
▶ cudaGraphicsRegisterFlagsSurfaceLoadStore: Specifies that CUDA will bind this resource to
a surface reference.
▶ cudaGraphicsRegisterFlagsTextureGather: Specifies that CUDA will perform texture gather
operations on this resource.
Not all Direct3D resources of the above types may be used for interoperability with CUDA. The
following are some limitations.
▶ The primary rendertarget may not be registered with CUDA.
▶ Textures which are not of a format which is 1, 2, or 4 channels of 8, 16, or 32-bit integer or
floating-point data cannot be shared.
▶ Surfaces of depth or stencil formats cannot be shared.
A complete list of supported DXGI formats is as follows. For compactness the notation A_{B,C,D}
represents A_B, A_C, and A_D.
▶ DXGI_FORMAT_A8_UNORM
▶ DXGI_FORMAT_B8G8R8A8_UNORM
▶ DXGI_FORMAT_B8G8R8X8_UNORM
▶ DXGI_FORMAT_R16_FLOAT
▶ DXGI_FORMAT_R16G16B16A16_{FLOAT,SINT,SNORM,UINT,UNORM}
▶ DXGI_FORMAT_R16G16_{FLOAT,SINT,SNORM,UINT,UNORM}
220
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ DXGI_FORMAT_R16_{SINT,SNORM,UINT,UNORM}
▶ DXGI_FORMAT_R32_FLOAT
▶ DXGI_FORMAT_R32G32B32A32_{FLOAT,SINT,UINT}
▶ DXGI_FORMAT_R32G32_{FLOAT,SINT,UINT}
▶ DXGI_FORMAT_R32_{SINT,UINT}
▶ DXGI_FORMAT_R8G8B8A8_{SINT,SNORM,UINT,UNORM,UNORM_SRGB}
▶ DXGI_FORMAT_R8G8_{SINT,SNORM,UINT,UNORM}
▶ DXGI_FORMAT_R8_{SINT,SNORM,UINT,UNORM}
If pD3DResource is of incorrect type or is already registered, then cudaErrorInvalidResourceHan-
dle is returned. If pD3DResource cannot be registered, then cudaErrorUnknown is returned.
See also:
cudaGraphicsUnregisterResource,
cudaGraphicsMapResources,
cudaGraphicsSub-
ResourceGetMappedArray,
cudaGraphicsResourceGetMappedPointer,
::cuGraph-
icsD3D11RegisterResource
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ resource - - Pointer to returned resource handle
▶ pD3DResource - - Direct3D resource to register
▶ flags - - Parameters for resource registration
Returns
cudaSuccess,
cudaErrorInvalidDevice,
cudaErrorInvalidValue,
cudaErrorIn-
validResourceHandle, cudaErrorUnknown
6.8. Direct3D 11 Interoperability [DEPRECATED]
This section describes deprecated Direct3D 11 interoperability functions.
Functions
__host__ cudaError_t cudaD3D11GetDirect3DDevice(ID3D11Device **ppD3D11Device)
Gets the Direct3D device against which the current CUDA context was created.
__host__ cudaError_t cudaD3D11SetDirect3DDevice(ID3D11Device *pD3D11Device, int device=-1)
Sets the Direct3D 11 device to use for interoperability with a CUDA device.
6.8. Direct3D 11 Interoperability [DEPRECATED]
221
CUDA Runtime API Reference Manual, Release 13.5
6.8.1. Functions
__host__ cudaError_t cudaD3D11GetDirect3DDevice(ID3D11Device **ppD3D11Device)
Gets the Direct3D device against which the current CUDA context was created.
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 a D3D11 device in order to achieve maximum interoperability performance.
See also:
cudaD3D11SetDirect3DDevice
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
ppD3D11Device - - Returns the Direct3D device for this thread
Returns
cudaSuccess, cudaErrorUnknown
__host__ cudaError_t cudaD3D11SetDirect3DDevice(ID3D11Device *pD3D11Device, int device =
-1)
Sets the Direct3D 11 device to use for interoperability with a CUDA device.
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 a D3D11 device in order to achieve maximum interoperability performance.
This function will immediately initialize the primary context on device if needed.
See also:
cudaD3D11GetDevice, cudaGraphicsD3D11RegisterResource, cudaDeviceReset
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ pD3D11Device - - Direct3D device to use for interoperability
▶ device - - The CUDA device to use. This device must be among the devices
returned when querying cudaD3D11DeviceListAll from cudaD3D11GetDevices,
may be set to -1 to automatically select an appropriate CUDA device.
222
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Returns
cudaSuccess, cudaErrorInitializationError, cudaErrorInvalidValue, cudaErrorSetOn-
ActiveProcess
6.9. Direct3D 9 Interoperability
impl_private
impl_private
This section describes the Direct3D 9 interoperability functions of the CUDA runtime application pro-
gramming interface. Note that mapping of Direct3D 9 resources is performed with the graphics API
agnostic, resource mapping interface described in Graphics Interopability.
Enumerations
cudaD3D9DeviceList
CUDA devices corresponding to a D3D9 device.
Functions
__host__ cudaError_t cudaD3D9GetDevice(int *device, const char *pszAdapterName)
Gets the device number for an adapter.
__host__ cudaError_t cudaD3D9GetDevices(unsigned int *pCudaDeviceCount, int *pCudaDevices,
unsigned int cudaDeviceCount, IDirect3DDevice9 *pD3D9Device, enum cudaD3D9DeviceList
deviceList)
Gets the CUDA devices corresponding to a Direct3D 9 device.
__host__ cudaError_t cudaD3D9GetDirect3DDevice(IDirect3DDevice9 **ppD3D9Device)
Gets the Direct3D device against which the current CUDA context was created.
__host__ cudaError_t cudaD3D9SetDirect3DDevice(IDirect3DDevice9 *pD3D9Device, int device=-1)
Sets the Direct3D 9 device to use for interoperability with a CUDA device.
__host__ cudaError_t cudaGraphicsD3D9RegisterResource(struct cudaGraphicsResource
**re-
source, IDirect3DResource9 *pD3DResource, unsigned int flags)
Register a Direct3D 9 resource for access by CUDA.
6.9.1. Enumerations
enum cudaD3D9DeviceList
CUDA devices corresponding to a D3D9 device.
Values:
enumerator cudaD3D9DeviceListAll = 1
The CUDA devices for all GPUs used by a D3D9 device.
6.9. Direct3D 9 Interoperability
223
CUDA Runtime API Reference Manual, Release 13.5
enumerator cudaD3D9DeviceListCurrentFrame = 2
The CUDA devices for the GPUs used by a D3D9 device in its currently rendering frame.
enumerator cudaD3D9DeviceListNextFrame = 3
The CUDA devices for the GPUs to be used by a D3D9 device in the next frame
6.9.2. Functions
__host__ cudaError_t cudaD3D9GetDevice(int *device, const char *pszAdapterName)
Gets the device number for an adapter.
Returns in *device the CUDA-compatible device corresponding to the adapter name
pszAdapterName obtained from ::EnumDisplayDevices or ::IDirect3D9::GetAdapterIdentifier(). If
no device on the adapter with name pszAdapterName is CUDA-compatible then the call will fail.
See also:
cudaD3D9SetDirect3DDevice, cudaGraphicsD3D9RegisterResource, ::cuD3D9GetDevice
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ device - - Returns the device corresponding to pszAdapterName
▶ pszAdapterName - - D3D9 adapter to get device for
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorUnknown
__host__ cudaError_t cudaD3D9GetDevices(unsigned int *pCudaDeviceCount, int *pCudaDevices,
unsigned int cudaDeviceCount, IDirect3DDevice9
*pD3D9Device, enum cudaD3D9DeviceList deviceList)
Gets the CUDA devices corresponding to a Direct3D 9 device.
Returns in *pCudaDeviceCount the number of CUDA-compatible devices corresponding to the
Direct3D 9 device pD3D9Device. Also returns in *pCudaDevices at most cudaDeviceCount of
the the CUDA-compatible devices corresponding to the Direct3D 9 device pD3D9Device.
If any of the GPUs being used to render pDevice are not CUDA capable then the call will return
cudaErrorNoDevice.
See also:
cudaGraphicsUnregisterResource,
cudaGraphicsMapResources,
cudaGraphicsSubRe-
sourceGetMappedArray, cudaGraphicsResourceGetMappedPointer, ::cuD3D9GetDevices
Note: Note that this function may also return error codes from previous, asynchronous launches.
224
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Parameters
▶ pCudaDeviceCount - - Returned number of CUDA devices corresponding to
pD3D9Device
▶ pCudaDevices - - Returned CUDA devices corresponding to pD3D9Device
▶ cudaDeviceCount - - The size of the output device array pCudaDevices
▶ pD3D9Device - - Direct3D 9 device to query for CUDA devices
▶ deviceList - - The set of devices to return.
This set may be cu-
daD3D9DeviceListAll for all devices,
cudaD3D9DeviceListCurrentFrame
for the devices used to render the current frame (in SLI), or cu-
daD3D9DeviceListNextFrame for the devices used to render the next frame (in
SLI).
Returns
cudaSuccess, cudaErrorNoDevice, cudaErrorUnknown
__host__ cudaError_t cudaD3D9GetDirect3DDevice(IDirect3DDevice9 **ppD3D9Device)
Gets the Direct3D device against which the current CUDA context was created.
Returns in *ppD3D9Device the Direct3D device against which this CUDA context was created in
cudaD3D9SetDirect3DDevice().
See also:
cudaD3D9SetDirect3DDevice, ::cuD3D9GetDirect3DDevice
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
ppD3D9Device - - Returns the Direct3D device for this thread
Returns
cudaSuccess, cudaErrorInvalidGraphicsContext, cudaErrorUnknown
__host__ cudaError_t cudaD3D9SetDirect3DDevice(IDirect3DDevice9 *pD3D9Device, int device =
-1)
Sets the Direct3D 9 device to use for interoperability with a CUDA device.
Records pD3D9Device as the Direct3D 9 device to use for Direct3D 9 interoperability with the
CUDA device device and sets device as the current device for the calling host thread.
This function will immediately initialize the primary context on device if needed.
If device has already been initialized then this call will fail with the error cudaErrorSetOnActive-
Process. In this case it is necessary to reset device using cudaDeviceReset() before Direct3D 9
interoperability on device may be enabled.
Successfully initializing CUDA interoperability with pD3D9Device will increase the internal ref-
erence count on pD3D9Device. This reference count will be decremented when device is reset
using cudaDeviceReset().
Note that this function is never required for correct functionality. Use of this function will result in
accelerated interoperability only when the operating system is Windows Vista or Windows 7, and
6.9. Direct3D 9 Interoperability
225
CUDA Runtime API Reference Manual, Release 13.5
the device pD3DDdevice is not an IDirect3DDevice9Ex. In all other cirumstances, this function
is not necessary.
See also:
cudaD3D9GetDevice, cudaGraphicsD3D9RegisterResource, cudaDeviceReset
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ pD3D9Device - - Direct3D device to use for this thread
▶ device - - The CUDA device to use. This device must be among the devices re-
turned when querying cudaD3D9DeviceListAll from cudaD3D9GetDevices, may
be set to -1 to automatically select an appropriate CUDA device.
Returns
cudaSuccess, cudaErrorInitializationError, cudaErrorInvalidValue, cudaErrorSetOn-
ActiveProcess
__host__ cudaError_t cudaGraphicsD3D9RegisterResource(struct cudaGraphicsResource
**resource, IDirect3DResource9
*pD3DResource, unsigned int flags)
Register a Direct3D 9 resource for access by CUDA.
Registers the Direct3D 9 resource pD3DResource for access by CUDA.
If this call is successful then the application will be able to map and unmap this resource until it is
unregistered through cudaGraphicsUnregisterResource(). Also on success, this call will increase
the internal reference count on pD3DResource. This reference count will be decremented when
this resource is unregistered through cudaGraphicsUnregisterResource().
This call potentially has a high-overhead and should not be called every frame in interactive ap-
plications.
The type of pD3DResource must be one of the following.
▶ ::IDirect3DVertexBuffer9: may be accessed through a device pointer
▶ ::IDirect3DIndexBuffer9: may be accessed through a device pointer
▶ ::IDirect3DSurface9: may be accessed through an array. Only stand-alone objects of type
::IDirect3DSurface9 may be explicitly shared. In particular, individual mipmap levels and
faces of cube maps may not be registered directly. To access individual surfaces associ-
ated with a texture, one must register the base texture object.
▶ ::IDirect3DBaseTexture9: individual surfaces on this texture may be accessed through an
array.
The flags argument may be used to specify additional parameters at register time. The valid
values for this parameter are
▶ cudaGraphicsRegisterFlagsNone: Specifies no hints about how this resource will be used.
226
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ cudaGraphicsRegisterFlagsSurfaceLoadStore: Specifies that CUDA will bind this resource to
a surface reference.
▶ cudaGraphicsRegisterFlagsTextureGather: Specifies that CUDA will perform texture gather
operations on this resource.
Not all Direct3D resources of the above types may be used for interoperability with CUDA. The
following are some limitations.
▶ The primary rendertarget may not be registered with CUDA.
▶ Resources allocated as shared may not be registered with CUDA.
▶ Textures which are not of a format which is 1, 2, or 4 channels of 8, 16, or 32-bit integer or
floating-point data cannot be shared.
▶ Surfaces of depth or stencil formats cannot be shared.
A complete list of supported formats is as follows:
▶ D3DFMT_L8
▶ D3DFMT_L16
▶ D3DFMT_A8R8G8B8
▶ D3DFMT_X8R8G8B8
▶ D3DFMT_G16R16
▶ D3DFMT_A8B8G8R8
▶ D3DFMT_A8
▶ D3DFMT_A8L8
▶ D3DFMT_Q8W8V8U8
▶ D3DFMT_V16U16
▶ D3DFMT_A16B16G16R16F
▶ D3DFMT_A16B16G16R16
▶ D3DFMT_R32F
▶ D3DFMT_G16R16F
▶ D3DFMT_A32B32G32R32F
▶ D3DFMT_G32R32F
▶ D3DFMT_R16F
If pD3DResource is of incorrect type or is already registered, then cudaErrorInvalidResourceHan-
dle is returned. If pD3DResource cannot be registered, then cudaErrorUnknown is returned.
See also:
cudaD3D9SetDirect3DDevice, cudaGraphicsUnregisterResource, cudaGraphicsMapResources,
cudaGraphicsSubResourceGetMappedArray,
cudaGraphicsResourceGetMappedPointer,
::cu-
GraphicsD3D9RegisterResource
6.9. Direct3D 9 Interoperability
227
CUDA Runtime API Reference Manual, Release 13.5
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ resource - - Pointer to returned resource handle
▶ pD3DResource - - Direct3D resource to register
▶ flags - - Parameters for resource registration
Returns
cudaSuccess,
cudaErrorInvalidDevice,
cudaErrorInvalidValue,
cudaErrorIn-
validResourceHandle, cudaErrorUnknown
6.10. Direct3D 9 Interoperability [DEPRECATED]
This section describes deprecated Direct3D 9 interoperability functions.
Enumerations
cudaD3D9MapFlags
CUDA D3D9 Map Flags.
cudaD3D9RegisterFlags
CUDA D3D9 Register Flags.
Functions
__host__ cudaError_t cudaD3D9Begin(IDirect3DDevice9 *pDevice)
__host__ cudaError_t cudaD3D9End(void)
__host__ cudaError_t cudaD3D9MapResources(int count, IDirect3DResource9 **ppResources)
Map Direct3D resources for access by CUDA.
__host__ cudaError_t cudaD3D9MapVertexBuffer(void **dptr, IDirect3DVertexBuffer9 *pVB)
__host__ cudaError_t cudaD3D9RegisterResource(IDirect3DResource9 *pResource, unsigned int
flags)
Registers a Direct3D resource for access by CUDA.
__host__ cudaError_t cudaD3D9RegisterVertexBuffer(IDirect3DVertexBuffer9 *pVB)
__host__
cudaError_t
cudaD3D9ResourceGetMappedArray(cudaArray
**ppArray,
IDi-
rect3DResource9 *pResource, unsigned int face, unsigned int level)
Get an array through which to access a subresource of a Direct3D resource which has been
mapped for access by CUDA.
228
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaD3D9ResourceGetMappedPitch(size_t *pPitch, size_t *pPitchSlice, IDi-
rect3DResource9 *pResource, unsigned int face, unsigned int level)
Get the pitch of a subresource of a Direct3D resource which has been mapped for access by
CUDA.
__host__ cudaError_t cudaD3D9ResourceGetMappedPointer(void **pPointer, IDirect3DResource9
*pResource, unsigned int face, unsigned int level)
Get a pointer through which to access a subresource of a Direct3D resource which has been
mapped for access by CUDA.
__host__ cudaError_t cudaD3D9ResourceGetMappedSize(size_t *pSize, IDirect3DResource9 *pRe-
source, unsigned int face, unsigned int level)
Get the size of a subresource of a Direct3D resource which has been mapped for access by CUDA.
__host__ cudaError_t cudaD3D9ResourceGetSurfaceDimensions(size_t *pWidth, size_t *pHeight,
size_t *pDepth, IDirect3DResource9 *pResource, unsigned int face, unsigned int level)
Get the dimensions of a registered Direct3D surface.
__host__ cudaError_t cudaD3D9ResourceSetMapFlags(IDirect3DResource9 *pResource, unsigned
int flags)
Set usage flags for mapping a Direct3D resource.
__host__ cudaError_t cudaD3D9UnmapResources(int count, IDirect3DResource9 **ppResources)
Unmap Direct3D resources for access by CUDA.
__host__ cudaError_t cudaD3D9UnmapVertexBuffer(IDirect3DVertexBuffer9 *pVB)
__host__ cudaError_t cudaD3D9UnregisterResource(IDirect3DResource9 *pResource)
Unregisters a Direct3D resource for access by CUDA.
__host__ cudaError_t cudaD3D9UnregisterVertexBuffer(IDirect3DVertexBuffer9 *pVB)
6.10.1. Enumerations
enum cudaD3D9MapFlags
CUDA D3D9 Map Flags.
Values:
enumerator cudaD3D9MapFlagsNone = 0
Default; Assume resource can be read/written.
enumerator cudaD3D9MapFlagsReadOnly = 1
CUDA kernels will not write to this resource.
enumerator cudaD3D9MapFlagsWriteDiscard = 2
CUDA kernels will only write to and will not read from this resource.
enum cudaD3D9RegisterFlags
CUDA D3D9 Register Flags.
Values:
6.10. Direct3D 9 Interoperability [DEPRECATED]
229
CUDA Runtime API Reference Manual, Release 13.5
enumerator cudaD3D9RegisterFlagsNone = 0
Default; Resource can be accessed througa void*.
enumerator cudaD3D9RegisterFlagsArray = 1
Resource can be accessed through a CUarray*.
6.10.2. Functions
__host__ cudaError_t cudaD3D9Begin(IDirect3DDevice9 *pDevice)
__host__ cudaError_t cudaD3D9End(void)
__host__ cudaError_t cudaD3D9MapResources(int count, IDirect3DResource9 **ppResources)
Map Direct3D resources for access by CUDA.
Deprecated:
This function is deprecated as of CUDA 3.0.
Maps the count Direct3D resources in ppResources for access by CUDA.
The resources in ppResources may be accessed in CUDA kernels until they are unmapped. Di-
rect3D should not access any resources while they are mapped by CUDA. If an application does
so, the results are undefined.
This function provides the synchronization guarantee that any Direct3D calls issued be-
fore cudaD3D9MapResources() will complete before any CUDA kernels issued after cu-
daD3D9MapResources() begin.
If any of ppResources have not been registered for use with CUDA or if ppResources contains
any duplicate entries then cudaErrorInvalidResourceHandle is returned. If any of ppResources
are presently mapped for access by CUDA then cudaErrorUnknown is returned.
See also:
cudaGraphicsMapResources
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ count - - Number of resources to map for CUDA
▶ ppResources - - Resources to map for CUDA
Returns
cudaSuccess, cudaErrorInvalidResourceHandle, cudaErrorUnknown
__host__ cudaError_t cudaD3D9MapVertexBuffer(void **dptr, IDirect3DVertexBuffer9 *pVB)
230
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaD3D9RegisterResource(IDirect3DResource9 *pResource, unsigned int
flags)
Registers a Direct3D resource for access by CUDA.
Deprecated:
This function is deprecated as of CUDA 3.0.
Registers the Direct3D resource pResource for access by CUDA.
If this call is successful, then the application will be able to map and unmap this resource until
it is unregistered through cudaD3D9UnregisterResource(). Also on success, this call will increase
the internal reference count on pResource. This reference count will be decremented when this
resource is unregistered through cudaD3D9UnregisterResource().
This call potentially has a high-overhead and should not be called every frame in interactive ap-
plications.
The type of pResource must be one of the following.
▶ ::IDirect3DVertexBuffer9: No notes.
▶ ::IDirect3DIndexBuffer9: No notes.
▶ ::IDirect3DSurface9: Only stand-alone objects of type ::IDirect3DSurface9 may be explicitly
shared. In particular, individual mipmap levels and faces of cube maps may not be registered
directly. To access individual surfaces associated with a texture, one must register the base
texture object.
▶ ::IDirect3DBaseTexture9: When a texture is registered, all surfaces associated with all
mipmap levels of all faces of the texture will be accessible to CUDA.
The flags argument specifies the mechanism through which CUDA will access the Direct3D
resource. The following value is allowed:
▶ cudaD3D9RegisterFlagsNone: Specifies that CUDA will access this resource through a
void*. The pointer, size, and pitch for each subresource of this resource may be queried
through cudaD3D9ResourceGetMappedPointer(), cudaD3D9ResourceGetMappedSize(), and
cudaD3D9ResourceGetMappedPitch() respectively. This option is valid for all resource types.
Not all Direct3D resources of the above types may be used for interoperability with CUDA. The
following are some limitations:
▶ The primary rendertarget may not be registered with CUDA.
▶ Resources allocated as shared may not be registered with CUDA.
▶ Any resources allocated in ::D3DPOOL_SYSTEMMEM or ::D3DPOOL_MANAGED may not be
registered with CUDA.
▶ Textures which are not of a format which is 1, 2, or 4 channels of 8, 16, or 32-bit integer or
floating-point data cannot be shared.
▶ Surfaces of depth or stencil formats cannot be shared.
If Direct3D interoperability is not initialized on this context, then cudaErrorInvalidDevice is re-
turned. If pResource is of incorrect type (e.g, is a non-stand-alone ::IDirect3DSurface9) or is
6.10. Direct3D 9 Interoperability [DEPRECATED]
231
CUDA Runtime API Reference Manual, Release 13.5
already registered, then cudaErrorInvalidResourceHandle is returned. If pResource cannot be
registered then cudaErrorUnknown is returned.
See also:
cudaGraphicsD3D9RegisterResource
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ pResource - - Resource to register
▶ flags - - Parameters for resource registration
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle, cudaErrorUn-
known
__host__ cudaError_t cudaD3D9RegisterVertexBuffer(IDirect3DVertexBuffer9 *pVB)
__host__ cudaError_t cudaD3D9ResourceGetMappedArray(cudaArray **ppArray,
IDirect3DResource9 *pResource,
unsigned int face, unsigned int level)
Get an array through which to access a subresource of a Direct3D resource which has been
mapped for access by CUDA.
Deprecated:
This function is deprecated as of CUDA 3.0.
Returns in *pArray an array through which the subresource of the mapped Direct3D resource
pResource, which corresponds to face and level may be accessed. The value set in pArray
may change every time that pResource is mapped.
If pResource is not registered then cudaErrorInvalidResourceHandle is returned. If pResource
was not registered with usage flags cudaD3D9RegisterFlagsArray, then cudaErrorInvalidResource-
Handle is returned. If pResource is not mapped, then cudaErrorUnknown is returned.
For
usage
requirements
of
face
and
level
parameters,
see
cu-
daD3D9ResourceGetMappedPointer().
See also:
cudaGraphicsSubResourceGetMappedArray
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ ppArray - - Returned array corresponding to subresource
232
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ pResource - - Mapped resource to access
▶ face - - Face of resource to access
▶ level - - Level of resource to access
Returns
cudaSuccess, cudaErrorInvalidResourceHandle, cudaErrorUnknown
__host__ cudaError_t cudaD3D9ResourceGetMappedPitch(size_t *pPitch, size_t *pPitchSlice,
IDirect3DResource9 *pResource,
unsigned int face, unsigned int level)
Get the pitch of a subresource of a Direct3D resource which has been mapped for access by
CUDA.
Deprecated:
This function is deprecated as of CUDA 3.0.
Returns in *pPitch and *pPitchSlice the pitch and Z-slice pitch of the subresource of the
mapped Direct3D resource pResource, which corresponds to face and level. The values set
in pPitch and pPitchSlice may change every time that pResource is mapped.
The pitch and Z-slice pitch values may be used to compute the location of a sample on a surface
as follows.
For a 2D surface, the byte offset of the sample at position x, y from the base pointer of the
surface is:
y * pitch + (bytes per pixel) * x
For a 3D surface, the byte offset of the sample at position x, y, z from the base pointer of the
surface is:
z* slicePitch + y * pitch + (bytes per pixel) * x
Both parameters pPitch and pPitchSlice are optional and may be set to NULL.
If pResource is not of type ::IDirect3DBaseTexture9 or one of its sub-types or if pResource
has not been registered for use with CUDA, then cudaErrorInvalidResourceHandle is returned. If
pResource was not registered with usage flags cudaD3D9RegisterFlagsNone, then cudaErrorIn-
validResourceHandle is returned. If pResource is not mapped for access by CUDA then cudaEr-
rorUnknown is returned.
For
usage
requirements
of
face
and
level
parameters,
see
cu-
daD3D9ResourceGetMappedPointer().
See also:
cudaGraphicsResourceGetMappedPointer
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ pPitch - - Returned pitch of subresource
6.10. Direct3D 9 Interoperability [DEPRECATED]
233
CUDA Runtime API Reference Manual, Release 13.5
▶ pPitchSlice - - Returned Z-slice pitch of subresource
▶ pResource - - Mapped resource to access
▶ face - - Face of resource to access
▶ level - - Level of resource to access
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle, cudaErrorUn-
known
__host__ cudaError_t cudaD3D9ResourceGetMappedPointer(void **pPointer, IDirect3DResource9
*pResource, unsigned int face,
unsigned int level)
Get a pointer through which to access a subresource of a Direct3D resource which has been
mapped for access by CUDA.
Deprecated:
This function is deprecated as of CUDA 3.0.
Returns in *pPointer the base pointer of the subresource of the mapped Direct3D resource
pResource, which corresponds to face and level. The value set in pPointer may change
every time that pResource is mapped.
If pResource is not registered, then cudaErrorInvalidResourceHandle is returned. If pResource
was not registered with usage flags cudaD3D9RegisterFlagsNone, then cudaErrorInvalidResource-
Handle is returned. If pResource is not mapped, then cudaErrorUnknown is returned.
If pResource is of type ::IDirect3DCubeTexture9, then face must one of the values enumer-
ated by type ::D3DCUBEMAP_FACES. For all other types, face must be 0. If face is invalid, then
cudaErrorInvalidValue is returned.
If pResource is of type ::IDirect3DBaseTexture9, then level must correspond to a valid mipmap
level. Only mipmap level 0 is supported for now. For all other types level must be 0. If level is
invalid, then cudaErrorInvalidValue is returned.
See also:
cudaGraphicsResourceGetMappedPointer
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ pPointer - - Returned pointer corresponding to subresource
▶ pResource - - Mapped resource to access
▶ face - - Face of resource to access
▶ level - - Level of resource to access
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle, cudaErrorUn-
known
234
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaD3D9ResourceGetMappedSize(size_t *pSize, IDirect3DResource9
*pResource, unsigned int face, unsigned
int level)
Get the size of a subresource of a Direct3D resource which has been mapped for access by CUDA.
Deprecated:
This function is deprecated as of CUDA 3.0.
Returns in *pSize the size of the subresource of the mapped Direct3D resource pResource,
which corresponds to face and level. The value set in pSize may change every time that
pResource is mapped.
If pResource has not been registered for use with CUDA then cudaErrorInvalidResourceHandle is
returned. If pResource was not registered with usage flags cudaD3D9RegisterFlagsNone, then
cudaErrorInvalidResourceHandle is returned. If pResource is not mapped for access by CUDA
then cudaErrorUnknown is returned.
For
usage
requirements
of
face
and
level
parameters,
see
cu-
daD3D9ResourceGetMappedPointer().
See also:
cudaGraphicsResourceGetMappedPointer
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ pSize - - Returned size of subresource
▶ pResource - - Mapped resource to access
▶ face - - Face of resource to access
▶ level - - Level of resource to access
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle, cudaErrorUn-
known
__host__ cudaError_t cudaD3D9ResourceGetSurfaceDimensions(size_t *pWidth, size_t *pHeight,
size_t *pDepth,
IDirect3DResource9
*pResource, unsigned int face,
unsigned int level)
Get the dimensions of a registered Direct3D surface.
Deprecated:
This function is deprecated as of CUDA 3.0.
Returns in *pWidth, *pHeight, and *pDepth the dimensions of the subresource of the mapped
Direct3D resource pResource which corresponds to face and level.
6.10. Direct3D 9 Interoperability [DEPRECATED]
235
CUDA Runtime API Reference Manual, Release 13.5
Since anti-aliased surfaces may have multiple samples per pixel, it is possible that the dimen-
sions of a resource will be an integer factor larger than the dimensions reported by the Direct3D
runtime.
The parameters pWidth, pHeight, and pDepth are optional. For 2D surfaces, the value returned
in *pDepth will be 0.
If pResource is not of type ::IDirect3DBaseTexture9 or ::IDirect3DSurface9 or if pResource has
not been registered for use with CUDA, then cudaErrorInvalidResourceHandle is returned.
For
usage
requirements
of
face
and
level
parameters,
see
cu-
daD3D9ResourceGetMappedPointer.
See also:
cudaGraphicsSubResourceGetMappedArray
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ pWidth - - Returned width of surface
▶ pHeight - - Returned height of surface
▶ pDepth - - Returned depth of surface
▶ pResource - - Registered resource to access
▶ face - - Face of resource to access
▶ level - - Level of resource to access
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle,
__host__ cudaError_t cudaD3D9ResourceSetMapFlags(IDirect3DResource9 *pResource, unsigned
int flags)
Set usage flags for mapping a Direct3D resource.
Deprecated:
This function is deprecated as of CUDA 3.0.
Set flags for mapping the Direct3D resource pResource.
Changes to flags will take effect the next time pResource is mapped. The flags argument may
be any of the following:
▶ cudaD3D9MapFlagsNone: Specifies no hints about how this resource will be used. It is there-
fore assumed that this resource will be read from and written to by CUDA kernels. This is
the default value.
▶ cudaD3D9MapFlagsReadOnly: Specifies that CUDA kernels which access this resource will
not write to this resource.
236
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ cudaD3D9MapFlagsWriteDiscard: Specifies that CUDA kernels which access this resource
will not read from this resource and will write over the entire contents of the resource, so
none of the data previously stored in the resource will be preserved.
If pResource has not been registered for use with CUDA, then cudaErrorInvalidResourceHandle
is returned. If pResource is presently mapped for access by CUDA, then cudaErrorUnknown is
returned.
See also:
::cudaInteropResourceSetMapFlags
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ pResource - - Registered resource to set flags for
▶ flags - - Parameters for resource mapping
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle, cudaErrorUn-
known
__host__ cudaError_t cudaD3D9UnmapResources(int count, IDirect3DResource9 **ppResources)
Unmap Direct3D resources for access by CUDA.
Deprecated:
This function is deprecated as of CUDA 3.0.
Unmaps the count Direct3D resources in ppResources.
This function provides the synchronization guarantee that any CUDA kernels issued be-
fore cudaD3D9UnmapResources() will complete before any Direct3D calls issued after cu-
daD3D9UnmapResources() begin.
If any of ppResources have not been registered for use with CUDA or if ppResources contains
any duplicate entries, then cudaErrorInvalidResourceHandle is returned. If any of ppResources
are not presently mapped for access by CUDA then cudaErrorUnknown is returned.
See also:
cudaGraphicsUnmapResources
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ count - - Number of resources to unmap for CUDA
▶ ppResources - - Resources to unmap for CUDA
6.10. Direct3D 9 Interoperability [DEPRECATED]
237
CUDA Runtime API Reference Manual, Release 13.5
Returns
cudaSuccess, cudaErrorInvalidResourceHandle, cudaErrorUnknown
__host__ cudaError_t cudaD3D9UnmapVertexBuffer(IDirect3DVertexBuffer9 *pVB)
__host__ cudaError_t cudaD3D9UnregisterResource(IDirect3DResource9 *pResource)
Unregisters a Direct3D resource for access by CUDA.
Deprecated:
This function is deprecated as of CUDA 3.0.
Unregisters the Direct3D resource pResource so it is not accessible by CUDA unless registered
again.
If pResource is not registered, then cudaErrorInvalidResourceHandle is returned.
See also:
cudaGraphicsUnregisterResource
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
pResource - - Resource to unregister
Returns
cudaSuccess, cudaErrorInvalidResourceHandle, cudaErrorUnknown
__host__ cudaError_t cudaD3D9UnregisterVertexBuffer(IDirect3DVertexBuffer9 *pVB)
6.11. Driver Entry Point Access
This section describes the driver entry point access functions of CUDA runtime application program-
ming interface.
Functions
__host__ cudaError_t cudaGetDriverEntryPoint(const char *symbol, void **funcPtr, unsigned long
long flags, enum cudaDriverEntryPointQueryResult *driverStatus=NULL)
Returns the requested driver API function pointer.
__host__ cudaError_t cudaGetDriverEntryPointByVersion(const char *symbol, void **funcPtr, un-
signed int cudaVersion, unsigned long long flags, enum cudaDriverEntryPointQueryResult
*driverStatus=NULL)
Returns the requested driver API function pointer by CUDA version.
238
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
6.11.1. Functions
__host__ cudaError_t cudaGetDriverEntryPoint(const char *symbol, void **funcPtr, unsigned
long long flags, enum
cudaDriverEntryPointQueryResult *driverStatus =
NULL)
Returns the requested driver API function pointer.
Deprecated:
This function is deprecated as of CUDA 13.0
Returns in **funcPtr the address of the CUDA driver function for the requested flags.
For a requested driver symbol, if the CUDA version in which the driver symbol was introduced is
less than or equal to the CUDA runtime version, the API will return the function pointer to the
corresponding versioned driver function.
The pointer returned by the API should be cast to a function pointer matching the requested
driver function’s definition in the API header file. The function pointer typedef can be picked up
from the corresponding typedefs header file. For example, cudaTypedefs.h consists of function
pointer typedefs for driver APIs defined in cuda.h.
The API will return cudaSuccess and set the returned funcPtr if the requested driver function
is valid and supported on the platform.
The API will return cudaSuccess and set the returned funcPtr to NULL if the requested driver
function is not supported on the platform, no ABI compatible driver function exists for the CUDA
runtime version or if the driver symbol is invalid.
It will also set the optional driverStatus to one of the values in cudaDriverEntryPointQueryRe-
sult with the following meanings:
▶ cudaDriverEntryPointSuccess - The requested symbol was succesfully found based on input
arguments and pfn is valid
▶ cudaDriverEntryPointSymbolNotFound - The requested symbol was not found
▶ cudaDriverEntryPointVersionNotSufficent - The requested symbol was found but is not sup-
ported by the current runtime version (CUDART_VERSION)
The requested flags can be:
▶ cudaEnableDefault: This is the default mode. This is equivalent to cudaEnablePerThread-
DefaultStream if the code is compiled with —default-stream per-thread compilation
flag or the macro CUDA_API_PER_THREAD_DEFAULT_STREAM is defined; cudaEnableLega-
cyStream otherwise.
▶ cudaEnableLegacyStream: This will enable the search for all driver symbols that match the
requested driver symbol name except the corresponding per-thread versions.
▶ cudaEnablePerThreadDefaultStream: This will enable the search for all driver symbols that
match the requested driver symbol name including the per-thread versions. If a per-thread
version is not found, the API will return the legacy version of the driver function.
See also:
::cuGetProcAddress
6.11. Driver Entry Point Access
239
CUDA Runtime API Reference Manual, Release 13.5
Note: This API is deprecated and cudaGetDriverEntryPointByVersion (with a hardcoded ::cudaV-
ersion) should be used instead.
Note: Version mixing among CUDA-defined types and driver API versions is strongly discouraged
and doing so can result in an undefined behavior. See Rules for version mixing.
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
▶ symbol - - The base name of the driver API function to look for. As an example,
for the driver API ::cuMemAlloc_v2, symbol would be cuMemAlloc. Note that
the API will use the CUDA runtime version to return the address to the most
recent ABI compatible driver symbol, ::cuMemAlloc or ::cuMemAlloc_v2.
▶ funcPtr - - Location to return the function pointer to the requested driver
function
▶ flags - - Flags to specify search options.
▶ driverStatus - - Optional location to store the status of finding the symbol
from the driver. See cudaDriverEntryPointQueryResult for possible values.
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorNotSupported
__host__ cudaError_t cudaGetDriverEntryPointByVersion(const char *symbol, void **funcPtr,
unsigned int cudaVersion, unsigned
long long flags, enum
cudaDriverEntryPointQueryResult
*driverStatus = NULL)
Returns the requested driver API function pointer by CUDA version.
Returns in **funcPtr the address of the CUDA driver function for the requested flags and CUDA
driver version.
The CUDA version is specified as (1000 * major + 10 * minor), so CUDA 11.2 should be specified
as 11020. For a requested driver symbol, if the specified CUDA version is greater than or equal
to the CUDA version in which the driver symbol was introduced, this API will return the function
pointer to the corresponding versioned function. If the specified CUDA version is greater than
the driver version, the API will return cudaErrorInvalidValue.
The pointer returned by the API should be cast to a function pointer matching the requested
driver function’s definition in the API header file. The function pointer typedef can be picked up
240
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
from the corresponding typedefs header file. For example, cudaTypedefs.h consists of function
pointer typedefs for driver APIs defined in cuda.h.
For the case where the CUDA version requested is greater than the CUDA Toolkit installed, there
may not be an appropriate function pointer typedef in the corresponding header file and may
need a custom typedef to match the driver function signature returned. This can be done by
getting the typedefs from a later toolkit or creating appropriately matching custom function
typedefs.
The API will return cudaSuccess and set the returned funcPtr if the requested driver function
is valid and supported on the platform.
The API will return cudaSuccess and set the returned funcPtr to NULL if the requested driver
function is not supported on the platform, no ABI compatible driver function exists for the re-
quested version or if the driver symbol is invalid.
It will also set the optional driverStatus to one of the values in cudaDriverEntryPointQueryRe-
sult with the following meanings:
▶ cudaDriverEntryPointSuccess - The requested symbol was succesfully found based on input
arguments and pfn is valid
▶ cudaDriverEntryPointSymbolNotFound - The requested symbol was not found
▶ cudaDriverEntryPointVersionNotSufficent - The requested symbol was found but is not sup-
ported by the specified version cudaVersion
The requested flags can be:
▶ cudaEnableDefault: This is the default mode. This is equivalent to cudaEnablePerThread-
DefaultStream if the code is compiled with —default-stream per-thread compilation
flag or the macro CUDA_API_PER_THREAD_DEFAULT_STREAM is defined; cudaEnableLega-
cyStream otherwise.
▶ cudaEnableLegacyStream: This will enable the search for all driver symbols that match the
requested driver symbol name except the corresponding per-thread versions.
▶ cudaEnablePerThreadDefaultStream: This will enable the search for all driver symbols that
match the requested driver symbol name including the per-thread versions. If a per-thread
version is not found, the API will return the legacy version of the driver function.
See also:
::cuGetProcAddress
Note: Version mixing among CUDA-defined types and driver API versions is strongly discouraged
and doing so can result in an undefined behavior. See Rules for version mixing.
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.11. Driver Entry Point Access
241
CUDA Runtime API Reference Manual, Release 13.5
Parameters
▶ symbol - - The base name of the driver API function to look for. As an example,
for the driver API ::cuMemAlloc_v2, symbol would be cuMemAlloc.
▶ funcPtr - - Location to return the function pointer to the requested driver
function
▶ cudaVersion - - The CUDA version to look for the requested driver symbol.
▶ flags - - Flags to specify search options.
▶ driverStatus - - Optional location to store the status of finding the symbol
from the driver. See cudaDriverEntryPointQueryResult for possible values.
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorNotSupported
6.12. EGL Interoperability
This section describes the EGL interoperability functions of the CUDA runtime application program-
ming interface.
Functions
__host__ cudaError_t cudaEGLStreamConsumerAcquireFrame(cudaEglStreamConnection *conn,
cudaGraphicsResource_t *pCudaResource, cudaStream_t *pStream, unsigned int timeout)
Acquire an image frame from the EGLStream with CUDA as a consumer.
__host__
cudaError_t
cudaEGLStreamConsumerConnect(cudaEglStreamConnection
*conn,
EGLStreamKHR eglStream)
Connect CUDA to EGLStream as a consumer.
__host__
cudaError_t
cudaEGLStreamConsumerConnectWithFlags(cudaEglStreamConnection
*conn, EGLStreamKHR eglStream, unsigned int flags)
Connect CUDA to EGLStream as a consumer with given flags.
__host__ cudaError_t cudaEGLStreamConsumerDisconnect(cudaEglStreamConnection *conn)
Disconnect CUDA as a consumer to EGLStream .
__host__ cudaError_t cudaEGLStreamConsumerReleaseFrame(cudaEglStreamConnection *conn,
cudaGraphicsResource_t pCudaResource, cudaStream_t *pStream)
Releases the last frame acquired from the EGLStream.
__host__
cudaError_t
cudaEGLStreamProducerConnect(cudaEglStreamConnection
*conn,
EGLStreamKHR eglStream, EGLint width, EGLint height)
Connect CUDA to EGLStream as a producer.
__host__ cudaError_t cudaEGLStreamProducerDisconnect(cudaEglStreamConnection *conn)
Disconnect CUDA as a producer to EGLStream .
__host__ cudaError_t cudaEGLStreamProducerPresentFrame(cudaEglStreamConnection *conn, cu-
daEglFrame eglframe, cudaStream_t *pStream)
Present a CUDA eglFrame to the EGLStream with CUDA as a producer.
242
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaEGLStreamProducerReturnFrame(cudaEglStreamConnection *conn, cud-
aEglFrame *eglframe, cudaStream_t *pStream)
Return the CUDA eglFrame to the EGLStream last released by the consumer.
__host__ cudaError_t cudaEventCreateFromEGLSync(cudaEvent_t *phEvent, EGLSyncKHR eglSync,
unsigned int flags)
Creates an event from EGLSync object.
__host__ cudaError_t cudaGraphicsEGLRegisterImage(struct cudaGraphicsResource **pCudaRe-
source, EGLImageKHR image, unsigned int flags)
Registers an EGL image.
__host__ cudaError_t cudaGraphicsResourceGetMappedEglFrame(cudaEglFrame *eglFrame, cuda-
GraphicsResource_t resource, unsigned int index, unsigned int mipLevel)
Get an eglFrame through which to access a registered EGL graphics resource.
6.12.1. Functions
__host__ cudaError_t cudaEGLStreamConsumerAcquireFrame(cudaEglStreamConnection *conn,
cudaGraphicsResource_t
*pCudaResource, cudaStream_t
*pStream, unsigned int timeout)
Acquire an image frame from the EGLStream with CUDA as a consumer.
Acquire an image frame from EGLStreamKHR. cudaGraphicsResourceGetMappedEglFrame can be
called on pCudaResource to get cudaEglFrame.
See also:
cudaEGLStreamConsumerConnect, cudaEGLStreamConsumerDisconnect, cudaEGLStreamCon-
sumerReleaseFrame, ::cuEGLStreamConsumerAcquireFrame
Parameters
▶ conn - - Connection on which to acquire
▶ pCudaResource - - CUDA resource on which the EGLStream frame will be
mapped for use.
▶ pStream - - CUDA stream for synchronization and any data migrations implied
by cudaEglResourceLocationFlags.
▶ timeout - - Desired timeout in usec.
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorUnknown, cudaErrorLaunchTimeout
__host__ cudaError_t cudaEGLStreamConsumerConnect(cudaEglStreamConnection *conn,
EGLStreamKHR eglStream)
Connect CUDA to EGLStream as a consumer.
Connect CUDA as a consumer to EGLStreamKHR specified by eglStream.
The EGLStreamKHR is an EGL object that transfers a sequence of image frames from one API to
another.
6.12. EGL Interoperability
243
CUDA Runtime API Reference Manual, Release 13.5
See also:
cudaEGLStreamConsumerDisconnect, cudaEGLStreamConsumerAcquireFrame, cudaEGLStream-
ConsumerReleaseFrame, ::cuEGLStreamConsumerConnect
Parameters
▶ conn - - Pointer to the returned connection handle
▶ eglStream - - EGLStreamKHR handle
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorUnknown
__host__ cudaError_t cudaEGLStreamConsumerConnectWithFlags(cudaEglStreamConnection
*conn, EGLStreamKHR
eglStream, unsigned int
flags)
Connect CUDA to EGLStream as a consumer with given flags.
Connect CUDA as a consumer to EGLStreamKHR specified by stream with specified flags de-
fined by cudaEglResourceLocationFlags.
The flags specify whether the consumer wants to access frames from system memory or video
memory. Default is cudaEglResourceLocationVidmem.
See also:
cudaEGLStreamConsumerDisconnect, cudaEGLStreamConsumerAcquireFrame, cudaEGLStream-
ConsumerReleaseFrame, ::cuEGLStreamConsumerConnectWithFlags
Parameters
▶ conn - - Pointer to the returned connection handle
▶ eglStream - - EGLStreamKHR handle
▶ flags - - Flags denote intended location - system or video.
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorUnknown
__host__ cudaError_t cudaEGLStreamConsumerDisconnect(cudaEglStreamConnection *conn)
Disconnect CUDA as a consumer to EGLStream .
Disconnect CUDA as a consumer to EGLStreamKHR.
See also:
cudaEGLStreamConsumerConnect, cudaEGLStreamConsumerAcquireFrame, cudaEGLStreamCon-
sumerReleaseFrame, ::cuEGLStreamConsumerDisconnect
Parameters
conn - - Conection to disconnect.
244
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorUnknown
__host__ cudaError_t cudaEGLStreamConsumerReleaseFrame(cudaEglStreamConnection *conn,
cudaGraphicsResource_t
pCudaResource, cudaStream_t
*pStream)
Releases the last frame acquired from the EGLStream.
Release the acquired image frame specified by pCudaResource to EGLStreamKHR.
See also:
cudaEGLStreamConsumerConnect, cudaEGLStreamConsumerDisconnect, cudaEGLStreamCon-
sumerAcquireFrame, ::cuEGLStreamConsumerReleaseFrame
Parameters
▶ conn - - Connection on which to release
▶ pCudaResource - - CUDA resource whose corresponding frame is to be re-
leased
▶ pStream - - CUDA stream on which release will be done.
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorUnknown
__host__ cudaError_t cudaEGLStreamProducerConnect(cudaEglStreamConnection *conn,
EGLStreamKHR eglStream, EGLint width,
EGLint height)
Connect CUDA to EGLStream as a producer.
Connect CUDA as a producer to EGLStreamKHR specified by stream.
The EGLStreamKHR is an EGL object that transfers a sequence of image frames from one API to
another.
See also:
cudaEGLStreamProducerDisconnect, cudaEGLStreamProducerPresentFrame, cudaEGLStreamPro-
ducerReturnFrame, ::cuEGLStreamProducerConnect
Parameters
▶ conn - - Pointer to the returned connection handle
▶ eglStream - - EGLStreamKHR handle
▶ width - - width of the image to be submitted to the stream
▶ height - - height of the image to be submitted to the stream
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorUnknown
6.12. EGL Interoperability
245
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaEGLStreamProducerDisconnect(cudaEglStreamConnection *conn)
Disconnect CUDA as a producer to EGLStream .
Disconnect CUDA as a producer to EGLStreamKHR.
See also:
cudaEGLStreamProducerConnect, cudaEGLStreamProducerPresentFrame, cudaEGLStreamPro-
ducerReturnFrame, ::cuEGLStreamProducerDisconnect
Parameters
conn - - Conection to disconnect.
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorUnknown
__host__ cudaError_t cudaEGLStreamProducerPresentFrame(cudaEglStreamConnection *conn,
cudaEglFrame eglframe,
cudaStream_t *pStream)
Present a CUDA eglFrame to the EGLStream with CUDA as a producer.
The cudaEglFrame is defined as:
typedef struct cudaEglFrame_st {
union {
cudaArray_t
pArray[CUDA_EGL_MAX_PLANES];
struct cudaPitchedPtr
pPitch[CUDA_EGL_MAX_PLANES];
} frame;
cudaEglPlaneDesc planeDesc[CUDA_EGL_MAX_PLANES];
unsigned int planeCount;
cudaEglFrameType frameType;
cudaEglColorFormat eglColorFormat;
} cudaEglFrame;
For cudaEglFrame of type cudaEglFrameTypePitch, the application may present sub-region of a
memory allocation. In that case, cudaPitchedPtr::ptr will specify the start address of the sub-
region in the allocation and cudaEglPlaneDesc will specify the dimensions of the sub-region.
See also:
cudaEGLStreamProducerConnect, cudaEGLStreamProducerDisconnect, cudaEGLStreamProduc-
erReturnFrame, ::cuEGLStreamProducerPresentFrame
Parameters
▶ conn - - Connection on which to present the CUDA array
▶ eglframe - - CUDA Eglstream Proucer Frame handle to be sent to the consumer
over EglStream.
▶ pStream - - CUDA stream on which to present the frame.
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorUnknown
246
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaEGLStreamProducerReturnFrame(cudaEglStreamConnection *conn,
cudaEglFrame *eglframe,
cudaStream_t *pStream)
Return the CUDA eglFrame to the EGLStream last released by the consumer.
This API can potentially return cudaErrorLaunchTimeout if the consumer has not returned a
frame to EGL stream. If timeout is returned the application can retry.
See also:
cudaEGLStreamProducerConnect, cudaEGLStreamProducerDisconnect, cudaEGLStreamProduc-
erPresentFrame, ::cuEGLStreamProducerReturnFrame
Parameters
▶ conn - - Connection on which to present the CUDA array
▶ eglframe - - CUDA Eglstream Proucer Frame handle returned from the con-
sumer over EglStream.
▶ pStream - - CUDA stream on which to return the frame.
Returns
cudaSuccess, cudaErrorLaunchTimeout, cudaErrorInvalidValue, cudaErrorUnknown
__host__ cudaError_t cudaEventCreateFromEGLSync(cudaEvent_t *phEvent, EGLSyncKHR
eglSync, unsigned int flags)
Creates an event from EGLSync object.
Creates an event *phEvent from an EGLSyncKHR eglSync with the flages specified via flags.
Valid flags include:
▶ cudaEventDefault: Default event creation flag.
▶ cudaEventBlockingSync: Specifies that the created event should use blocking synchroniza-
tion. A CPU thread that uses cudaEventSynchronize() to wait on an event created with this
flag will block until the event has actually been completed.
cudaEventRecord and TimingData are not supported for events created from EGLSync.
The EGLSyncKHR is an opaque handle to an EGL sync object. typedef void* EGLSyncKHR
See also:
cudaEventQuery, cudaEventSynchronize, cudaEventDestroy
Parameters
▶ phEvent - - Returns newly created event
▶ eglSync - - Opaque handle to EGLSync object
▶ flags - - Event creation flags
Returns
cudaSuccess, cudaErrorInitializationError, cudaErrorInvalidValue, cudaErrorLaunch-
Failure, cudaErrorMemoryAllocation
6.12. EGL Interoperability
247
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaGraphicsEGLRegisterImage(struct cudaGraphicsResource
**pCudaResource, EGLImageKHR image,
unsigned int flags)
Registers an EGL image.
Registers the EGLImageKHR specified by image for access by CUDA. A handle to the registered
object is returned as pCudaResource. Additional Mapping/Unmapping is not required for the
registered resource and cudaGraphicsResourceGetMappedEglFrame can be directly called on the
pCudaResource.
The application will be responsible for synchronizing access to shared objects. The application
must ensure that any pending operation which access the objects have completed before passing
control to CUDA. This may be accomplished by issuing and waiting for glFinish command on all
GLcontexts (for OpenGL and likewise for other APIs). The application will be also responsible for
ensuring that any pending operation on the registered CUDA resource has completed prior to
executing subsequent commands in other APIs accesing the same memory objects. This can be
accomplished by calling cuCtxSynchronize or cuEventSynchronize (preferably).
The surface’s intended usage is specified using flags, 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.
The EGLImageKHR is an object which can be used to create EGLImage target resource. It is
defined as a void pointer. typedef void* EGLImageKHR
See also:
cudaGraphicsUnregisterResource,
cudaGraphicsResourceGetMappedEglFrame,
::cuGraphic-
sEGLRegisterImage
Parameters
▶ pCudaResource - - Pointer to the returned object handle
▶ image - - An EGLImageKHR image which can be used to create target resource.
▶ flags - - Map flags
Returns
cudaSuccess, cudaErrorInvalidResourceHandle, cudaErrorInvalidValue, cudaErrorUn-
known
__host__ cudaError_t cudaGraphicsResourceGetMappedEglFrame(cudaEglFrame *eglFrame,
cudaGraphicsResource_t
resource, unsigned int index,
unsigned int mipLevel)
Get an eglFrame through which to access a registered EGL graphics resource.
248
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Returns in *eglFrame an eglFrame pointer through which the registered graphics resource re-
source may be accessed. This API can only be called for EGL graphics resources.
The cudaEglFrame is defined as
typedef struct cudaEglFrame_st {
union {
cudaArray_t
pArray[CUDA_EGL_MAX_PLANES];
struct cudaPitchedPtr
pPitch[CUDA_EGL_MAX_PLANES];
} frame;
cudaEglPlaneDesc planeDesc[CUDA_EGL_MAX_PLANES];
unsigned int planeCount;
cudaEglFrameType frameType;
cudaEglColorFormat eglColorFormat;
} cudaEglFrame;
See also:
cudaGraphicsSubResourceGetMappedArray,
cudaGraphicsResourceGetMappedPointer,
::cu-
GraphicsResourceGetMappedEglFrame
Note: Note that in case of multiplanar *eglFrame, pitch of only first plane (unsigned int cud-
aEglPlaneDesc::pitch) is to be considered by the application.
Parameters
▶ eglFrame - - Returned eglFrame.
▶ resource - - Registered resource to access.
▶ index - - Index for cubemap surfaces.
▶ mipLevel - - Mipmap level for the subresource to access.
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorUnknown
6.13. Error Handling
This section describes the error handling functions of the CUDA runtime application programming
interface.
6.13. Error Handling
249
CUDA Runtime API Reference Manual, Release 13.5
Functions
__host__ const char * cudaGetErrorName(cudaError_t error)
Returns the string representation of an error code enum name.
__host__ const char * cudaGetErrorString(cudaError_t error)
Returns the description string for an error code.
__host__ cudaError_t cudaGetLastError(void)
Returns the last error from a runtime call.
__host__ cudaError_t cudaPeekAtLastError(void)
Returns the last error from a runtime call.
6.13.1. Functions
__host__ const char *cudaGetErrorName(cudaError_t error)
Returns the string representation of an error code enum name.
Returns a string containing the name of an error code in the enum. If the error code is not
recognized, “unrecognized error code” is returned.
See also:
cudaGetErrorString, cudaGetLastError, cudaPeekAtLastError, cudaError, ::cuGetErrorName
Parameters
error - - Error code to convert to string
Returns
char* pointer to a NULL-terminated string
__host__ const char *cudaGetErrorString(cudaError_t error)
Returns the description string for an error code.
Returns the description string for an error code. If the error code is not recognized, “unrecognized
error code” is returned.
See also:
cudaGetErrorName, cudaGetLastError, cudaPeekAtLastError, cudaError, ::cuGetErrorString
Parameters
error - - Error code to convert to string
Returns
char* pointer to a NULL-terminated string
__host__ cudaError_t cudaGetLastError(void)
Returns the last error from a runtime call.
Returns the last error that has been produced by any of the runtime calls in the same instance
of the CUDA Runtime library in the host thread and resets it to cudaSuccess.
250
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Note: Multiple instances of the CUDA Runtime library can be present in an application when using
a library that statically links the CUDA Runtime.
See also:
cudaPeekAtLastError, cudaGetErrorName, cudaGetErrorString, cudaError
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.
Returns
cudaSuccess, cudaErrorMissingConfiguration, cudaErrorMemoryAllocation, cudaEr-
rorInitializationError, cudaErrorLaunchFailure, cudaErrorLaunchTimeout, cudaEr-
rorLaunchOutOfResources, cudaErrorInvalidDeviceFunction, cudaErrorInvalidCon-
figuration, cudaErrorInvalidDevice, cudaErrorInvalidValue, cudaErrorInvalidPitch-
Value, cudaErrorInvalidSymbol, cudaErrorUnmapBufferObjectFailed, cudaErrorIn-
validDevicePointer, cudaErrorInvalidTexture, cudaErrorInvalidTextureBinding, cu-
daErrorInvalidChannelDescriptor, cudaErrorInvalidMemcpyDirection, cudaErrorIn-
validFilterSetting, cudaErrorInvalidNormSetting, cudaErrorUnknown, cudaError-
InvalidResourceHandle, cudaErrorInsufficientDriver, cudaErrorNoDevice, cudaEr-
rorSetOnActiveProcess, cudaErrorStartupFailure, cudaErrorInvalidPtx, cudaErrorUn-
supportedPtxVersion, cudaErrorNoKernelImageForDevice, cudaErrorJitCompilerNot-
Found, cudaErrorJitCompilationDisabled
__host__ cudaError_t cudaPeekAtLastError(void)
Returns the last error from a runtime call.
Returns the last error that has been produced by any of the runtime calls in the same instance
of the CUDA Runtime library in the host thread. This call does not reset the error to cudaSuccess
like cudaGetLastError().
Note: Multiple instances of the CUDA Runtime library can be present in an application when using
a library that statically links the CUDA Runtime.
See also:
cudaGetLastError, cudaGetErrorName, cudaGetErrorString, cudaError
Note: Note that this function may also return error codes from previous, asynchronous launches.
6.13. Error Handling
251
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.
Returns
cudaSuccess, cudaErrorMissingConfiguration, cudaErrorMemoryAllocation, cudaEr-
rorInitializationError, cudaErrorLaunchFailure, cudaErrorLaunchTimeout, cudaEr-
rorLaunchOutOfResources, cudaErrorInvalidDeviceFunction, cudaErrorInvalidCon-
figuration, cudaErrorInvalidDevice, cudaErrorInvalidValue, cudaErrorInvalidPitch-
Value, cudaErrorInvalidSymbol, cudaErrorUnmapBufferObjectFailed, cudaErrorIn-
validDevicePointer, cudaErrorInvalidTexture, cudaErrorInvalidTextureBinding, cu-
daErrorInvalidChannelDescriptor, cudaErrorInvalidMemcpyDirection, cudaErrorIn-
validFilterSetting, cudaErrorInvalidNormSetting, cudaErrorUnknown, cudaError-
InvalidResourceHandle, cudaErrorInsufficientDriver, cudaErrorNoDevice, cudaEr-
rorSetOnActiveProcess, cudaErrorStartupFailure, cudaErrorInvalidPtx, cudaErrorUn-
supportedPtxVersion, cudaErrorNoKernelImageForDevice, cudaErrorJitCompilerNot-
Found, cudaErrorJitCompilationDisabled
6.14. Error Log Management Functions
This section describes the error log management functions of the CUDA runtime application program-
ming interface.
The Error Log Management interface will operate on both the CUDA Driver and CUDA Runtime.
Functions
__host__ cudaError_t cudaLogsCurrent(cudaLogIterator *iterator_out, unsigned int flags)
Sets log iterator to point to the end of log buffer, where the next message would be written.
__host__ cudaError_t cudaLogsDumpToFile(cudaLogIterator *iterator, const char *pathToFile, un-
signed int flags)
Dump accumulated driver logs into a file.
__host__ cudaError_t cudaLogsDumpToMemory(cudaLogIterator *iterator, char *buffer, size_t *size,
unsigned int flags)
Dump accumulated driver logs into a buffer.
__host__ cudaError_t cudaLogsRegisterCallback(cudaLogsCallback_t callbackFunc, void *userData,
cudaLogsCallbackHandle *callback_out)
Register a callback function to receive error log messages.
__host__ cudaError_t cudaLogsUnregisterCallback(cudaLogsCallbackHandle callback)
Unregister a log message callback.
252
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Typedefs
cudaLogsCallback_t
Type of public error reporting callback functions.
6.14.1. Functions
__host__ cudaError_t cudaLogsCurrent(cudaLogIterator *iterator_out, unsigned int flags)
Sets log iterator to point to the end of log buffer, where the next message would be written.
Parameters
▶ iterator_out - - Location to store an iterator to the current tail of the logs
▶ flags - - Reserved for future use, must be 0
Returns
cudaSuccess, cudaErrorInvalidValue,
__host__ cudaError_t cudaLogsDumpToFile(cudaLogIterator *iterator, const char *pathToFile,
unsigned int flags)
Dump accumulated driver logs into a file.
Logs generated by the driver are stored in an internal buffer and can be copied out using this API.
This API dumps all driver logs starting from iterator into pathToFile provided.
Note: iterator is auto-advancing. Dumping logs will update the value of iterator to receive
the next generated log.
Note: The driver reserves limited memory for storing logs. The oldest logs may be overwritten
and become unrecoverable. An indication will appear in the destination outupt if the logs have
been truncated. Call dump after each failed API to mitigate this risk.
Parameters
▶ iterator - - Optional auto-advancing iterator specifying the starting log to
read. NULL value dumps all logs.
▶ pathToFile - - Path to output file for dumping logs
▶ flags - - Reserved for future use, must be 0
Returns
cudaSuccess, cudaErrorInvalidValue,
__host__ cudaError_t cudaLogsDumpToMemory(cudaLogIterator *iterator, char *buffer, size_t *size,
unsigned int flags)
Dump accumulated driver logs into a buffer.
Logs generated by the driver are stored in an internal buffer and can be copied out using this
API. This API dumps driver logs from iterator into buffer up to the size specified in *size.
6.14. Error Log Management Functions
253
CUDA Runtime API Reference Manual, Release 13.5
The driver will always null terminate the buffer but there will not be a null character between log
entries, only a newline \n. The driver will then return the actual number of bytes written in *size,
excluding the null terminator. If there are no messages to dump, *size will be set to 0 and the
function will return ::CUDA_SUCCESS. If the provided buffer is not large enough to hold any
messages, *size will be set to 0 and the function will return ::CUDA_ERROR_INVALID_VALUE.
Note: iterator is auto-advancing. Dumping logs will update the value of iterator to receive
the next generated log.
Note: The driver reserves limited memory for storing logs. The maximum size of the buffer is
25600 bytes. The oldest logs may be overwritten and become unrecoverable. An indication will
appear in the destination outupt if the logs have been truncated. Call dump after each failed API
to mitigate this risk.
Note: If the provided value in *size is not large enough to hold all buffered messages, a message
will be added at the head of the buffer indicating this. The driver then computes the number of
messages it is able to store in buffer and writes it out. The final message in buffer will always
be the most recent log message as of when the API is called.
Parameters
▶ iterator - - Optional auto-advancing iterator specifying the starting log to
read. NULL value dumps all logs.
▶ buffer - - Pointer to dump logs
▶ size - - See description
▶ flags - - Reserved for future use, must be 0
Returns
cudaSuccess, cudaErrorInvalidValue,
__host__ cudaError_t cudaLogsRegisterCallback(cudaLogsCallback_t callbackFunc, void
*userData, cudaLogsCallbackHandle
*callback_out)
Register a callback function to receive error log messages.
Parameters
▶ callbackFunc - - The function to register as a callback
▶ userData - - A generic pointer to user data. This is passed into the callback
function.
▶ callback_out - - Optional location to store the callback handle after it is reg-
istered
Returns
cudaSuccess, cudaErrorInvalidValue,
254
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaLogsUnregisterCallback(cudaLogsCallbackHandle callback)
Unregister a log message callback.
Parameters
callback - - The callback instance to unregister from receiving log messages
Returns
cudaSuccess, cudaErrorInvalidValue,
6.14.2. Typedefs
void(__stdcall * cudaLogsCallback_t )(void *data, cudaLogLevel logLevel,
char *message, size_t length)
Type of public error reporting callback functions.
Param data
User parameter provided at registration
Param logLevel
Severity level of the log message
Param message
Error log message being reported
Param length
Length of the message in bytes
6.15. Event Management
This section describes the event management functions of the CUDA runtime application program-
ming interface.
Functions
__host__ cudaError_t cudaEventCreate(cudaEvent_t *event)
Creates an event object.
__host__ cudaError_t cudaEventCreateWithFlags(cudaEvent_t *event, unsigned int flags)
Creates an event object with the specified flags.
__host__ cudaError_t cudaEventDestroy(cudaEvent_t event)
Destroys an event object.
__host__ cudaError_t cudaEventElapsedTime(float *ms, cudaEvent_t start, cudaEvent_t end)
Computes the elapsed time between events.
__host__ cudaError_t cudaEventQuery(cudaEvent_t event)
Queries an event's status.
__host__ cudaError_t cudaEventRecord(cudaEvent_t event, cudaStream_t stream=0)
Records an event.
6.15. Event Management
255
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaEventRecordWithFlags(cudaEvent_t event, cudaStream_t stream=0, un-
signed int flags=0)
Records an event.
__host__ cudaError_t cudaEventSynchronize(cudaEvent_t event)
Waits for an event to complete.
6.15.1. Functions
__host__ cudaError_t cudaEventCreate(cudaEvent_t *event)
Creates an event object.
Creates an event object for the current device using cudaEventDefault.
See also:
cudaEventCreate (C++ API), cudaEventCreateWithFlags, cudaEventRecord, cudaEventQuery,
cudaEventSynchronize,
cudaEventDestroy,
cudaEventElapsedTime,
cudaStreamWaitEvent,
::cuEventCreate
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
event - - Newly created event
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorLaunchFailure, cudaErrorMemoryAllo-
cation
__host__ cudaError_t cudaEventCreateWithFlags(cudaEvent_t *event, unsigned int flags)
Creates an event object with the specified flags.
Creates an event object for the current device with the specified flags. Valid flags include:
▶ cudaEventDefault: Default event creation flag.
▶ cudaEventBlockingSync: Specifies that event should use blocking synchronization. A host
thread that uses cudaEventSynchronize() to wait on an event created with this flag will block
until the event actually completes.
256
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ cudaEventDisableTiming: Specifies that the created event does not need to record timing
data. Events created with this flag specified and the cudaEventBlockingSync flag not spec-
ified will provide the best performance when used with cudaStreamWaitEvent() and cud-
aEventQuery().
▶ cudaEventInterprocess: Specifies that the created event may be used as an interprocess
event by cudaIpcGetEventHandle(). cudaEventInterprocess must be specified along with cu-
daEventDisableTiming.
See also:
cudaEventCreate (C API), cudaEventSynchronize, cudaEventDestroy, cudaEventElapsedTime, cud-
aStreamWaitEvent, ::cuEventCreate
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
▶ event - - Newly created event
▶ flags - - Flags for new event
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorLaunchFailure, cudaErrorMemoryAllo-
cation
__host__ cudaError_t cudaEventDestroy(cudaEvent_t event)
Destroys an event object.
Destroys the event specified by event.
An event may be destroyed before it is complete (i.e., while cudaEventQuery() would return cudaEr-
rorNotReady). In this case, the call does not block on completion of the event, and any associated
resources will automatically be released asynchronously at completion.
See also:
cudaEventCreate (C API), cudaEventCreateWithFlags, cudaEventQuery, cudaEventSynchronize, cu-
daEventRecord, cudaEventElapsedTime, ::cuEventDestroy
Note: Note that this function may also return error codes from previous, asynchronous launches.
6.15. Event Management
257
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.
Note: Use of the handle after this call is undefined behavior.
Note: Returns cudaErrorInvalidResourceHandle in the event of being passed NULL as the input
event.
Parameters
event - - Event to destroy
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle, cudaError-
LaunchFailure
__host__ cudaError_t cudaEventElapsedTime(float *ms, cudaEvent_t start, cudaEvent_t end)
Computes the elapsed time between events.
Computes the elapsed time between two events (in milliseconds with a resolution of around 0.5
microseconds). Note this API is not guaranteed to return the latest errors for pending work. As
such this API is intended to serve as a elapsed time calculation only and polling for completion
on the events to be compared should be done with cudaEventQuery instead.
If either event was last recorded in a non-NULL stream, the resulting time may be greater than ex-
pected (even if both used the same stream handle). This happens because the cudaEventRecord()
operation takes place asynchronously and there is no guarantee that the measured latency is
actually just between the two events. Any number of other different stream operations could
execute in between the two measured events, thus altering the timing in a significant way.
If cudaEventRecord() has not been called on either event, then cudaErrorInvalidResourceHandle is
returned. If cudaEventRecord() has been called on both events but one or both of them has not
yet been completed (that is, cudaEventQuery() would return cudaErrorNotReady on at least one
of the events), cudaErrorNotReady is returned. If either event was created with the cudaEvent-
DisableTiming flag, then this function will return cudaErrorInvalidResourceHandle.
See also:
cudaEventCreate (C API), cudaEventCreateWithFlags, cudaEventQuery, cudaEventSynchronize, cu-
daEventDestroy, cudaEventRecord, ::cuEventElapsedTime
Note: Note that this function may also return error codes from previous, asynchronous launches.
258
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.
Note: Returns cudaErrorInvalidResourceHandle in the event of being passed NULL as the input
event.
Parameters
▶ ms - - Time between start and end in ms
▶ start - - Starting event
▶ end - - Ending event
Returns
cudaSuccess, cudaErrorNotReady, cudaErrorInvalidValue, cudaErrorInvalidResource-
Handle, cudaErrorLaunchFailure, cudaErrorUnknown
__host__ cudaError_t cudaEventQuery(cudaEvent_t event)
Queries an event’s status.
Queries the status of all work currently captured by event. See cudaEventRecord() for details on
what is captured by an event.
Returns cudaSuccess if all captured work has been completed, or cudaErrorNotReady if any cap-
tured work is incomplete.
For the purposes of Unified Memory, a return value of cudaSuccess is equivalent to having called
cudaEventSynchronize().
See also:
cudaEventCreate (C API), cudaEventCreateWithFlags, cudaEventRecord, cudaEventSynchronize,
cudaEventDestroy, cudaEventElapsedTime, ::cuEventQuery
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.15. Event Management
259
CUDA Runtime API Reference Manual, Release 13.5
such case.
Note: Returns cudaErrorInvalidResourceHandle in the event of being passed NULL as the input
event.
Parameters
event - - Event to query
Returns
cudaSuccess, cudaErrorNotReady, cudaErrorInvalidValue, cudaErrorInvalidResource-
Handle, cudaErrorLaunchFailure
__host__ cudaError_t cudaEventRecord(cudaEvent_t event, cudaStream_t stream = 0)
Records an event.
Captures in event the contents of stream at the time of this call. event and stream must be
on the same CUDA context. Calls such as cudaEventQuery() or cudaStreamWaitEvent() will then
examine or wait for completion of the work that was captured. Uses of stream after this call do
not modify event. See note on default stream behavior for what is captured in the default case.
cudaEventRecord() can be called multiple times on the same event and will overwrite the previ-
ously captured state. Other APIs such as cudaStreamWaitEvent() use the most recently captured
state at the time of the API call, and are not affected by later calls to cudaEventRecord(). Before
the first call to cudaEventRecord(), an event represents an empty set of work, so for example
cudaEventQuery() would return cudaSuccess.
See also:
cudaEventCreate (C API), cudaEventCreateWithFlags, cudaEventQuery, cudaEventSynchronize,
cudaEventDestroy, cudaEventElapsedTime, cudaStreamWaitEvent, cudaEventRecordWithFlags,
::cuEventRecord
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: Returns cudaErrorInvalidResourceHandle in the event of being passed NULL as the input
event.
260
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Parameters
▶ event - - Event to record
▶ stream - - Stream in which to record event
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle, cudaError-
LaunchFailure
__host__ cudaError_t cudaEventRecordWithFlags(cudaEvent_t event, cudaStream_t stream = 0,
unsigned int flags = 0)
Records an event.
Captures in event the contents of stream at the time of this call. event and stream must be
on the same CUDA context. Calls such as cudaEventQuery() or cudaStreamWaitEvent() will then
examine or wait for completion of the work that was captured. Uses of stream after this call do
not modify event. See note on default stream behavior for what is captured in the default case.
cudaEventRecordWithFlags() can be called multiple times on the same event and will overwrite
the previously captured state. Other APIs such as cudaStreamWaitEvent() use the most recently
captured state at the time of the API call, and are not affected by later calls to cudaEventRecord-
WithFlags(). Before the first call to cudaEventRecordWithFlags(), an event represents an empty
set of work, so for example cudaEventQuery() would return cudaSuccess.
flags include:
▶ cudaEventRecordDefault: Default event creation flag.
▶ cudaEventRecordExternal: Event is captured in the graph as an external event node when
performing stream capture.
See also:
cudaEventCreate (C API), cudaEventCreateWithFlags, cudaEventQuery, cudaEventSynchronize,
cudaEventDestroy, cudaEventElapsedTime, cudaStreamWaitEvent, cudaEventRecord, ::cuEven-
tRecord,
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.
6.15. Event Management
261
CUDA Runtime API Reference Manual, Release 13.5
Note: Returns cudaErrorInvalidResourceHandle in the event of being passed NULL as the input
event.
Parameters
▶ event - - Event to record
▶ stream - - Stream in which to record event
▶ flags - - Parameters for the operation(See above)
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle, cudaError-
LaunchFailure
__host__ cudaError_t cudaEventSynchronize(cudaEvent_t event)
Waits for an event to complete.
Waits until the completion of all work currently captured in event. See cudaEventRecord() for
details on what is captured by an event.
Waiting for an event that was created with the cudaEventBlockingSync flag will cause the call-
ing CPU thread to block until the event has been completed by the device. If the cudaEvent-
BlockingSync flag has not been set, then the CPU thread will busy-wait until the event has been
completed by the device.
See also:
cudaEventCreate (C API), cudaEventCreateWithFlags, cudaEventRecord, cudaEventQuery, cud-
aEventDestroy, cudaEventElapsedTime, ::cuEventSynchronize
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: Returns cudaErrorInvalidResourceHandle in the event of being passed NULL as the input
event.
Parameters
event - - Event to wait for
262
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidResourceHandle, cudaError-
LaunchFailure
6.16. Execution Context Management
This section describes the execution context management functions of the CUDA runtime application
programming interface.
6.16.1. Overview
A CUDA execution context cudaExecutionContext_t serves as an abstraction for the contexts exposed
by the CUDA Runtime, specifically green contexts and the primary context, and provides a unified
programming model and API interface for contexts in the Runtime.
There are two primary ways today to obtain an execution context:
▶ cudaDeviceGetExecutionCtx: Returns the execution context that corresponds to the primary
context of the specified device.
▶ cudaGreenCtxCreate: Creates a green context with the specified resources and returns an exe-
cution context.
Once you have an execution context at hand, you can perform context-level operations via the CUDA
Runtime APIs. This includes:
▶ Submitting work via streams created with cudaExecutionCtxStreamCreate.
▶ Querying context via cudaExecutionCtxGetDevResource, cudaExecutionCtxGetDevice, etc.
▶ Synchronizing and tracking context-level operations via cudaExecutionCtxSynchronize, cudaExe-
cutionCtxRecordEvent, cudaExecutionCtxWaitEvent.
▶ Performing context-level graph node operations via cudaGraphAddNode by specifying the con-
text in nodeParams. Note that individual node creation APIs, such as cudaGraphAddKernelNode,
do not support specifying an execution context.
Note: The above APIs take in an explicit cudaExecutionContext_t handle and ignores the context that
is current to the calling thread. This enables explicit context-based programming without relying on
thread-local state. If no context is specified, the APIs return cudaErrorInvalidValue.
Note: Developers should treat cudaExecutionContext_t as an opaque handle and avoid assumptions
about its underlying representation. The CUDA Runtime does not provide a way to convert this handle
into driver-level contexts, such as ::CUcontext or ::CUgreenCtx.
6.16. Execution Context Management
263
CUDA Runtime API Reference Manual, Release 13.5
6.16.2. Lifetime of CUDA Resources
The lifetime of CUDA resources (memory, streams, events, modules, etc) is not tied to the lifetime of
the execution context. Their lifetime is tied to the device against which they were created. As such,
usage of cudaDeviceReset() should be avoided to persist the lifetime of these resources.
6.16.3. APIs Operating on Current Context
The CUDA runtime does not provide a way to set an execution context as current. Since, the majority
of the runtime APIs operate on the current context, we document below how the developer can work
with these APIs.
6.16.3.1 APIs Operating on Device Resources
To work with these APIs (for example, cudaMalloc, cudaEventCreate, etc), developers are expected to
call cudaSetDevice() prior to invoking them. Doing so does not impact functional correctness as these
APIs operate on resources that are device-wide. If users have a context handle at hand, they can get
the device handle from the context handle using cudaExecutionCtxGetDevice().
6.16.3.2 APIs Operating on Context Resources
These APIs (for example, cudaLaunchKernel, cudaMemcpyAsync, cudaMemsetAsync, etc) take in a
stream and resources are inferred from the context bound to the stream at creation. See cudaEx-
ecutionCtxStreamCreate for more details. Developers are expected to use the stream-based APIs for
context awareness and always pass an explicit stream handle to ensure context-awareness, and avoid
reliance on the default NULL stream, which implicitly binds to the current context.
6.16.4. Green Contexts
Green contexts are a lightweight alternative to traditional contexts, that can be used to select a sub-
set of device resources. This allows the developer to, for example, select SMs from distinct spatial
partitions of the GPU and target them via CUDA stream operations, kernel launches, etc.
Here are the broad initial steps to follow to get started:
▶ (1) Start with an initial set of resources. For SM resources, they can be fetched via cudaDe-
viceGetDevResource. In case of workqueues, a new configuration can be used or an existing one
queried via the cudaDeviceGetDevResource API.
▶ (2) Modify these resources by either partitioning them (in case of SMs) or changing the con-
figuration (in case of workqueues). To partition SMs, we recommend cudaDevSmResourceSplit.
Changing the workqueue configuration can be done directly in place.
▶ (3) Finalize the specification of resources by creating a descriptor via cudaDevResourceGenerat-
eDesc.
▶ (4) Create a green context via cudaGreenCtxCreate. This provisions the resource, such as
workqueues (until this step it was only a configuration specification).
▶ (5) Create a stream via cudaExecutionCtxStreamCreate, and use it throughout your application.
264
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
SMs
There are two possible partition operations - with cudaDevSmResourceSplitByCount the partitions cre-
ated have to follow default SM count granularity requirements, so it will often be rounded up and
aligned to a default value. On the other hand, cudaDevSmResourceSplit is explicit and allows for cre-
ation of non-equal groups. It will not round up automatically - instead it is the developer’s responsibility
to query and set the correct values. These requirements can be queried with cudaDeviceGetDevRe-
source to determine the alignment granularity (sm.smCoscheduledAlignment). A general guideline on
the default values for each compute architecture:
▶ On Compute Architecture 7.X, 8.X, and all Tegra SoC:
▶ The smCount must be a multiple of 2.
▶ The alignment (and default value of coscheduledSmCount) is 2.
▶ On Compute Architecture 9.0+:
▶ The smCount must be a multiple of 8, or coscheduledSmCount if provided.
▶ The alignment (and default value of coscheduledSmCount) is 8. While the maximum value
for coscheduled SM count is 32 on all Compute Architecture 9.0+, it’s recommended to fol-
low cluster size requirements. The portable cluster size and the max cluster size should be
used in order to benefit from this co-scheduling.
Workqueues
For cudaDevResourceTypeWorkqueueConfig, the resource specifies the expected maximum num-
ber of concurrent stream-ordered workloads via the wqConcurrencyLimit field. The sharingScope
field determines how workqueue resources are shared:
▶ cudaDevWorkqueueConfigScopeDeviceCtx: Use all shared workqueue resources across all
contexts (default driver behavior).
▶ cudaDevWorkqueueConfigScopeGreenCtxBalanced: When possible, use non-overlapping
workqueue resources with other balanced green contexts.
The maximum concurrency limit depends on ::CUDA_DEVICE_MAX_CONNECTIONS and can be queried
from the device via cudaDeviceGetDevResource. Configurations may exceed this concurrency limit, but
the driver will not guarantee that work submission remains non-overlapping.
For cudaDevResourceTypeWorkqueue, the resource represents a pre-existing workqueue that can
be retrieved from existing execution contexts. This allows reusing workqueue resources across differ-
ent execution contexts.
On Concurrency
Even if the green contexts have disjoint SM partitions, it is not guaranteed that the kernels launched
in them will run concurrently or have forward progress guarantees. This is due to other resources
that could cause a dependency. Using a combination of disjoint SMs and cudaDevWorkqueueCon-
figScopeGreenCtxBalanced workqueue configurations can provide the best chance of avoiding in-
terference. More resources will be added in the future to provide stronger guarantees.
Additionally, there are two known scenarios, where its possible for the workload to run on more SMs
than was provisioned (but never less).
▶ On Volta+ MPS: When CUDA_MPS_ACTIVE_THREAD_PERCENTAGE is used, the set of SMs that are
used for running kernels can be scaled up to the value of SMs used for the MPS client.
▶ On Compute Architecture 9.x: When a module with dynamic parallelism (CDP) is loaded, all future
kernels running under green contexts may use and share an additional set of 2 SMs.
6.16. Execution Context Management
265
CUDA Runtime API Reference Manual, Release 13.5
Memory Copy Operations
Green context restrictions apply to memory copy operations only when the copy is performed using a
green context. For cross-device copies, green context restrictions may not be applied.
Functions
__host__ cudaError_t cudaDevResourceGenerateDesc(cudaDevResourceDesc_t *phDesc, cudaDe-
vResource *resources, unsigned int nbResources)
Generate a resource descriptor.
__host__ cudaError_t cudaDevSmResourceSplit(cudaDevResource *result, unsigned int nbGroups,
const cudaDevResource *input, cudaDevResource *remainder, unsigned int flags, cudaDevSm-
ResourceGroupParams *groupParams)
Splits a cudaDevResourceTypeSm resource into structured groups.
__host__ cudaError_t cudaDevSmResourceSplitByCount(cudaDevResource *result, unsigned int
*nbGroups, const cudaDevResource *input, cudaDevResource *remaining, unsigned int flags,
unsigned int minCount)
Splits cudaDevResourceTypeSm resources.
__host__ cudaError_t cudaDeviceGetDevResource(int device, cudaDevResource *resource, enum cu-
daDevResourceType type)
Get device resources.
__host__ cudaError_t cudaDeviceGetExecutionCtx(cudaExecutionContext_t *ctx, int device)
Returns the execution context for a device.
__host__ cudaError_t cudaExecutionCtxDestroy(cudaExecutionContext_t ctx)
Destroy a execution context.
__host__ cudaError_t cudaExecutionCtxGetDevResource(cudaExecutionContext_t ctx, cudaDevRe-
source *resource, enum cudaDevResourceType type)
Get context resources.
__host__ cudaError_t cudaExecutionCtxGetDevice(int *device, cudaExecutionContext_t ctx)
Returns the device handle for the execution context.
__host__ cudaError_t cudaExecutionCtxGetId(cudaExecutionContext_t ctx, unsigned long long
*ctxId)
Returns the unique Id associated with the execution context supplied.
__host__ cudaError_t cudaExecutionCtxRecordEvent(cudaExecutionContext_t ctx, cudaEvent_t
event)
Records an event for the specified execution context.
__host__ cudaError_t cudaExecutionCtxStreamCreate(cudaStream_t *phStream, cudaExecution-
Context_t ctx, unsigned int flags, int priority)
Creates a stream and initializes it for the given execution context.
__host__ cudaError_t cudaExecutionCtxSynchronize(cudaExecutionContext_t ctx)
Block for the specified execution context's tasks to complete.
__host__ cudaError_t cudaExecutionCtxWaitEvent(cudaExecutionContext_t ctx, cudaEvent_t
event)
Make an execution context wait on an event.
__host__
cudaError_t
cudaGreenCtxCreate(cudaExecutionContext_t
*phCtx,
cudaDevRe-
sourceDesc_t desc, int device, unsigned int flags)
Creates a green context with a specified set of resources.
266
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaStreamGetDevResource(cudaStream_t hStream, cudaDevResource *re-
source, enum cudaDevResourceType type)
Get stream resources.
6.16.5. Functions
__host__ cudaError_t cudaDevResourceGenerateDesc(cudaDevResourceDesc_t *phDesc,
cudaDevResource *resources, unsigned int
nbResources)
Generate a resource descriptor.
Generates a single resource descriptor with the set of resources specified in resources. The
generated resource descriptor is necessary for the creation of green contexts via the cuda-
GreenCtxCreate API. Resources of the same type can be passed in, provided they meet the re-
quirements as noted below.
A successful API call must have:
▶ A valid output pointer for the phDesc descriptor as well as a valid array of resources point-
ers, with the array size passed in nbResources. If multiple resources are provided in re-
sources, the device they came from must be the same, otherwise cudaErrorInvalidResource-
Configuration is returned. If multiple resources are provided in resources and they are of
type cudaDevResourceTypeSm, they must be outputs (whether result or remaining) from
the same split API instance and have the same smCoscheduledAlignment values, otherwise
cudaErrorInvalidResourceConfiguration is returned.
Note: The API is not supported on 32-bit platforms.
See also:
::cuDevResourceGenerateDesc, cudaDeviceGetDevResource, cudaExecutionCtxGetDevResource,
cudaDevSmResourceSplit, cudaGreenCtxCreate
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
▶ phDesc - - Output descriptor
▶ resources - - Array of resources to be included in the descriptor
▶ nbResources - - Number of resources passed in resources
Returns
cudaSuccess,
cudaErrorInvalidValue,
cudaErrorNotPermitted,
cudaErrorIn-
validResourceType,
cudaErrorInvalidResourceConfiguration,
cudaErrorNotSup-
ported, ::cudaErrorOutOfMemory, cudaErrorCudartUnloading, cudaErrorInitializa-
tionError
6.16. Execution Context Management
267
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaDevSmResourceSplit(cudaDevResource *result, unsigned int nbGroups,
const cudaDevResource *input, cudaDevResource
*remainder, unsigned int flags,
cudaDevSmResourceGroupParams
*groupParams)
Splits a cudaDevResourceTypeSm resource into structured groups.
This API will split a resource of cudaDevResourceTypeSm into nbGroups structured device re-
source groups (the result array), as well as an optional remainder, according to a set of re-
quirements specified in the groupParams array. The term “structured” is a trait that specifies
the result has SMs that are co-scheduled together. This co-scheduling can be specified via the
coscheduledSmCount field of the groupParams structure, while the smCount will specify how
many SMs are required in total for that result. The remainder is always “unstructured”, it does not
have any set guarantees with respect to co-scheduling and those properties will need to either
be queried via the occupancy set of APIs or further split into structured groups by this API.
The API has a discovery mode for use cases where it is difficult to know ahead of time what the
SM count should be. Discovery happens when the smCount field of a given groupParams array
entry is set to 0 - the smCount will be filled in by the API with the derived SM count according
to the provided groupParams fields and constraints. Discovery can be used with both a valid
result array and with a NULL result pointer value. The latter is useful in situations where the
smCount will end up being zero, which is an invalid value to create a result entry with, but allowed
for discovery purposes when the result is NULL.
The groupParams array is evaluated from index 0 to nbGroups - 1. For each index in the group-
Params array, the API will evaluate which SMs may be a good fit based on constraints and assign
those SMs to result. This evaluation order is important to consider when using discovery mode,
as it helps discover the remaining SMs.
For a valid call:
▶ result should point to a cudaDevResource array of size nbGroups, or alternatively, may
be NULL, if the developer wishes for only the groupParams entries to be updated
▶ input should be a valid cudaDevResourceTypeSm resource that originates from querying
the execution context, or device.
▶ The remainder group may be NULL.
▶ There are no API flags at this time, so the value passed in should be 0.
▶ A cudaDevSmResourceGroupParams array of size nbGroups. Each entry must be zero-
initialized.
▶ smCount: must be either 0 or in the range of [2,inputSmCount] where inputSmCount is
the amount of SMs the input resource has. smCount must be a multiple of 2, as well as
a multiple of coscheduledSmCount. When assigning SMs to a group (and if results are
expected by having the result parameter set), smCount cannot end up with 0 or a value
less than coscheduledSmCount otherwise cudaErrorInvalidResourceConfiguration will
be returned.
▶ coscheduledSmCount: allows grouping SMs together in order to be able to launch
clusters on Compute Architecture 9.0+. The default value may be queried from the de-
vice’s cudaDevResourceTypeSm resource (8 on Compute Architecture 9.0+ and 2 other-
wise). The maximum is 32 on Compute Architecture 9.0+ and 2 otherwise.
▶ preferredCoscheduledSmCount: Attempts to merge coscheduledSmCount groups
into larger groups, in order to make use of preferredClusterDimensions on Com-
pute Architecture 10.0+. The default value is set to coscheduledSmCount.
268
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ flags:
▶ cudaDevSmResourceGroupBackfill: Treats constraints as a hint, ignoring them
if necessary to reach the requested smCount. Lets smCount be a non-multiple of
coscheduledSmCount, filling the difference between SM count and already as-
signed co-scheduled groupings with other SMs. This lets any resulting group be-
have similar to the remainder group for example. When used with cudaDevSmRe-
sourceGroupLocalityDomainId, backfill fills up to the requested smCount using
the target locality domain first, then SMs not attributed to any locality domain, then
SMs from other locality domains. If no SMs can be found in the requested local-
ity domain, cudaErrorInvalidResourceConfiguration is returned. When used with cu-
daDevSmResourceGroupLocalityDomainSupplementalSms, backfill follows the
same behavior after first consuming all SMs from the target locality domain.
▶ cudaDevSmResourceGroupLocalityDomainId: Specifies that the SM partition
should be localized to the specified localityDomainId.
▶ cudaDevSmResourceGroupLocalityDomainSupplementalSms:
Mod-
ifier
to
cudaDevSmResourceGroupLocalityDomainId
which
allows
selection of SMs in the locality domain exceeding
the
::cudaDe-
viceAttr::cudaDevAttrLocalityDomainMultiprocessorCount.
▶ localityDomainId: Specifies the locality domain that the partitioned SMs must be
located on. Only valid when cudaDevSmResourceGroupLocalityDomainId is set in
flags. The special value cudaDevSmResourceGroupLocalityDomainIdAny specifies
that the partitioned SMs must be selected from the union of all available locality do-
mains in the input SM resource.
Example params and their effect:
A groupParams array element is defined in the following order:
{ .smCount, .coscheduledSmCount, .preferredCoscheduledSmCount, .flags, \∕\* .
↪→reserved \*\∕ }
∕∕ Example 1
∕∕ Will discover how many SMs there are, that are co-scheduled in groups of
↪→smCoscheduledAlignment.
∕∕ The rest is placed in the optional remainder.
cudaDevSmResourceGroupParams params { 0, 0, 0, 0 };
∕∕ Example 2
∕∕ Assuming the device has 10+ SMs, the result will have 10 SMs that are co-
↪→scheduled in groups of 2 SMs.
∕∕ The rest is placed in the optional remainder.
cudaDevSmResourceGroupParams params { 10, 2, 0, 0};
∕∕ Setting the coscheduledSmCount to 2 guarantees that we can always have a valid
↪→result
∕∕ as long as the SM count is less than or equal to the input resource SM count.
∕∕ Example 3
∕∕ A single piece is split-off, but instead of assigning the rest to the remainder,
↪→a second group contains everything else
∕∕ This assumes the device has 10+ SMs (8 of which are coscheduled in groups of 4),
∕∕ otherwise the second group could end up with 0 SMs, which is not allowed.
cudaDevSmResourceGroupParams params[] = {
(continues on next page)
6.16. Execution Context Management
269
CUDA Runtime API Reference Manual, Release 13.5
(continued from previous page)
{8, 4, 0, 0},
{0, 2, 0, cudaDevSmResourceGroupBackfill},
};
The difference between a catch-all param group as the last entry and the remainder is in two
aspects:
▶ The remainder may be NULL / _TYPE_INVALID (if there are no SMs remaining), while a result
group must always be valid.
▶ The remainder does not have a structure, while the result group will always need to adhere
to a structure of coscheduledSmCount (even if its just 2), and therefore must always have
enough coscheduled SMs to cover that requirement (even with the cudaDevSmResource-
GroupBackfill flag enabled).
Splitting an input into N groups, can be accomplished by repeatedly splitting off 1 group and re-
splitting the remainder (a bisect operation). However, it’s recommended to accomplish this with
a single call wherever possible.
See also:
::cuDevSmResourceSplit, cudaDeviceGetDevResource, cudaExecutionCtxGetDevResource, cud-
aDevResourceGenerateDesc
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
▶ result - - Output array of cudaDevResource resources. Can be NULL, along-
side an smCount of 0, for discovery purpose.
▶ nbGroups - - Specifies the number of groups in result and groupParams
▶ input - - Input SM resource to be split. Must be a valid cudaDevResource-
TypeSm resource.
▶ remainder - - If splitting the input resource leaves any SMs, the remainder is
placed in here.
▶ flags - - Flags specifying how the API should behave. The value should be 0 for
now.
▶ groupParams - - Description of how the SMs should be split and assigned to
the corresponding result entry.
Returns
cudaSuccess,
cudaErrorInvalidValue,
cudaErrorNotPermitted,
cudaErrorIn-
validResourceType,
cudaErrorInvalidResourceConfiguration,
cudaErrorNotSup-
ported, cudaErrorCudartUnloading, cudaErrorInitializationError
270
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaDevSmResourceSplitByCount(cudaDevResource *result, unsigned int
*nbGroups, const cudaDevResource
*input, cudaDevResource *remaining,
unsigned int flags, unsigned int
minCount)
Splits cudaDevResourceTypeSm resources.
Splits cudaDevResourceTypeSm resources into nbGroups, adhering to the minimum SM count
specified in minCount and the usage flags in flags. If result is NULL, the API simulates a split
and provides the amount of groups that would be created in nbGroups. Otherwise, nbGroups
must point to the amount of elements in result and on return, the API will overwrite nbGroups
with the amount actually created. The groups are written to the array in result. nbGroups can
be less than the total amount if a smaller number of groups is needed.
This API is used to spatially partition the input resource. The input resource needs to come from
one of cudaDeviceGetDevResource, or cudaExecutionCtxGetDevResource. A limitation of the API
is that the output results cannot be split again without first creating a descriptor and a green
context with that descriptor.
When creating the groups, the API will take into account the performance and functional charac-
teristics of the input resource, and guarantee a split that will create a disjoint set of symmetrical
partitions. This may lead to fewer groups created than purely dividing the total SM count by
the minCount due to cluster requirements or alignment and granularity requirements for the
minCount. These requirements can be queried with cudaDeviceGetDevResource, or cudaExecu-
tionCtxGetDevResource for cudaDevResourceTypeSm, using the minSmPartitionSize and sm-
CoscheduledAlignment fields to determine minimum partition size and alignment granularity,
respectively.
The remainder set does not have the same functional or performance guarantees as the groups
in result. Its use should be carefully planned and future partitions of the remainder set are
discouraged.
The following flags are supported:
▶ cudaDevSmResourceSplitIgnoreSmCoscheduling : Lower the minimum SM count and
alignment, and treat each SM independent of its hierarchy. This allows more fine grained
partitions but at the cost of advanced features (such as large clusters on compute capability
9.0+).
▶ cudaDevSmResourceSplitMaxPotentialClusterSize : Compute Capability 9.0+ only.
Attempt to create groups that may allow for maximally sized thread clusters. This can be
queried post green context creation using cudaOccupancyMaxPotentialClusterSize.
A successful API call must either have:
▶ A valid array of result pointers of size passed in nbGroups, with input of type cudaDe-
vResourceTypeSm. Value of minCount must be between 0 and the SM count specified in
input. remaining may be NULL.
▶ NULL passed in for result, with a valid integer pointer in nbGroups and input of type
cudaDevResourceTypeSm. Value of minCount must be between 0 and the SM count spec-
ified in input. remaining may be NULL. This queries the number of groups that would be
created by the API.
Note: The API is not supported on 32-bit platforms.
6.16. Execution Context Management
271
CUDA Runtime API Reference Manual, Release 13.5
See also:
::cuDevSmResourceSplitByCount,
cudaDeviceGetDevResource,
cudaExecutionCtxGetDevRe-
source, cudaDevResourceGenerateDesc
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
▶ result - - Output array of cudaDevResource resources. Can be NULL to query
the number of groups.
▶ nbGroups - - This is a pointer, specifying the number of groups that would be
or should be created as described below.
▶ input - - Input SM resource to be split. Must be a valid cudaDevSmResource
resource.
▶ remaining - - If the input resource cannot be cleanly split among nbGroups,
the remaining is placed in here. Can be ommitted (NULL) if the user does not
need the remaining set.
▶ flags - - Flags specifying how these partitions are used or which constraints
to abide by when splitting the input. Zero is valid for default behavior.
▶ minCount - - Minimum number of SMs required
Returns
cudaSuccess,
cudaErrorInvalidValue,
cudaErrorNotPermitted,
cudaErrorIn-
validResourceType,
cudaErrorInvalidResourceConfiguration,
cudaErrorNotSup-
ported, cudaErrorCudartUnloading, cudaErrorInitializationError
__host__ cudaError_t cudaDeviceGetDevResource(int device, cudaDevResource *resource, enum
cudaDevResourceType type)
Get device resources.
Get the type resources available to the device. This may often be the starting point for further
partitioning or configuring of resources.
Note: The API is not supported on 32-bit platforms.
See also:
::cuDeviceGetDevResource, cudaExecutionCtxGetDevResource, cudaDevSmResourceSplit, cud-
aDevResourceGenerateDesc
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
272
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ device - - Device to get resource for
▶ resource - - Output pointer to a cudaDevResource structure
▶ type - - Type of resource to retrieve
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorNotPermitted, cudaErrorInvalidDe-
vice, cudaErrorInvalidResourceType, cudaErrorNotSupported, cudaErrorCudartUn-
loading, cudaErrorInitializationError
__host__ cudaError_t cudaDeviceGetExecutionCtx(cudaExecutionContext_t *ctx, int device)
Returns the execution context for a device.
Returns in ctx the execution context for the specified device. This is the device’s primary con-
text. The returned context can then be passed to APIs that take in a cudaExecutionContext_t
enabling explicit context-based programming without relying on thread-local state.
Passing the returned execution context to cudaExecutionCtxDestroy() is not allowed and will re-
sult in undefined behavior.
See also:
cudaExecutionCtxGetDevice, cudaExecutionCtxGetId
Parameters
▶ ctx - - Returns the device execution context
▶ device - - Device to get the execution context for
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidDevice
__host__ cudaError_t cudaExecutionCtxDestroy(cudaExecutionContext_t ctx)
Destroy a execution context.
Destroys the specified execution context ctx. It is the responsibility of the caller to ensure that
no API call issues using ctx while cudaExecutionCtxDestroy() is executing or subsequently.
If ctx is a green context, any resources provisioned for it (that were initially available via the
resource descriptor) are released as well.
The API does not destroy streams created via cudaExecutionCtxStreamCreate. Users are ex-
pected to destroy these streams explicitly using cudaStreamDestroy to avoid resource leaks.
Once the execution context is destroyed, any subsequent API calls involving these streams will
return cudaErrorStreamDetached with the exception of the following APIs:
▶ cudaStreamDestroy. Note this is only supported on CUDA drivers 13.1 and above.
Additionally, the API will invalidate all active captures on these streams.
Passing in a ctx that was not explicitly created via CUDA Runtime APIs is not allowed and will
result in undefined behavior.
See also:
cudaGreenCtxCreate
6.16. Execution Context Management
273
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 context parameter is required and the API ignores the context that is current to the
calling thread. This enables explicit context-based programming without relying on thread-local
state. If no context is specified, the API will return cudaErrorInvalidValue.
Parameters
ctx - - Execution context to destroy (required parameter, see note below)
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorNotPermitted, cudaErrorCudartUn-
loading, cudaErrorInitializationError
__host__ cudaError_t cudaExecutionCtxGetDevResource(cudaExecutionContext_t ctx,
cudaDevResource *resource, enum
cudaDevResourceType type)
Get context resources.
Get the type resources available to context represented by ctx.
Note: The API is not supported on 32-bit platforms.
See also:
cudaDeviceGetDevResource, cudaDevSmResourceSplit, cudaDevResourceGenerateDesc, cuda-
GreenCtxCreate
Note: Note that this function may also return error codes from previous, asynchronous launches.
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 context parameter is required and the API ignores the context that is current to the
calling thread. This enables explicit context-based programming without relying on thread-local
state. If no context is specified, the API will return cudaErrorInvalidValue.
Parameters
▶ ctx - - Execution context to get resource for (required parameter, see note be-
low)
▶ resource - - Output pointer to a cudaDevResource structure
▶ type - - Type of resource to retrieve
274
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorNotSupported, cudaErrorNotPermit-
ted, cudaErrorCudartUnloading, cudaErrorInitializationError
__host__ cudaError_t cudaExecutionCtxGetDevice(int *device, cudaExecutionContext_t ctx)
Returns the device handle for the execution context.
Returns in *device the handle of the specified execution context’s device. The execution con-
text should not be NULL.
See also:
cudaGreenCtxCreate, cudaExecutionCtxDestroy, ::cuCtxGetDevice
Note: Note that this function may also return error codes from previous, asynchronous launches.
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 context parameter is required and the API ignores the context that is current to the
calling thread. This enables explicit context-based programming without relying on thread-local
state. If no context is specified, the API will return cudaErrorInvalidValue.
Parameters
▶ device - - Returned device handle for the specified execution context
▶ ctx - - Execution context for which to obtain the device (required parameter,
see note below)
Returns
cudaSuccess, cudaErrorCudartUnloading, cudaErrorInitializationError, cudaErrorIn-
validValue, cudaErrorNotPermitted
__host__ cudaError_t cudaExecutionCtxGetId(cudaExecutionContext_t ctx, unsigned long long
*ctxId)
Returns the unique Id associated with the execution context supplied.
Returns in ctxId the unique Id which is associated with a given context. The Id is unique for the
life of the program for this instance of CUDA. The execution context should not be NULL.
See also:
cudaGreenCtxCreate, cudaExecutionCtxDestroy, cudaExecutionCtxGetDevice, ::cuCtxGetId
Note: Note that this function may also return error codes from previous, asynchronous launches.
6.16. Execution Context Management
275
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 context parameter is required and the API ignores the context that is current to the
calling thread. This enables explicit context-based programming without relying on thread-local
state. If no context is specified, the API will return cudaErrorInvalidValue.
Parameters
▶ ctx - - Context for which to obtain the Id (required parameter, see note below)
▶ ctxId - - Pointer to store the Id of the context
Returns
cudaSuccess, cudaErrorCudartUnloading, cudaErrorInitializationError, cudaErrorIn-
validValue, cudaErrorNotPermitted
__host__ cudaError_t cudaExecutionCtxRecordEvent(cudaExecutionContext_t ctx, cudaEvent_t
event)
Records an event for the specified execution context.
Captures in event all the activities of the execution context ctx at the time of this call. event
and ctx must be from the same CUDA device, otherwise ::cudaErrorInvalidHandle will be re-
turned. Calls such as cudaEventQuery() or cudaExecutionCtxWaitEvent() will then examine or wait
for completion of the work that was captured. Uses of ctx after this call do not modify event. If
the execution context passed to ctx is the device (primary) context obtained via cudaDeviceGe-
tExecutionCtx(), event will capture all the activities of the green contexts created on the device
as well.
See also:
cudaEventRecord, cudaExecutionCtxWaitEvent, ::cuCtxRecordEvent, ::cuGreenCtxRecordEvent
Note: The API will return cudaErrorStreamCaptureUnsupported if the specified execution con-
text ctx has a stream in the capture mode. In such a case, the call will invalidate all the conflicting
captures.
Note: Note that this function may also return error codes from previous, asynchronous launches.
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 context parameter is required and the API ignores the context that is current to the
calling thread. This enables explicit context-based programming without relying on thread-local
276
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
state. If no context is specified, the API will return cudaErrorInvalidValue.
Parameters
▶ ctx - - Execution context to record event for (required parameter, see note be-
low)
▶ event - - Event to record
Returns
cudaSuccess, cudaErrorCudartUnloading, cudaErrorInitializationError, ::cudaErrorIn-
validHandle, cudaErrorStreamCaptureUnsupported
__host__ cudaError_t cudaExecutionCtxStreamCreate(cudaStream_t *phStream,
cudaExecutionContext_t ctx, unsigned int
flags, int priority)
Creates a stream and initializes it for the given execution context.
The API creates a CUDA stream with the specified flags and priority, initializing it with re-
sources as defined at the time of creating the specified ctx. Additionally, the API also enables
work submitted to to the stream to be tracked under ctx.
The supported values for flags are:
▶ cudaStreamDefault: Default stream creation flag. This would be cudaStreamNonBlocking for
streams created on a green context.
▶ 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
Specifying priority 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 cudaDeviceGetStreamPrior-
ityRange. If the specified priority is outside the numerical range returned by cudaDeviceGet-
StreamPriorityRange, it will automatically be clamped to the lowest or the highest number in the
range.
See also:
cudaStreamDestroy, cudaGreenCtxCreate, cudaDeviceGetStreamPriorityRange, cudaStreamGet-
Flags, cudaStreamGetPriority, cudaStreamGetDevice, cudaStreamGetDevResource, cudaLaunchK-
ernel, cudaEventRecord, cudaStreamWaitEvent, cudaStreamQuery, cudaStreamSynchronize, cud-
aStreamAddCallback
Note: Note that this function may also return error codes from previous, asynchronous launches.
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.16. Execution Context Management
277
CUDA Runtime API Reference Manual, Release 13.5
Note: The context parameter is required and the API ignores the context that is current to the
calling thread. This enables explicit context-based programming without relying on thread-local
state. If no context is specified, the API will return cudaErrorInvalidValue.
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
▶ phStream - - Returned stream handle
▶ ctx - - Execution context to initialize the stream with (required parameter, see
note below)
▶ flags - - Flags for stream creation
▶ priority - - Stream priority
Returns
cudaSuccess,
cudaErrorInvalidValue,
cudaErrorNotPermitted,
::cudaErrorOut-
OfMemory, cudaErrorCudartUnloading, cudaErrorInitializationError
__host__ cudaError_t cudaExecutionCtxSynchronize(cudaExecutionContext_t ctx)
Block for the specified execution context’s tasks to complete.
Blocks until the specified execution context has completed all preceding requested tasks. If the
specified execution context is the device (primary) context obtained via cudaDeviceGetExecu-
tionCtx, green contexts that have been created on the device will also be synchronized.
The API returns an error if one of the preceding tasks failed.
See also:
cudaGreenCtxCreate, cudaExecutionCtxDestroy, cudaDeviceSynchronize, ::cuCtxSynchronize_v2
Note: Note that this function may also return error codes from previous, asynchronous launches.
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 context parameter is required and the API ignores the context that is current to the
calling thread. This enables explicit context-based programming without relying on thread-local
state. If no context is specified, the API will return cudaErrorInvalidValue.
Parameters
ctx - - Execution context to synchronize (required parameter, see note below)
278
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
Returns
cudaSuccess, cudaErrorCudartUnloading, cudaErrorDeviceUninitialized, cudaErrorIn-
validValue
__host__ cudaError_t cudaExecutionCtxWaitEvent(cudaExecutionContext_t ctx, cudaEvent_t
event)
Make an execution context wait on an event.
Makes all future work submitted to execution context ctx wait for all work captured in event.
The synchronization will be performed on the device and will not block the calling CPU thread.
See cudaExecutionCtxRecordEvent() for details on what is captured by an event. If the execution
context passed to ctx is the device (primary) context obtained via cudaDeviceGetExecutionCtx(),
all green contexts created on the device will wait for event as well.
See also:
cudaExecutionCtxRecordEvent, cudaStreamWaitEvent, ::cuCtxWaitEvent, ::cuGreenCtxWaitEvent
Note: event may be from a different execution context or device than ctx.
Note: The API will return cudaErrorStreamCaptureUnsupported and invalidate the capture if the
specified event event is part of an ongoing capture sequence or if the specified execution con-
text ctx has a stream in the capture mode.
Note: Note that this function may also return error codes from previous, asynchronous launches.
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 context parameter is required and the API ignores the context that is current to the
calling thread. This enables explicit context-based programming without relying on thread-local
state. If no context is specified, the API will return cudaErrorInvalidValue.
Parameters
▶ ctx - - Execution context to wait for (required parameter, see note below)
▶ event - - Event to wait on
Returns
cudaSuccess, cudaErrorCudartUnloading, cudaErrorInitializationError, ::cudaErrorIn-
validHandle, cudaErrorStreamCaptureUnsupported
__host__ cudaError_t cudaGreenCtxCreate(cudaExecutionContext_t *phCtx,
cudaDevResourceDesc_t desc, int device, unsigned int
flags)
6.16. Execution Context Management
279
CUDA Runtime API Reference Manual, Release 13.5
Creates a green context with a specified set of resources.
This API creates a green context with the resources specified in the descriptor desc and returns
it in the handle represented by phCtx.
This API retains the device’s primary context for the lifetime of the green context. The primary
context will be released when the green context is destroyed. To avoid the overhead of repeated
initialization and teardown, it is recommended to explicitly initialize the device’s primary context
ahead of time using cudaInitDevice. This ensures that the primary context remains initialized
throughout the program’s lifetime, minimizing overhead during green context creation and de-
struction.
The API does not create a default stream for the green context. Developers are expected to cre-
ate streams explicitly using cudaExecutionCtxStreamCreate to submit work to the green context.
Note: The API is not supported on 32-bit platforms.
See also:
cudaDeviceGetDevResource, cudaDevSmResourceSplit, cudaDevResourceGenerateDesc, cudaEx-
ecutionCtxGetDevResource, cudaExecutionCtxDestroy, cudaInitDevice, cudaExecutionCtxStream-
Create
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
▶ phCtx - - Pointer for the output handle to the green context
▶ desc - - Descriptor generated via cudaDevResourceGenerateDesc which con-
tains the set of resources to be used
▶ device - - Device on which to create the green context.
▶ flags - - Green context creation flags. Must be 0, currently reserved for future
use.
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidDevice, cudaErrorNotPermit-
ted, cudaErrorNotSupported, ::cudaErrorOutOfMemory, cudaErrorCudartUnloading,
cudaErrorInitializationError
__host__ cudaError_t cudaStreamGetDevResource(cudaStream_t hStream, cudaDevResource
*resource, enum cudaDevResourceType type)
Get stream resources.
Get the type resources available to the hStream and store them in resource.
Note: The API will return cudaErrorInvalidResourceType is type is cudaDevResourceType-
WorkqueueConfig or cudaDevResourceTypeWorkqueue.
280
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
See also:
cudaGreenCtxCreate, cudaExecutionCtxStreamCreate, cudaStreamCreate, cudaDevSmResource-
Split, cudaDevResourceGenerateDesc, ::cuStreamGetDevResource
Note: Note that this function may also return error codes from previous, asynchronous launches.
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 - - Stream to get resource for
▶ resource - - Output pointer to a cudaDevResource structure
▶ type - - Type of resource to retrieve
Returns
cudaSuccess, cudaErrorCudartUnloading, cudaErrorInitializationError, cudaErrorDe-
viceUninitialized, cudaErrorInvalidResourceType, cudaErrorInvalidValue, ::cudaError-
InvalidHandle, cudaErrorNotPermitted, cudaErrorCallRequiresNewerDriver,
6.17. Execution Control
This section describes the execution control functions of the CUDA runtime application programming
interface.
Some functions have overloaded C++ API template versions documented separately in the C++ API
Routines module.
Functions
__host__ cudaError_t cudaFuncGetAttributes(struct cudaFuncAttributes *attr, const void *func)
Find out attributes for a given function.
__host__ cudaError_t cudaFuncGetName(const char **name, const void *func)
Returns the function name for a device entry function pointer.
__host__ cudaError_t cudaFuncGetParamCount(const void *func, size_t *paramCount)
Returns the number of parameters used by the function.
__host__ cudaError_t cudaFuncGetParamInfo(const void *func, size_t paramIndex, size_t
*paramOffset, size_t *paramSize)
Returns the offset and size of a kernel parameter in the device-side parameter layout.
__host__ cudaError_t cudaFuncSetAttribute(const void *func, enum cudaFuncAttribute attr, int
value)
Set attributes for a given function.
6.17. Execution Control
281
CUDA Runtime API Reference Manual, Release 13.5
__host__ cudaError_t cudaFuncSetCacheConfig(const void *func, enum cudaFuncCache cacheCon-
fig)
Sets the preferred cache configuration for a device function.
__device__ void * cudaGetParameterBuffer(size_t alignment, size_t size)
Obtains a parameter buffer.
__device__ void cudaGridDependencySynchronize(void)
Programmatic grid dependency synchronization.
__host__ cudaError_t cudaLaunchCooperativeKernel(const void *func, dim3 gridDim, dim3 blockDim,
void **args, size_t sharedMem, cudaStream_t stream)
Launches a device function where thread blocks can cooperate and synchronize as they execute.
__device__ cudaError_t cudaLaunchDevice(void *func, void *parameterBuffer, dim3 gridDimension,
dim3 blockDimension, unsigned int sharedMemSize, cudaStream_t stream)
Launches a specified kernel.
__host__ cudaError_t cudaLaunchHostFunc(cudaStream_t stream, cudaHostFn_t fn, void *userData)
Enqueues a host function call in a stream.
__host__ cudaError_t cudaLaunchHostFunc_v2(cudaStream_t stream, cudaHostFn_t fn, void *user-
Data, unsigned int syncMode)
Enqueues a host function call in a stream.
__host__ cudaError_t cudaLaunchKernel(const void *func, dim3 gridDim, dim3 blockDim, void **args,
size_t sharedMem, cudaStream_t stream)
Launches a device function.
__host__ cudaError_t cudaLaunchKernelExC(const cudaLaunchConfig_t *config, const void *func,
void **args)
Launches a CUDA function with launch-time configuration.
__device__ void cudaTriggerProgrammaticLaunchCompletion(void)
Programmatic dependency trigger.
6.17.1. Functions
__host__ cudaError_t cudaFuncGetAttributes(struct cudaFuncAttributes *attr, const void *func)
Find out attributes for a given function.
This function obtains the attributes of a function specified via func. func is a device func-
tion symbol and must be declared as a __global__ function. The fetched attributes are
placed in attr. If the specified function does not exist, then it is assumed to be a cu-
daKernel_t and used as is. For templated functions, pass the function symbol as follows:
func_name<template_arg_0,…,template_arg_N>
Note that some function attributes such as maxThreadsPerBlock may vary based on the device
that is currently being used.
See also:
cudaFuncSetCacheConfig (C API), cudaFuncGetAttributes (C++ API), cudaLaunchKernel (C API), ::cu-
FuncGetAttribute
282
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: Use of a string naming a function as the func parameter was deprecated in CUDA 4.1
and removed in CUDA 5.0.
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
▶ attr - - Return pointer to function’s attributes
▶ func - - Device function symbol
Returns
cudaSuccess, cudaErrorInvalidDeviceFunction
__host__ cudaError_t cudaFuncGetName(const char **name, const void *func)
Returns the function name for a device entry function pointer.
Returns in **name the function name associated with the symbol func . The function name is
returned as a null-terminated string. This API may return a mangled name if the function is not
declared as having C linkage. If **name is NULL, cudaErrorInvalidValue is returned. If func is not
a device entry function, then it is assumed to be a cudaKernel_t and used as is.
cudaFuncGetName (C++ API)
Note: Note that this function may also return error codes from previous, asynchronous launches.
6.17. Execution Control
283
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.
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
▶ name - - The returned name of the function
▶ func - - The function pointer to retrieve name for
Returns
cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidDeviceFunction
__host__ cudaError_t cudaFuncGetParamCount(const void *func, size_t *paramCount)
Returns the number of parameters used by the function.
Queries the number of kernel parameters used by func and returns it in paramCount.
Note: Note that this function may also return error codes from previous, asynchronous launches.
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
284
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ func - - The function to query
▶ paramCount - - Returns the number of parameters used by the function
Returns
::CUDA_SUCCESS, ::CUDA_ERROR_INVALID_VALUE,
__host__ cudaError_t cudaFuncGetParamInfo(const void *func, size_t paramIndex, size_t
*paramOffset, size_t *paramSize)
Returns the offset and size of a kernel parameter in the device-side parameter layout.
Queries the kernel parameter at paramIndex in func's list of parameters and returns parameter
information via paramOffset and paramSize. paramOffset returns the offset of the parame-
ter in the device-side parameter layout. paramSize returns the size in bytes of the parameter.
This information can be used to update kernel node parameters from the device via cudaGraphK-
ernelNodeSetParam() and cudaGraphKernelNodeUpdatesApply(). paramIndex must be less than
the number of parameters that func takes.
Note: Note that this function may also return error codes from previous, asynchronous launches.
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
▶ func - - The function to query
▶ paramIndex - - The parameter index to query
▶ paramOffset - - The offset into the device-side parameter layout at which the
parameter resides
▶ paramSize - - The size of the parameter in the device-side parameter layout
Returns
::CUDA_SUCCESS, ::CUDA_ERROR_INVALID_VALUE,
__host__ cudaError_t cudaFuncSetAttribute(const void *func, enum cudaFuncAttribute attr, int
value)
Set attributes for a given function.
This function sets the attributes of a function specified via func. The parameter func must
be a pointer to a function that executes on the device. The parameter specified by func must
be declared as a __global__ function. The enumeration defined by attr is set to the value
defined by value. If the specified function does not exist, then it is assumed to be a cudaKernel_t
6.17. Execution Control
285
CUDA Runtime API Reference Manual, Release 13.5
and used as is. If the specified attribute cannot be written, or if the value is incorrect, then
cudaErrorInvalidValue is returned.
Valid values for attr are:
▶ cudaFuncAttributeMaxDynamicSharedMemorySize - The requested maximum size in bytes
of dynamically-allocated shared memory. The sum of this value and the function attribute
::sharedSizeBytes cannot exceed the device attribute cudaDevAttrMaxSharedMemoryPer-
BlockOptin. The maximal size of requestable dynamic shared memory may differ by GPU
architecture.
▶ cudaFuncAttributePreferredSharedMemoryCarveout - On devices where the L1 cache and
shared memory use the same hardware resources, this sets the shared memory carveout
preference, in percent of the total shared memory. See cudaDevAttrMaxSharedMemoryPer-
Multiprocessor. This is only a hint, and the driver can choose a different ratio if required to
execute the function.
▶ cudaFuncAttributeRequiredClusterWidth: The required cluster width in blocks. The width,
height, and depth values must either all be 0 or all be positive. The validity of the cluster
dimensions is checked at launch time. If the value is set during compile time, it cannot be
set at runtime. Setting it at runtime will return cudaErrorNotPermitted.
▶ cudaFuncAttributeRequiredClusterHeight: The required cluster height in blocks. The width,
height, and depth values must either all be 0 or all be positive. The validity of the cluster
dimensions is checked at launch time. If the value is set during compile time, it cannot be
set at runtime. Setting it at runtime will return cudaErrorNotPermitted.
▶ cudaFuncAttributeRequiredClusterDepth: The required cluster depth in blocks. The width,
height, and depth values must either all be 0 or all be positive. The validity of the cluster
dimensions is checked at launch time. If the value is set during compile time, it cannot be
set at runtime. Setting it at runtime will return cudaErrorNotPermitted.
▶ cudaFuncAttributeNonPortableClusterSizeAllowed: Indicates whether the function can be
launched with non-portable cluster size. 1 is allowed, 0 is disallowed.
▶ cudaFuncAttributeClusterSchedulingPolicyPreference: The block scheduling policy of a func-
tion. The value type is cudaClusterSchedulingPolicy.
cudaLaunchKernel (C++ API), cudaFuncSetCacheConfig (C++ API), cudaFuncGetAttributes (C API),
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
286
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
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
▶ func - - Function to get attributes of
▶ attr - - Attribute to set
▶ value - - Value to set
Returns
cudaSuccess, cudaErrorInvalidDeviceFunction, cudaErrorInvalidValue
__host__ cudaError_t cudaFuncSetCacheConfig(const void *func, enum cudaFuncCache
cacheConfig)
Sets the preferred cache configuration for a device function.
On devices where the L1 cache and shared memory use the same hardware resources, this sets
through cacheConfig the preferred cache configuration for the function specified via func.
This is only a preference. The runtime will use the requested configuration if possible, but it is
free to choose a different configuration if required to execute func.
func is a device function symbol and must be declared as a __global__ function. If the spec-
ified function does not exist, then cudaErrorInvalidDeviceFunction is returned. For templated
functions, pass the function symbol as follows: func_name<template_arg_0,…,template_arg_N>
This setting does nothing on devices where the size of the L1 cache and shared memory are
fixed.
Launching a kernel with a different preference than the most recent preference setting may
insert a device-side synchronization point.
The supported cache configurations are:
▶ cudaFuncCachePreferNone: no preference for shared memory or L1 (default)
▶ cudaFuncCachePreferShared: prefer larger shared memory and smaller L1 cache
▶ cudaFuncCachePreferL1: prefer larger L1 cache and smaller shared memory
▶ cudaFuncCachePreferEqual: prefer equal size L1 cache and shared memory
See also:
cudaFuncSetCacheConfig (C++ API), cudaFuncGetAttributes (C API), cudaLaunchKernel (C API), ::cu-
FuncSetCacheConfig
Note: Note that this function may also return error codes from previous, asynchronous launches.
6.17. Execution Control
287
CUDA Runtime API Reference Manual, Release 13.5
Note: Use of a string naming a function as the func parameter was deprecated in CUDA 4.1
and removed in CUDA 5.0.
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: This API does not accept a cudaKernel_t casted as void*. If cache config modification is
required for a cudaKernel_t (or a global function), it can be replaced with a call to ::cudaFunc-
SetAttributes with the attribute cudaFuncAttributePreferredSharedMemoryCarveout to specify
a more granular L1 cache and shared memory split configuration.
Parameters
▶ func - - Device function symbol
▶ cacheConfig - - Requested cache configuration
Returns
cudaSuccess, cudaErrorInvalidDeviceFunction
__device__ void *cudaGetParameterBuffer(size_t alignment, size_t size)
Obtains a parameter buffer.
Obtains a parameter buffer which can be filled with parameters for a kernel launch. Parameters
passed to cudaLaunchDevice must be allocated via this function.
This is a low level API and can only be accessed from Parallel Thread Execution (PTX). CUDA user
code should use <<< >>> to launch kernels.
See also:
cudaLaunchDevice
Note: Note that this function may also return error codes from previous, asynchronous launches.
Parameters
▶ alignment - - Specifies alignment requirement of the parameter buffer
▶ size - - Specifies size requirement in bytes
Returns
Returns pointer to the allocated parameterBuffer
288
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
__device__ inline void cudaGridDependencySynchronize(void)
Programmatic grid dependency synchronization.
This device function will block the thread until all direct grid dependencies have completed.
This API is intended to use in conjuncture with programmatic / launch event / dependency.
See ::cudaLaunchAttributeID::cudaLaunchAttributeProgrammaticStreamSerialization and ::cud-
aLaunchAttributeID::cudaLaunchAttributeProgrammaticEvent for more information.
__host__ cudaError_t cudaLaunchCooperativeKernel(const void *func, dim3 gridDim, dim3
blockDim, void **args, size_t sharedMem,
cudaStream_t stream)
Launches a device function where thread blocks can cooperate and synchronize as they execute.
The function invokes kernel func on gridDim (gridDim.xgridDim.ygridDim.z) grid of blocks.
Each block contains blockDim (blockDim.xblockDim.yblockDim.z) threads.
The device on which this kernel is invoked must have a non-zero value for the device attribute
cudaDevAttrCooperativeLaunch.
The total number of blocks launched cannot exceed the maximum number of blocks per multi-
processor as returned by cudaOccupancyMaxActiveBlocksPerMultiprocessor (or cudaOccupancy-
MaxActiveBlocksPerMultiprocessorWithFlags) times the number of multiprocessors as specified
by the device attribute cudaDevAttrMultiProcessorCount.
The kernel cannot make use of CUDA dynamic parallelism.
If the kernel has N parameters the args should point to array of N pointers. Each pointer, from
args[0] to args[N - 1], point to the region of memory from which the actual parameter will
be copied.
For
templated
functions,
pass
the
function
symbol
as
follows:
func_name<template_arg_0,…,template_arg_N>
sharedMem sets the amount of dynamic shared memory that will be available to each thread
block.
stream specifies a stream the invocation is associated to.
See also:
cudaLaunchCooperativeKernel (C++ API), ::cuLaunchCooperativeKernel
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.
6.17. Execution Control
289
CUDA Runtime API Reference Manual, Release 13.5
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
▶ func - - Device function symbol
▶ gridDim - - Grid dimentions
▶ blockDim - - Block dimentions
▶ args - - Arguments
▶ sharedMem - - Shared memory
▶ stream - - Stream identifier
Returns
cudaSuccess, cudaErrorInvalidDeviceFunction, cudaErrorInvalidConfiguration, cu-
daErrorLaunchFailure, cudaErrorLaunchTimeout, cudaErrorLaunchOutOfResources,
cudaErrorCooperativeLaunchTooLarge, cudaErrorSharedObjectInitFailed
__device__ cudaError_t cudaLaunchDevice(void *func, void *parameterBuffer, dim3 gridDimension,
dim3 blockDimension, unsigned int sharedMemSize,
cudaStream_t stream)
Launches a specified kernel.
Launches a specified kernel with the specified parameter buffer. A parameter buffer can be
obtained by calling cudaGetParameterBuffer().
This is a low level API and can only be accessed from Parallel Thread Execution (PTX). CUDA user
code should use <<< >>> to launch the kernels.
See also:
cudaGetParameterBuffer
Note:
Note that this function may also return error codes from previous, asynchronous launches.
Please refer to Execution Configuration and Parameter Buffer Layout from the CUDA Program-
ming Guide for the detailed descriptions of launch configuration and parameter layout respec-
tively.
Parameters
290
Chapter 6. APIs
CUDA Runtime API Reference Manual, Release 13.5
▶ func - - Pointer to the kernel to be launched
▶ parameterBuffer - - Holds the parameters to the launched kernel. parame-
terBuffer can be NULL. (Optional)
▶ gridDimension - - Specifies grid dimensions
▶ blockDimension - - Specifies block dimensions
▶ sharedMemSize - - Specifies size of shared memory
▶ stream - - Specifies the stream to be used
Returns
cudaSuccess, cudaErrorInvalidDevice, cudaErrorLaunchMaxDepthExceeded, cudaEr-
rorInvalidConfiguration, cudaErrorStartupFailure, cudaErrorLaunchPendingCountEx-
ceeded, cudaErrorLaunchOutOfResources
__host__ cudaError_t cudaLaunchHostFunc(cudaStream_t stream, cudaHostFn_t fn, void
*userData)
Enqueues a host function call in a stream.
Enqueues a host function to run in a stream. The function will be called after currently enqueued
work and will block work added after it.
The host function must not make any CUDA API calls. Attempting to use a CUDA API may re-
sult in cudaErrorNotPermitted, but this is not required. The host function must not perform any
synchronization that may depend on outstanding CUDA work not mandated to run earlier. Host
functions without a mandated order (such as in independent streams) execute in undefined or-
der and may be serialized.
For the purposes of Unified Memory, execution makes a number of guarantees:
▶ The stream is considered idle for the duration of the function’s execution. Thus, for example,
the function may always use memory attached to the stream it was enqueued in.
▶ The start of execution of the function has the same effect as synchronizing an event
recorded in the same stream immediately prior to the function. It thus synchronizes streams
which have been “joined” prior to the function.
▶ Adding device work to any stream does not have the effect of making the stream active
until all preceding host functions and stream callbacks have executed. Thus, for example, a
function might use global attached memory even if work has been added to another stream,
if the work has been ordered behind the function call with an event.
▶ Completion of the function does not cause a stream to become active except as described
above. The stream will remain idle if no device work follows the function, and will remain
idle across consecutive host functions or stream callbacks without device work in between.
Thus, for example, stream synchronization can be done by signaling from a host function at
the end of the stream.
Note that, in constrast to ::cuStreamAddCallback, the function will not be called in the event of
an error in the CUDA context.
See also:
cudaStreamCreate, cudaStreamQuery, cudaStreamSynchronize, cudaStreamWaitEvent, cudaS-
treamDestroy, cudaMallocManaged, cudaStreamAttachMemAsync, cudaStreamAddCallback, ::cu-
LaunchHostFunc
6.17. Execution Control
291
|
||
|
|
|