device_core.h#

Fully qualified name: src/device/vpu_runtime/include/cupva_device/device_core.h

File members: src/device/vpu_runtime/include/cupva_device/device_core.h

/*
 * Copyright (c) 2020-2026 NVIDIA Corporation.  All rights reserved.
 *
 * NVIDIA Corporation and its licensors retain all intellectual property
 * and proprietary rights in and to this software, related documentation
 * and any modifications thereto.  Any use, reproduction, disclosure or
 * distribution of this software and related documentation without an express
 * license agreement from NVIDIA Corporation is strictly prohibited.
 */
#ifndef CUPVA_DEVICE_CORE_H
#define CUPVA_DEVICE_CORE_H

#include "impl/dma_common.h"

#include <cupva_device/cupva_vector_ptr_cast.h>
#include <cupva_device/impl/cpp_utils.h>
#include <cupva_types.h>
#include <limits.h>
#include <stddef.h>
#include <stdint.h>

#if (CUPVA_BUILD_MODE != CUPVA_NATIVE)
typedef dvuint AgenCFG;
#else
#    include <assert.h>
#endif

namespace cupva { namespace device { namespace priv {
template<typename T>
inline void ignoreReturn(T const &)
{
}

template<bool DoAsserts>
struct AssertHandler
{
    template<typename T>
    static constexpr void check(T const &)
    {
    }
};

#if (CUPVA_BUILD_MODE == CUPVA_NATIVE)
template<>
struct AssertHandler<true>
{
    template<typename T>
    static constexpr void check(T const &predicate)
    {
        assert(predicate);
    }
};
#endif

template<bool DoAsserts, typename T>
inline constexpr void checkAndAssert(T const &predicate)
{
    AssertHandler<DoAsserts>::check(predicate);
}

template<typename T>
inline constexpr void vpuAssert(T const &predicate)
{
    checkAndAssert<true>(predicate);
}

}}} // namespace cupva::device::priv

#define CUPVA_VPU_MAIN() int32_t CUPVA_VPU_MAIN_SYMBOL()

namespace cupva { namespace device { namespace priv {
template<typename T>
struct TypeTag
{
};

template<typename TileWidth, typename TileHeight, typename HaloX, typename HaloY>
constexpr uint32_t singleBufferLength(TileWidth tw, TileHeight th, HaloX haloX, HaloY haloY)
{
    return static_cast<uint32_t>(((tw + (2U * haloX)) * (th + (2U * haloY))));
}

template<typename TileWidth, typename TileHeight, typename... Unused>
constexpr uint32_t bufferLengthVar(TileWidth tw, TileHeight th, Unused...)
{
    return singleBufferLength(tw, th, 0U, 0U);
}

template<typename TileWidth, typename TileHeight, typename HaloX, typename... Unused>
constexpr uint32_t bufferLengthHalo1D(TileWidth tw, TileHeight th, HaloX haloX, Unused...)
{
    return singleBufferLength(tw, th, haloX, 0U);
}

template<typename TileWidth, typename TileHeight, typename HaloX, typename HaloY, typename... Unused>
constexpr uint32_t bufferLengthHalo2D(TileWidth tw, TileHeight th, HaloX haloX, HaloY haloY, Unused...)
{
    return singleBufferLength(tw, th, haloX, haloY);
}

template<typename TileWidth, typename TileHeight, typename HaloX, typename HaloY, typename Mode, typename T>
constexpr uint32_t bufferLengthHaloTranspose2D(TileWidth tw, TileHeight th, HaloX haloX, HaloY haloY, Mode mode,
                                               TypeTag<T>)
{
    return static_cast<uint32_t>(
        (TRANSPOSE_LINE_PITCH_ALIGNED((tw + (2U * haloX)) * sizeof(T), mode, sizeof(T)) * (th + (2U * haloY))) /
        sizeof(T));
}

template<typename T, typename TileWidth, typename TileHeight>
constexpr uint32_t bufferLength(TileWidth tw, TileHeight th)
{
    return bufferLengthVar(tw, th);
}

template<typename T, typename TileWidth, typename TileHeight, typename HaloX>
constexpr uint32_t bufferLength(TileWidth tw, TileHeight th, HaloX haloX)
{
    return bufferLengthHalo1D(tw, th, haloX);
}

template<typename T, typename TileWidth, typename TileHeight, typename HaloX, typename HaloY>
constexpr uint32_t bufferLength(TileWidth tw, TileHeight th, HaloX haloX, HaloY haloY)
{
    return bufferLengthHalo2D(tw, th, haloX, haloY);
}

template<typename T, typename TileWidth, typename TileHeight, typename HaloX, typename HaloY, typename Mode>
constexpr uint32_t bufferLength(TileWidth tw, TileHeight th, HaloX haloX, HaloY haloY, Mode mode)
{
    return bufferLengthHaloTranspose2D(tw, th, haloX, haloY, mode, TypeTag<T>{});
}
}}} // namespace cupva::device::priv

#define CUPVA_BUFFER_LENGTH_IMPL_HALO_TRANSPOSE_2D(tw, th, haloX, haloY, type, mode)                                \
    (TRANSPOSE_LINE_PITCH_ALIGNED(((tw) + 2 * (haloX)) * sizeof(type), mode, sizeof(type)) * ((th) + 2 * (haloY)) / \
     sizeof(type))
#define CUPVA_BUFFER_LENGTH_MACRO(tw, th, haloX, haloY, type, mode, macro, ...) macro

namespace cupva { namespace device { namespace priv {
template<typename T, typename TileWidth, typename TileHeight, typename HaloX, typename HaloY, typename Mode,
         typename... Unused>
constexpr uint32_t circularBufferLengthRowMajor(TileWidth tw, TileHeight th, HaloX haloX, HaloY haloY, Mode mode,
                                                Unused...)
{
    return static_cast<uint32_t>(
        (CIRCULAR_BUFFER_ALIGNED_SIZE(TRANSPOSE_LINE_PITCH_ALIGNED(CIRCULAR_BUFFER_LINE_PITCH_ALIGNED(
                                                                       ((tw * CIRCULAR_BUFFER_LINE_PITCH_FACTOR0) +
                                                                        (haloX * CIRCULAR_BUFFER_LINE_PITCH_FACTOR1)) *
                                                                       sizeof(T)),
                                                                   mode, sizeof(T)) *
                                      (th + (2U * haloY))) +
         CIRCULAR_BUFFER_EXTRA_BYTES) /
        sizeof(T));
}

template<typename T, typename TileWidth, typename TileHeight, typename HaloX, typename HaloY, typename Mode,
         typename... Unused>
constexpr uint32_t circularBufferLengthColumnMajor(TileWidth tw, TileHeight th, HaloX haloX, HaloY haloY, Mode mode,
                                                   Unused...)
{
    return static_cast<uint32_t>(
        (CIRCULAR_BUFFER_ALIGNED_SIZE(
             TRANSPOSE_LINE_PITCH_ALIGNED(CIRCULAR_BUFFER_LINE_PITCH_ALIGNED((tw + (2U * haloX)) * sizeof(T)), mode,
                                          sizeof(T)) *
             ((th * CIRCULAR_BUFFER_LINE_PITCH_FACTOR0) + (haloY * CIRCULAR_BUFFER_LINE_PITCH_FACTOR1))) +
         CIRCULAR_BUFFER_EXTRA_BYTES) /
        sizeof(T));
}
template<typename T>
constexpr T maxValue(T a, T b)
{
    return a > b ? a : b;
}
}}} // namespace cupva::device::priv

#define CUPVA_SINGLE_BUFFER_LENGTH(tw, th, ...)                                                                 \
    CUPVA_BUFFER_LENGTH_MACRO(tw, th, ##__VA_ARGS__, CUPVA_BUFFER_LENGTH_IMPL_HALO_TRANSPOSE_2D,                \
                              cupva::device::priv::bufferLengthHalo2D, cupva::device::priv::bufferLengthHalo2D, \
                              cupva::device::priv::bufferLengthHalo1D, cupva::device::priv::bufferLengthVar)    \
    (tw, th, ##__VA_ARGS__)

#define CUPVA_DOUBLE_BUFFER_LENGTH(tw, th, ...) \
    (CIRCULAR_BUFFER_ALIGNED_SIZE(CUPVA_SINGLE_BUFFER_LENGTH(tw, th, ##__VA_ARGS__) * 2))

#define CUPVA_CIRCULAR_BUFFER_LENGTH(type, tw, th, haloX, haloY, ...) \
    RDF_CIRCULAR_ROWMAJOR(type, tw, th, haloX, haloY, ##__VA_ARGS__)

#define RDF_SINGLE(type, tw, th, ...) cupva::device::priv::bufferLength<type>(tw, th, ##__VA_ARGS__)

#define RDF_DOUBLE(type, tw, th, ...) \
    (CIRCULAR_BUFFER_ALIGNED_SIZE((RDF_SINGLE(type, tw, th, ##__VA_ARGS__)) * 2 * sizeof(type)) / sizeof(type))

#define RDF_CIRCULAR_ROWMAJOR(type, tw, th, haloX, haloY, ...) \
    cupva::device::priv::circularBufferLengthRowMajor<type>(tw, th, haloX, haloY, ##__VA_ARGS__, TRANS_MODE_NONE)

#define RDF_CIRCULAR_COLUMNMAJOR(type, tw, th, haloX, haloY, ...) \
    cupva::device::priv::circularBufferLengthColumnMajor<type>(tw, th, haloX, haloY, ##__VA_ARGS__, TRANS_MODE_NONE)

#define RDF_CIRCULAR(type, tw, th, haloX, haloY, ...)                                               \
    cupva::device::priv::maxValue(RDF_CIRCULAR_ROWMAJOR(type, tw, th, haloX, haloY, ##__VA_ARGS__), \
                                  RDF_CIRCULAR_COLUMNMAJOR(type, tw, th, haloX, haloY, ##__VA_ARGS__))

#define VMEM_NOEXPORT(bank, type, name, ...) VMEM_NOEXPORT_IMPL(bank, type, name, ##__VA_ARGS__)

#define VMEM_DATA_IMPL(bank, type, name, ...)                                        \
    GET_VMEM_MACRO(bank, type, name, ##__VA_ARGS__, VMEM_2D, VMEM_1D, VMEM_VAR, ...) \
    (bank, type, name, ##__VA_ARGS__);                                               \
    CUPVA_EXPORT(name, name)

#define VMEM_DDF_HANDLER_WRAPPER(bank, type, name, nodesPerLane, lanes, isDDF) \
    VMEM_DDF_HANDLER(bank, name, nodesPerLane, lanes)

#define VMEM_DDF_SELECTOR(bank, type, name, h, w, isDDF, macro, ...) macro

#define VMEM_INVOKE(NAME, ARGS) NAME ARGS

#define VMEM(bank, type, name, ...)                                                                        \
    VMEM_INVOKE(VMEM_INVOKE(VMEM_DDF_SELECTOR, (bank, type, name, ##__VA_ARGS__, VMEM_DDF_HANDLER_WRAPPER, \
                                                VMEM_DATA_IMPL, VMEM_DATA_IMPL, VMEM_DATA_IMPL)),          \
                (bank, type, name, ##__VA_ARGS__))

#define EXTERN_VMEM(bank, type, name, ...) EXTERN_VMEM_IMPL(bank, type, name, ##__VA_ARGS__)

#define VMEM_POINTER(bank, name)         \
    VMEM_VAR(bank, ExtMemPointer, name); \
    CUPVA_EXPORT(name, name, VMEM_TYPE_POINTER_EX)

#define EXTERN_VMEM_POINTER(bank, name) EXTERN_VMEM_IMPL(bank, ExtMemPointer, name)

#define VMEM_SURFACE(bank, name)                                \
    VMEM_VAR(bank, VPUSurfaceData, name);                       \
    CUPVA_EXPORT(name.pointer, _S##name, VMEM_TYPE_POINTER_EX); \
    CUPVA_EXPORT(name.metadata, _M##name)

#define EXTERN_VMEM_SURFACE(bank, name) EXTERN_VMEM_IMPL(bank, VPUSurfaceData, name)

#define VMEM_RDF_UNIFIED(bank, name)         \
    VMEM_VAR(bank, UnifiedRDFHandler, name); \
    CUPVA_EXPORT(name.hdl, name)

#define VMEM_DMA_CONFIG(bank, type, name, ...)                                       \
    GET_VMEM_MACRO(bank, type, name, ##__VA_ARGS__, VMEM_2D, VMEM_1D, VMEM_VAR, ...) \
    (bank, type, name, ##__VA_ARGS__);                                               \
    CUPVA_EXPORT(name, name, VMEM_TYPE_VPUC_TABLE)

#define EXTERN_VMEM_DMA_CONFIG(bank, type, name, ...) EXTERN_VMEM_IMPL(bank, type, name, ##__VA_ARGS__)

#define CUPVA_ALIGNED(type, name, alignment) CUPVA_ALIGNED_IMPL(type, name, alignment)

#define CUPVA_EXPORT(variable, name, ...) \
    CUPVA_EXPORT_IMPL(variable, name##_export, sizeof(variable), ##__VA_ARGS__, VMEM_TYPE_DATA)

inline void cupvaDataFlowTrig(uint32_t handler);

inline void cupvaDataFlowSync(uint32_t handler);

inline uint32_t cupvaGetVpuId(void);

namespace cupva { namespace device { namespace priv {
inline uint32_t icacheRegisterAddress(uint32_t offset)
{
    uint32_t const vpuId = cupvaGetVpuId();
    cupva::device::priv::vpuAssert((vpuId <= (UINT32_MAX / icacheVpuOffset)));
    uint32_t const vpuBase = icacheVpuOffset * vpuId;
    cupva::device::priv::vpuAssert((vpuBase <= (UINT32_MAX - icacheVpu0Base)));
    uint32_t const base = icacheVpu0Base + vpuBase;
    cupva::device::priv::vpuAssert((offset <= (UINT32_MAX - base)));
    return base + offset;
}

inline uint32_t icachePrefetchCmdStatus()
{
    return icacheRegisterAddress(0x10U);
}

inline uint32_t icachePrefetchStart()
{
    return icacheRegisterAddress(0x14U);
}
}}} // namespace cupva::device::priv
inline uint32_t cupvaGetVmemBase(void);

inline uint32_t cupvaGetDmaDescBase(void);

inline uint32_t cupvaGetHwseqRamBase(void);

inline uint32_t cupvaGetChannelRegAddr(int8_t channel_idx, uint16_t reg_ofst);

inline uint32_t cupvaGetL2Base(void);

inline uint32_t cupvaGetL2Size(void);

inline void cupvaGetL2ExtMemPointer(ExtMemPointer *ptr, uint32_t offset)
{
    ptr->base   = static_cast<uint64_t>(cupvaGetL2Base());
    ptr->size   = static_cast<uint64_t>(cupvaGetL2Size());
    ptr->offset = offset;
    // cast accesses uint8_t (1 byte) at offset 7 of
    // ptr->base, which is `uint64_t` (8 bytes by definition). Trivially in
    // bounds; no runtime/static check needed.
    uint8_t *base = ::cupva::device::priv::pointerCast<uint8_t>(&ptr->base);
    base[7]       = CUPVA_EXT_MEM_TYPE_L2;
}

inline uint32_t cupvaGetVmemAddress(void *ptr);

typedef struct
{
    int32_t size;

    uint16_t n1;
    uint16_t n2;
    uint16_t n3;
    uint16_t n4;
    uint16_t n5;
    uint16_t n6;

    int32_t s1;
    int32_t s2;
    int32_t s3;
    int32_t s4;
    int32_t s5;
    int32_t s6;
} AgenWrapper;

namespace cupva { namespace device { namespace priv {

template<typename Agen>
inline void initAgen1(Agen &agen, AgenWrapper const &wrapper)
{
    agen.n1   = wrapper.n1;
    agen.mod1 = wrapper.s1 * wrapper.size;
}

template<typename Agen>
inline void initAgen2(Agen &agen, AgenWrapper const &wrapper)
{
    initAgen1(agen, wrapper);
    agen.n2   = wrapper.n2;
    agen.mod2 = (wrapper.s2 - ((static_cast<int32_t>(wrapper.n1) - 1) * wrapper.s1)) * wrapper.size;
}

template<typename Agen>
inline void initAgen3(Agen &agen, AgenWrapper const &wrapper)
{
    initAgen2(agen, wrapper);
    agen.n3   = wrapper.n3;
    agen.mod3 = (wrapper.s3 - ((static_cast<int32_t>(wrapper.n1) - 1) * wrapper.s1) -
                 ((static_cast<int32_t>(wrapper.n2) - 1) * wrapper.s2)) *
                wrapper.size;
}

template<typename Agen>
inline void initAgen4(Agen &agen, AgenWrapper const &wrapper)
{
    initAgen3(agen, wrapper);
    agen.n4   = wrapper.n4;
    agen.mod4 = (wrapper.s4 - ((static_cast<int32_t>(wrapper.n1) - 1) * wrapper.s1) -
                 ((static_cast<int32_t>(wrapper.n2) - 1) * wrapper.s2) -
                 ((static_cast<int32_t>(wrapper.n3) - 1) * wrapper.s3)) *
                wrapper.size;
}

template<typename Agen>
inline void initAgen5(Agen &agen, AgenWrapper const &wrapper)
{
    initAgen4(agen, wrapper);
    agen.n5 = wrapper.n5;
    agen.mod5 =
        (wrapper.s5 - ((static_cast<int32_t>(wrapper.n1) - 1) * wrapper.s1) -
         ((static_cast<int32_t>(wrapper.n2) - 1) * wrapper.s2) - ((static_cast<int32_t>(wrapper.n3) - 1) * wrapper.s3) -
         ((static_cast<int32_t>(wrapper.n4) - 1) * wrapper.s4)) *
        wrapper.size;
}

template<typename Agen>
inline void initAgen6(Agen &agen, AgenWrapper const &wrapper)
{
    initAgen5(agen, wrapper);
    agen.n6 = wrapper.n6;
    agen.mod6 =
        (wrapper.s6 - ((static_cast<int32_t>(wrapper.n1) - 1) * wrapper.s1) -
         ((static_cast<int32_t>(wrapper.n2) - 1) * wrapper.s2) - ((static_cast<int32_t>(wrapper.n3) - 1) * wrapper.s3) -
         ((static_cast<int32_t>(wrapper.n4) - 1) * wrapper.s4) -
         ((static_cast<int32_t>(wrapper.n5) - 1) * wrapper.s5)) *
        wrapper.size;
}
}}} // namespace cupva::device::priv
#define INIT_AGEN1(AGEN_INIT, AGEN_WRAPPER) cupva::device::priv::initAgen1((AGEN_INIT), (AGEN_WRAPPER))

#define INIT_AGEN2(AGEN_INIT, AGEN_WRAPPER) cupva::device::priv::initAgen2((AGEN_INIT), (AGEN_WRAPPER))

#define INIT_AGEN3(AGEN_INIT, AGEN_WRAPPER) cupva::device::priv::initAgen3((AGEN_INIT), (AGEN_WRAPPER))

#define INIT_AGEN4(AGEN_INIT, AGEN_WRAPPER) cupva::device::priv::initAgen4((AGEN_INIT), (AGEN_WRAPPER))

#define INIT_AGEN5(AGEN_INIT, AGEN_WRAPPER) cupva::device::priv::initAgen5((AGEN_INIT), (AGEN_WRAPPER))

#define INIT_AGEN6(AGEN_INIT, AGEN_WRAPPER) cupva::device::priv::initAgen6((AGEN_INIT), (AGEN_WRAPPER))

namespace cupva { namespace device { namespace priv {

template<typename VecType>
struct LinearCounts
{
    static_assert(sizeof(VecType) == 0,
                  "cupvaLinearCounts() supports vcharx, vshortx, vintx, dvcharx, dvshortx and dvintx only.");
};

template<>
struct LinearCounts<vshortx>
{
    static inline vshortx generate()
    {
        // VCOLLATEIDX reports the indices of the zero lanes of its source, which for an
        // all-zero source is the lane index of every lane.
        return vcollate_idx(replicateh(0));
    }
};

template<>
struct LinearCounts<vintx>
{
    static inline vintx generate()
    {
        return vcollate_idx(replicatew(0));
    }
};

template<>
struct LinearCounts<dvshortx>
{
    static inline dvshortx generate()
    {
        dvshortx dst;
        dst.lo = LinearCounts<vshortx>::generate();
        dst.hi = dst.lo + static_cast<int32_t>(pva_elementsof(vshortx));
        return dst;
    }
};

template<>
struct LinearCounts<dvintx>
{
    static inline dvintx generate()
    {
        dvintx dst;
        dst.lo = LinearCounts<vintx>::generate();
        dst.hi = dst.lo + static_cast<int32_t>(pva_elementsof(vintx));
        return dst;
    }
};

template<>
struct LinearCounts<vcharx>
{
    static inline vcharx generate()
    {
        // VCOLLATEIDX has no byte form, so the sequence is demoted from the two half word
        // halves it spans.
        return vdemote(LinearCounts<dvshortx>::generate());
    }
};

template<>
struct LinearCounts<dvcharx>
{
    static inline dvcharx generate()
    {
        dvcharx dst;
        dst.lo = LinearCounts<vcharx>::generate();
        dst.hi = dst.lo + static_cast<int32_t>(pva_elementsof(vcharx));
        return dst;
    }
};

}}} // namespace cupva::device::priv
template<typename VecType>
inline VecType cupvaLinearCounts()
{
    return cupva::device::priv::LinearCounts<VecType>::generate();
}

inline void cupvaModifyAgenCfgBase(AgenCFG *cfg, void *const addr);

inline void *cupvaGetAgenCfgBase(AgenCFG *cfg);

inline void cupvaPrefetchReadyWait(void);

inline void cupvaPrefetchDoneWait(void);

inline void cupvaAdvanceAgenCfg(AgenCFG *cfg, const int32_t step_in_bytes)
{
    agen x = init_agen_from_cfg(*cfg);
    adv_agen_base(x, step_in_bytes);
    *cfg = extract_agen_cfg(x);
}

namespace cupva { namespace device { namespace priv {
inline uint32_t getDescAttrAddr(uint32_t const descId, uint32_t const fieldOffset)
{
    uint32_t const base     = cupvaGetDmaDescBase();
    uint32_t const descSize = static_cast<uint32_t>(sizeof(PvaDmaDescriptor));
    vpuAssert((descId <= (0xFFFFFFFFU / descSize)));
    uint32_t const descOffset = descSize * descId;
    vpuAssert((descOffset <= (0xFFFFFFFFU - base)));
    uint32_t const baseWithDesc = base + descOffset;
    vpuAssert((fieldOffset <= (0xFFFFFFFFU - baseWithDesc)));
    return baseWithDesc + fieldOffset;
}
}}} // namespace cupva::device::priv

#define CUPVA_GET_DESC_ATTR_ADDR(desc_id, field) \
    cupva::device::priv::getDescAttrAddr(static_cast<uint32_t>((desc_id)), CUPVA_DMA_DESC_OFFSET(field))

#define CUPVA_ICACHE_FIELD(r, f, value)                             \
    (((value) & CUPVA_FIELD_MASK(CUPVA_ICACHE_##r##_0_##f##_RANGE)) \
     << CUPVA_FIELD_SHIFT(CUPVA_ICACHE_##r##_0_##f##_RANGE))

inline void cupvaCircularBufferMemcpy(void *cb, uint32_t size)
{
    // this function reads one dvint from `cb[0]` and writes
    // one dvint at `cb[size]`. Caller contract (documented above) is that `cb`
    // points to a circular buffer of `size + sizeof(dvint)` bytes minimum so
    // that the head/tail dvint slots are in-bounds.
    // Compare in the uint32_t domain; hoisting sizeof into a typed constant avoids
    // promoting `size` to size_t at the comparison (MISRA 7.0.5).
    cupva::device::priv::vpuAssert((size >= static_cast<uint32_t>(sizeof(dvint))));
    // dvint load/store requires 4-byte alignment of both the base pointer and
    // the size-derived tail offset.
    cupva::device::priv::vpuAssert(((cupva::device::priv::asUintPtr(cb) & 0x3U) == 0U));
    cupva::device::priv::vpuAssert(((size & 0x3U) == 0U));
    dvint *src = cupvaDvintPointerCast(cb);
    // Index in the uint32_t domain (size is asserted 4-byte aligned above) so the
    // reinterpret to dvint* is not an alignment increase from a byte pointer.
    dvint *dst = cupvaDvintPointerCast(&cupva::device::priv::pointerCast<uint32_t>(cb)[size / 4U]);
    (void)(*dst = extract(sign_extend(*src)));
}

inline uint32_t cupvaRasterDataFlowAdvProgPriv(RasterDataFlowHandler &handler)
{
    uint32_t const pc = static_cast<uint32_t>(handler.pc);
    cupva::device::priv::vpuAssert((pc < RDF_INST_COUNT));
    RasterDataFlowTrigInst &instruction = handler.trigProgram[pc];
    uint32_t const modIncResult0 =
        mod_inc(static_cast<uint32_t>(handler.trigCnt), static_cast<uint32_t>(instruction.trigRpt));
    uint32_t const newTrigCnt = modIncResult0;
    uint32_t const jumpDec    = max(static_cast<uint32_t>(instruction.jmpCnt), 1U) - 1U; // Subtract 1, clamp to 0
    // If we are not repeating this trigger, update jmpCnt
    uint32_t const newJmpCnt = (newTrigCnt != 0U) ? static_cast<uint32_t>(instruction.jmpCnt) : jumpDec;
    // If the updated jmpCnt is different to curent jmpCnt, it means we should take the jump
    uint32_t const applyJmp = (newJmpCnt != static_cast<uint32_t>(instruction.jmpCnt)) ? 1U : 0U;
    // Decide whether to 1) apply jump 2) advance PC or 3) stay with current PC
    int32_t const jumpOrAdv = (applyJmp != 0U) ? static_cast<int32_t>(instruction.jmpOffst) : 1;
    int32_t const pcOffset  = (newTrigCnt != 0U) ? 0 : jumpOrAdv;
    // GPIO[0] are not used for triggers so are used for 'no-trigger'
    uint32_t const gpio       = static_cast<uint32_t>(instruction.gpio);
    uint32_t const setTrigger = ((gpio > 0U) ? 1U : 0U);
    uint32_t const trigger    = setTrigger << gpio;
    instruction.jmpCnt        = static_cast<uint8_t>(newJmpCnt);
    int32_t const newPcSigned = static_cast<int32_t>(pc) + pcOffset;
    cupva::device::priv::vpuAssert((newPcSigned >= 0));
    uint32_t const newPc = static_cast<uint32_t>(newPcSigned);
    // Write updates to handler
    handler.pc          = static_cast<uint8_t>(min(newPc, RDF_INST_COUNT - 1U)); // pc - clamp to valid bounds
    handler.trigCnt     = static_cast<uint8_t>(newTrigCnt);                      // trigCnt
    handler.gpioHistory = instruction.gpio;
    return trigger;
}

inline void cupvaRasterDataFlowTrig(RasterDataFlowHandler &handler)
{
    uint32_t trigger = cupvaRasterDataFlowAdvProgPriv(handler);
    cupvaDataFlowTrig(trigger);
}

inline void cupvaRasterDataFlowSync(RasterDataFlowHandler &handler)
{
    uint32_t const gpioHist   = static_cast<uint32_t>(handler.gpioHistory);
    uint32_t const setTrigger = ((gpioHist > 0U) ? 1U : 0U);
    uint32_t const trigger    = setTrigger << gpioHist;
    handler.gpioHistory       = 0;
    cupvaDataFlowSync(trigger);
}

inline int32_t cupvaRasterDataFlowGetLinePitch(RasterDataFlowHandler &handler)
{
    return static_cast<int32_t>(handler.linePitch);
}

inline uint8_t cupvaRasterDataFlowGetLayout(RasterDataFlowHandler &handler)
{
    return static_cast<uint8_t>(
        CUPVA_EXTRACT_FIELD(RDF_TRANSFER_PROPERTIES_LAYOUT, static_cast<uint32_t>(handler.transferProperties)));
}

inline bool cupvaRasterDataFlowIsRead(RasterDataFlowHandler &handler)
{
    return (CUPVA_EXTRACT_FIELD(RDF_TRANSFER_PROPERTIES_IS_READ, static_cast<uint32_t>(handler.transferProperties)) >
            0U);
}

inline uint32_t cupvaRasterDataFlowGetBppLog2(RasterDataFlowHandler &handler)
{
    return CUPVA_EXTRACT_FIELD(RDF_TRANSFER_PROPERTIES_BPPLOG2, static_cast<uint32_t>(handler.transferProperties));
}

inline int32_t cupvaRasterDataFlowGetCbLen(RasterDataFlowHandler &handler)
{
    return handler.cbLen;
}

inline int32_t cupvaRasterDataFlowGetAdvance(RasterDataFlowHandler &handler)
{
    uint32_t ixAdv = static_cast<uint32_t>(handler.ixAdv);
    uint32_t nxm1  = static_cast<uint32_t>(handler.nxm1);
    bool isLast    = ixAdv == nxm1;
    ixAdv          = isLast ? 0U : (ixAdv + 1U);
    int32_t adv    = isLast ? handler.adv[1] : handler.adv[0];
    handler.ixAdv  = static_cast<uint16_t>(ixAdv);

    return adv;
}

inline int32_t cupvaRasterDataFlowGetOffset(RasterDataFlowHandler &handler, int32_t offset)
{
    int32_t ret = cupvaRasterDataFlowGetAdvance(handler) + offset;
    ret         = (ret >= handler.cbLen) ? (ret - handler.cbLen) : ret;
    ret         = (ret < 0) ? (ret + handler.cbLen) : ret;
    return ret;
}

inline int32_t cupvaTransposeLaneOfst(RasterDataFlowHandler &handler, TranspositionMode mode, int32_t bpp)
{
    cupva::device::priv::vpuAssert((bpp >= 0));
    cupva::device::priv::vpuAssert((static_cast<int32_t>(mode) >= 0));
    uint32_t linePitchInBytes   = static_cast<uint32_t>(handler.linePitch) * static_cast<uint32_t>(bpp);
    uint32_t const transHOffset = TRANSPOSE_HORIZONTAL_OFFSET(static_cast<uint32_t>(mode), static_cast<uint32_t>(bpp));
    cupva::device::priv::vpuAssert((linePitchInBytes >= transHOffset));
    uint32_t laneOfst = (linePitchInBytes - transHOffset) / VMEM_SUPERBANK_WIDTH_IN_BYTES;
    return static_cast<int32_t>(laneOfst);
}

void cupvaRasterDataFlowOpen(UnifiedRDFHandler &handler, void *vmemBuffer);

inline void *cupvaRasterDataFlowAcquire(UnifiedRDFHandler &handler)
{
    // Trigger/sync values
    uint32_t const shouldDeferSync = handler.deferSync;
    uint32_t const shouldDeferTrig = handler.deferTrig;
    uint32_t const sync            = handler.nextSync;
    uint32_t const trig            = handler.nextTrig;

    // Pointers for copying CB and returning
    void *const base  = handler.base;
    void *const cbDst = handler.cbDst;
    dvintx cbCopyData;
    uint32_t const bppLog2 = cupvaRasterDataFlowGetBppLog2(handler.hdl);

    // Scalar loads for tile advancement
    uint32_t const ixAdvCurrent      = static_cast<uint32_t>(handler.hdl.ixAdv);
    uint32_t const nxm1Current       = static_cast<uint32_t>(handler.hdl.nxm1);
    int32_t const adv0               = handler.hdl.adv[0];
    int32_t const adv1               = handler.hdl.adv[1];
    uint32_t const tileOffsetCurrent = handler.tileOffset;

    if (shouldDeferSync == 0U)
    {
        cupvaDataFlowSync(sync);
    }

    // Update offset step 1 - determine adv, load registers
    int32_t const cbLen  = handler.hdl.cbLen;
    bool const isLast    = (ixAdvCurrent == nxm1Current);
    int32_t const adv    = isLast ? adv1 : adv0;
    uint32_t const ixAdv = isLast ? 0U : (ixAdvCurrent + 1U);
    void *const retVal   = cupva::device::priv::pointerCast<int8_t>(base) + (tileOffsetCurrent << bppLog2);

    // Vector read CB head
    // dvint load requires 4-byte alignment of the source address.
    cupva::device::priv::vpuAssert(((cupva::device::priv::asUintPtr(base) & 0x3U) == 0U));
    cbCopyData = sign_extend(*cupvaDvintPointerCast(base));

    if (shouldDeferTrig == 0U)
    {
        cupvaDataFlowTrig(trig);
    }

    // Update offset step 2 - compute new tileOffset with wrapping
    handler.hdl.ixAdv = static_cast<uint16_t>(ixAdv);
    cupva::device::priv::vpuAssert((tileOffsetCurrent <= 0x7FFFFFFFU));
    int32_t const tileOffsetNew = adv + static_cast<int32_t>(tileOffsetCurrent);
    int32_t tileOffsetWrapped   = (tileOffsetNew >= cbLen) ? (tileOffsetNew - cbLen) : tileOffsetNew;
    // On host side, negative advancements with CB have been converted to positive advancements, so no need to check
    // for condition tileOffsetNew < 0.
    handler.tileOffset = static_cast<uint32_t>(tileOffsetWrapped);

    // cbDst was computed in cupvaRasterDataFlowOpen as
    //   vmemBuffer plus the offset of the CB tail slot (cbLen << bppLog2)
    // and points at the CB tail slot. RDF layout guarantees the underlying
    // vmemBuffer is sized to hold (cbLen + dvint) bytes.
    // Vector write CB tail
    // dvint store requires 4-byte alignment of the destination address.
    cupva::device::priv::vpuAssert(((cupva::device::priv::asUintPtr(cbDst) & 0x3U) == 0U));
    *cupvaDvintPointerCast(cbDst) = extract(cbCopyData);

    // Return previously calculated tile offset as a pointer
    return retVal;
}

inline void cupvaRasterDataFlowRelease(UnifiedRDFHandler &handler)
{
    // Load data to registers
    uint32_t const pc              = static_cast<uint32_t>(handler.hdl.pc);
    uint32_t const trigCnt         = static_cast<uint32_t>(handler.hdl.trigCnt);
    uint32_t const sync            = handler.nextSync;
    uint32_t const trig            = handler.nextTrig;
    uint32_t const shouldDeferTrig = handler.deferTrig;
    uint32_t const shouldDeferSync = handler.deferSync;

    // Next GPIO calculation part 1 - calculate PC jump
    cupva::device::priv::vpuAssert((pc < RDF_INST_COUNT));
    RasterDataFlowTrigInst &instruction = handler.hdl.trigProgram[pc];
    uint32_t const trigRpt              = static_cast<uint32_t>(instruction.trigRpt);
    uint32_t const jmpCnt               = static_cast<uint32_t>(instruction.jmpCnt);
    int32_t const jmpOffset             = static_cast<int32_t>(instruction.jmpOffst);
    uint32_t const modIncResult1        = mod_inc(static_cast<uint32_t>(trigCnt), static_cast<uint32_t>(trigRpt));
    uint32_t const newTrigCnt           = modIncResult1;
    uint32_t const jumpDec              = max(jmpCnt, 1U) - 1U; // Subtract 1, clamp to 0

    if (shouldDeferSync != 0U)
    {
        cupvaDataFlowSync(sync);
    }

    // Next GPIO calculation part 1 - calculate next trigger
    // If we are not repeating this trigger, update jmpCnt
    uint32_t const newJmpCnt = (newTrigCnt != 0U) ? jmpCnt : jumpDec;
    // If the updated jmpCnt is different to curent jmpCnt, it means we should take the jump
    uint32_t const applyJmp = (newJmpCnt != jmpCnt) ? 1U : 0U;
    // Decide whether to 1) apply jump 2) advance PC or 3) stay with current PC
    int32_t const jumpOrAdv = (applyJmp != 0U) ? jmpOffset : 1;
    int32_t const pcOffset  = (newTrigCnt != 0U) ? 0 : jumpOrAdv;
    // GPIO[0] are not used for triggers so are used for 'no-trigger'
    uint32_t const gpio        = static_cast<uint32_t>(instruction.gpio);
    uint32_t const setNextTrig = ((gpio > 0U) ? 1U : 0U);
    uint32_t const nextTrig    = setNextTrig << gpio;

    if (shouldDeferTrig != 0U)
    {
        cupvaDataFlowTrig(trig);
    }

    // Write updates to handler
    instruction.jmpCnt        = static_cast<uint8_t>(newJmpCnt);
    int32_t const newPcSigned = static_cast<int32_t>(pc) + pcOffset;
    cupva::device::priv::vpuAssert((newPcSigned >= 0));
    uint32_t const newPc = static_cast<uint32_t>(newPcSigned);
    handler.hdl.pc       = static_cast<uint8_t>(min(newPc, RDF_INST_COUNT - 1U)); // pc - clamp to valid bounds
    handler.hdl.trigCnt  = static_cast<uint8_t>(newTrigCnt);                      // trigCnt
    handler.nextTrig     = nextTrig;
    handler.nextSync     = trig;
}

inline void cupvaRasterDataFlowClose(UnifiedRDFHandler &handler)
{
    cupvaDataFlowSync(handler.nextSync);
}

inline int32_t cupvaRasterDataFlowGetLinePitch(UnifiedRDFHandler &handler)
{
    return cupvaRasterDataFlowGetLinePitch(handler.hdl);
}

inline int32_t cupvaRasterDataFlowGetCbLen(UnifiedRDFHandler &handler)
{
    return cupvaRasterDataFlowGetCbLen(handler.hdl);
}

inline int32_t cupvaTransposeLaneOfst(UnifiedRDFHandler &handler, TranspositionMode mode, int32_t bpp)
{
    return cupvaTransposeLaneOfst(handler.hdl, mode, bpp);
}

inline bool cupvaRasterDataFlowIsRead(UnifiedRDFHandler &handler)
{
    return cupvaRasterDataFlowIsRead(handler.hdl);
}

inline uint32_t cupvaRasterDataFlowGetBppLog2(UnifiedRDFHandler &handler)
{
    return cupvaRasterDataFlowGetBppLog2(handler.hdl);
}

namespace cupva { namespace device { namespace priv {
constexpr uint32_t blGobWidth                     = 64U;
constexpr uint32_t blGobWidthLog2                 = 6U;
constexpr int32_t blGobWidthLog2Signed            = 6;
constexpr uint64_t blGobWidthLog2Wide             = 6ULL;
constexpr uint32_t blGobHeight                    = 8U;
constexpr uint32_t blGobHeightLog2                = 3U;
constexpr int32_t blGobHeightLog2Signed           = 3;
constexpr uint64_t blGobHeightLog2Wide            = 3ULL;
constexpr uint32_t blGobSize                      = blGobWidth * blGobHeight;
constexpr uint32_t blGobSizeLog2                  = blGobWidthLog2 + blGobHeightLog2;
constexpr int32_t blGobSizeLog2Signed             = 9;
constexpr uint32_t blGobSectorWidth               = 16U;
constexpr uint32_t blGobSectorWidthLog2           = 4U;
constexpr uint32_t blGobSectorHeight              = 2U;
constexpr uint32_t blGobSectorSize                = blGobSectorWidth * blGobSectorHeight;
constexpr uint32_t blGobPacketMask                = blGobWidth >> 1U;
constexpr uint32_t blGobPacketStride              = 8U;
constexpr uint32_t blGobSubpacketVerticalMask     = 6U;
constexpr uint32_t blGobSubpacketVerticalStride   = 32U;
constexpr uint32_t blGobSubpacketHorizontalMask   = blGobSectorSize >> 1U;
constexpr uint32_t blGobSubpacketHorizontalStride = 2U;
constexpr uint32_t blGobSectorVerticalMask        = blGobSectorHeight - 1U;
constexpr uint32_t blGobSectorVerticalStride      = 16U;
constexpr int32_t blGobPacketStrideSigned              = 8;
constexpr int32_t blGobSubpacketVerticalStrideSigned   = 32;
constexpr int32_t blGobSubpacketHorizontalStrideSigned = 2;
constexpr int32_t blGobSectorVerticalStrideSigned      = 16;
constexpr uint32_t blGobSectorHorizontalMask      = blGobSectorWidth - 1U;
constexpr uint32_t blSbadrIovaShift               = CUPVA_FIELD_SHIFT_UNSIGNED(UINT32_C(13) : UINT32_C(9));
constexpr uint32_t blSbadrIovaMask                = CUPVA_FIELD_MASK(UINT32_C(13) : UINT32_C(9)) << blSbadrIovaShift;
constexpr uint32_t blMetadataFlag                 = 1U << 8U;
constexpr int32_t blMaxBlockheightLog2            = 5;
}}} // namespace cupva::device::priv

#define BL_GOBW cupva::device::priv::blGobWidth
#define BL_GOB_SZ cupva::device::priv::blGobSize

// Swizzle bit which should be set on non-native builds
#define BL_SWIZZLE_BIT 39U
// Addresses from cupvaSurfaceAddress2D will fill metadata starting from this bit
#define BL_ADDR_METADATA_SHIFT 40U
// Flag to indicate that the address is a BL address
#define BL_METADATA_FLAG_BIT 8U

inline vintx cupvaBlocklinearOffset2D(vintx const &xCoords, vintx const &yCoords, uint32_t const linePitch,
                                      uint8_t const blockHeightLog2Param)
{
    uint32_t const blockHeightLog2 = static_cast<uint32_t>(blockHeightLog2Param);
    cupva::device::priv::vpuAssert((blockHeightLog2 <= 5U));
    uint32_t const widthInGobs  = linePitch >> static_cast<uint32_t>(cupva::device::priv::blGobWidthLog2);
    int32_t const blockSizeLog2 = cupva::device::priv::blGobWidthLog2Signed +
                                  cupva::device::priv::blGobHeightLog2Signed + static_cast<int32_t>(blockHeightLog2);
    uint32_t const linesPerBlock = static_cast<uint32_t>(cupva::device::priv::blGobHeight) << blockHeightLog2;
    int32_t const linesPerBlockLog2 =
        cupva::device::priv::blGobHeightLog2Signed + static_cast<int32_t>(blockHeightLog2);
    vintx x = xCoords;
    vintx y = yCoords;

    cupva::device::priv::vpuAssert((linesPerBlock >= 1U));
    vintx vgobBase = (((y & (linesPerBlock - 1U)) >> cupva::device::priv::blGobHeightLog2Signed)
                      << cupva::device::priv::blGobSizeLog2Signed) +
                     ((x >> cupva::device::priv::blGobWidthLog2Signed) << blockSizeLog2);
    vgobBase = vmaddwhw((y >> linesPerBlockLog2) << blockSizeLog2, static_cast<int32_t>(widthInGobs), vgobBase, 0, 1);
    vintx vgobOffset =
        vmaddwhw(y & cupva::device::priv::blGobSectorVerticalMask, cupva::device::priv::blGobSectorVerticalStrideSigned,
                 (x & cupva::device::priv::blGobSectorHorizontalMask), 0, 1);
    vgobOffset = vmaddwhw(x & cupva::device::priv::blGobPacketMask, cupva::device::priv::blGobPacketStrideSigned,
                          vgobOffset, 0, 1);
    vgobOffset = vmaddwhw(y & cupva::device::priv::blGobSubpacketVerticalMask,
                          cupva::device::priv::blGobSubpacketVerticalStrideSigned, vgobOffset, 0, 1);
    vgobOffset = vmaddwhw(x & cupva::device::priv::blGobSubpacketHorizontalMask,
                          cupva::device::priv::blGobSubpacketHorizontalStrideSigned, vgobOffset, 0, 1);

#if ((CUPVA_BUILD_MODE == CUPVA_QNX || CUPVA_BUILD_MODE == CUPVA_L4T) && CUPVA_PVA_GEN_NUMBER <= 2)
    vintx swizzleBit = (replicatew(1) << static_cast<int32_t>(BL_SWIZZLE_BIT));
#else
    vintx swizzleBit = replicatew(0);
#endif
    return (swizzleBit + vgobBase + vgobOffset);
}

inline vintx cupvaBlocklinearOffset2D(vintx const &xCoords, vintx const &yCoords, vintx const &vLinePitch,
                                      uint8_t const blockHeightLog2Param)
{
    uint32_t const blockHeightLog2 = static_cast<uint32_t>(blockHeightLog2Param);
    cupva::device::priv::vpuAssert((blockHeightLog2 <= 5U));
    vintx const widthInGobs     = vLinePitch >> cupva::device::priv::blGobWidthLog2Signed;
    int32_t const blockSizeLog2 = cupva::device::priv::blGobWidthLog2Signed +
                                  cupva::device::priv::blGobHeightLog2Signed + static_cast<int32_t>(blockHeightLog2);
    uint32_t const linesPerBlock = static_cast<uint32_t>(cupva::device::priv::blGobHeight) << blockHeightLog2;
    int32_t const linesPerBlockLog2 =
        cupva::device::priv::blGobHeightLog2Signed + static_cast<int32_t>(blockHeightLog2);
    vintx x = xCoords;
    vintx y = yCoords;

    cupva::device::priv::vpuAssert((linesPerBlock >= 1U));
    vintx vgobBase = (((y & (linesPerBlock - 1U)) >> cupva::device::priv::blGobHeightLog2Signed)
                      << cupva::device::priv::blGobSizeLog2Signed) +
                     ((x >> cupva::device::priv::blGobWidthLog2Signed) << blockSizeLog2);
    vgobBase         = vmaddwhw((y >> linesPerBlockLog2) << blockSizeLog2, widthInGobs, vgobBase, 0, 1);
    vintx vgobOffset =
        vmaddwhw(y & cupva::device::priv::blGobSectorVerticalMask, cupva::device::priv::blGobSectorVerticalStrideSigned,
                 (x & cupva::device::priv::blGobSectorHorizontalMask), 0, 1);
    vgobOffset = vmaddwhw(x & cupva::device::priv::blGobPacketMask, cupva::device::priv::blGobPacketStrideSigned,
                          vgobOffset, 0, 1);
    vgobOffset = vmaddwhw(y & cupva::device::priv::blGobSubpacketVerticalMask,
                          cupva::device::priv::blGobSubpacketVerticalStrideSigned, vgobOffset, 0, 1);
    vgobOffset = vmaddwhw(x & cupva::device::priv::blGobSubpacketHorizontalMask,
                          cupva::device::priv::blGobSubpacketHorizontalStrideSigned, vgobOffset, 0, 1);

#if ((CUPVA_BUILD_MODE == CUPVA_QNX || CUPVA_BUILD_MODE == CUPVA_L4T) && CUPVA_PVA_GEN_NUMBER <= 2)
    vintx swizzleBit = (replicatew(1) << static_cast<int32_t>(BL_SWIZZLE_BIT));
#else
    vintx swizzleBit = replicatew(0);
#endif
    return (swizzleBit + vgobBase + vgobOffset);
}
inline uint64_t cupvaSurfaceAddress2D(VPUSurfaceData const &surfData, uint32_t const x, uint32_t const y)
{
    cupva::device::priv::vpuAssert(surfData.metadata.linePitch > 0U);
    uint32_t const blockHeightLog2 = static_cast<uint32_t>(surfData.metadata.blockHeightLog2 & 0x7FU);
    cupva::device::priv::vpuAssert((blockHeightLog2 <= 5U));
    uint32_t const widthInGobs       = surfData.metadata.linePitch >> cupva::device::priv::blGobWidthLog2;
    uint32_t const blockSizeLog2     = cupva::device::priv::blGobSizeLog2 + blockHeightLog2;
    uint32_t const linesPerBlock     = cupva::device::priv::blGobHeight << blockHeightLog2;
    uint32_t const linesPerBlockLog2 = cupva::device::priv::blGobHeightLog2 + blockHeightLog2;
    cupva::device::priv::vpuAssert((linesPerBlock >= 1U));
    uint64_t const gobBlockRow = (static_cast<uint64_t>(y) >> static_cast<uint64_t>(linesPerBlockLog2))
                                 << static_cast<uint64_t>(blockSizeLog2);
    cupva::device::priv::vpuAssert((widthInGobs == 0U) ||
                                   (gobBlockRow <= (0xFFFFFFFFFFFFFFFFULL / static_cast<uint64_t>(widthInGobs))));
    uint64_t const gobRowTerm = gobBlockRow * static_cast<uint64_t>(widthInGobs);
    uint64_t const gobColTerm = (static_cast<uint64_t>(x) >> cupva::device::priv::blGobWidthLog2Wide)
                                << static_cast<uint64_t>(blockSizeLog2);
    cupva::device::priv::vpuAssert(gobRowTerm <= (0xFFFFFFFFFFFFFFFFULL - gobColTerm));
    uint64_t const gobRowColTerm = gobRowTerm + gobColTerm;
    uint64_t const gobHeightTerm =
        ((static_cast<uint64_t>(y) & (static_cast<uint64_t>(linesPerBlock) - 1UL)) >>
         cupva::device::priv::blGobHeightLog2Wide)
        << (cupva::device::priv::blGobWidthLog2Wide + cupva::device::priv::blGobHeightLog2Wide);
    cupva::device::priv::vpuAssert(gobRowColTerm <= (0xFFFFFFFFFFFFFFFFULL - gobHeightTerm));
    uint64_t const gobBase = gobRowColTerm + gobHeightTerm;

    cupva::device::priv::vpuAssert(((0xFFFFFFFFFFFFFFFFULL) - surfData.pointer.base) >= surfData.pointer.offset);
    ExtMemIova const vaVal  = surfData.pointer.base + surfData.pointer.offset;
    uint32_t const vaAddrLo = cupvaIovaAddrLo(vaVal);
    // blBaddr needs bits 13:9, plus set bit 8 to indicate BL mode, to be shifted to bit 40
    uint32_t const blMetadata = (vaAddrLo & cupva::device::priv::blSbadrIovaMask) | cupva::device::priv::blMetadataFlag;
    uint64_t const blMetadataPacked = static_cast<uint64_t>(blMetadata)
                                      << (BL_ADDR_METADATA_SHIFT - BL_METADATA_FLAG_BIT);

    uint32_t const packOffset = (x & cupva::device::priv::blGobPacketMask) * cupva::device::priv::blGobPacketStride;
    uint32_t const subpackOffset =
        ((y & cupva::device::priv::blGobSubpacketVerticalMask) * cupva::device::priv::blGobSubpacketVerticalStride) +
        ((x & cupva::device::priv::blGobSubpacketHorizontalMask) * cupva::device::priv::blGobSubpacketHorizontalStride);
    uint32_t const secOffset =
        ((y & cupva::device::priv::blGobSectorVerticalMask) * cupva::device::priv::blGobSectorVerticalStride) +
        (x & cupva::device::priv::blGobSectorHorizontalMask);
    uint64_t const gobOffset =
        static_cast<uint64_t>(packOffset) + static_cast<uint64_t>(subpackOffset) + static_cast<uint64_t>(secOffset);
    uint64_t const swizzleBit =
        ((CUPVA_BUILD_MODE == CUPVA_QNX || CUPVA_BUILD_MODE == CUPVA_L4T) && CUPVA_PVA_GEN_NUMBER <= 2)
            ? (1ULL << BL_SWIZZLE_BIT)
            : 0ULL;
    // blMetadataPacked occupies bits [32,45], swizzleBit is bit 39 — sum cannot overflow
    uint64_t const blSwizzle = blMetadataPacked + swizzleBit;
    cupva::device::priv::vpuAssert((blSwizzle <= (0xFFFFFFFFFFFFFFFFULL - gobBase)));
    uint64_t const blSwizzleBase = blSwizzle + gobBase;
    cupva::device::priv::vpuAssert((blSwizzleBase <= (0xFFFFFFFFFFFFFFFFULL - gobOffset)));
    uint64_t const BLOffset = blSwizzleBase + gobOffset;
    cupva::device::priv::vpuAssert(((0xFFFFFFFFFFFFFFFFULL) / static_cast<uint64_t>(surfData.metadata.linePitch)) >=
                                   static_cast<uint64_t>(y));
    cupva::device::priv::vpuAssert(((0xFFFFFFFFFFFFFFFFULL) - (static_cast<uint64_t>(surfData.metadata.linePitch) *
                                                               static_cast<uint64_t>(y))) >= static_cast<uint64_t>(x));
    uint64_t const PLOffset =
        (static_cast<uint64_t>(y) * static_cast<uint64_t>(surfData.metadata.linePitch)) + static_cast<uint64_t>(x);
    uint64_t const offset = (surfData.metadata.format == 1U) ? BLOffset : PLOffset;

    cupva::device::priv::vpuAssert((vaVal <= (0xFFFFFFFFFFFFFFFFULL - offset)));
    return (vaVal + offset);
}

inline vintx cupvaSurfaceAddress2D(VPUSurfaceData const &surfData, dvintx coords)
{
    cupva::device::priv::vpuAssert(surfData.metadata.linePitch > 0U);
    cupva::device::priv::vpuAssert((static_cast<uint32_t>(surfData.metadata.blockHeightLog2) <= 5U));
    vintx x = coords.hi;
    vintx y = coords.lo;

    cupva::device::priv::vpuAssert(((0xFFFFFFFFFFFFFFFFULL) - surfData.pointer.base) >= surfData.pointer.offset);
    ExtMemIova const vaVal  = surfData.pointer.base + surfData.pointer.offset;
    uint32_t const vaAddrLo = cupvaIovaAddrLo(vaVal);
    uint8_t const vaAddrHi  = cupvaIovaAddrHi(vaVal);
    // blBaddr needs bits 13:9, plus set bit 8 to indicate BL mode, to be shifted to bit 40
    uint32_t const blMetadata = (vaAddrLo & cupva::device::priv::blSbadrIovaMask) | cupva::device::priv::blMetadataFlag;
    vintx blMetadataPacked    = replicatew(blMetadata)
                             << static_cast<int32_t>(BL_ADDR_METADATA_SHIFT - BL_METADATA_FLAG_BIT);

    vintx vBLOffset =
        cupvaBlocklinearOffset2D(coords.hi, coords.lo, surfData.metadata.linePitch, surfData.metadata.blockHeightLog2);

    vBLOffset       = vBLOffset + blMetadataPacked;
    vintx vPLOffset = vmaddwhw(y, replicatew(surfData.metadata.linePitch), x, 0, 1);
    vintx voffset   = vmux(replicatew(static_cast<int32_t>(surfData.metadata.format)), vBLOffset, vPLOffset);
    vintx vBaseAddr = replicatew(vaAddrLo) | (replicatew(static_cast<int32_t>(vaAddrHi)) << 32);

    return (vBaseAddr + voffset);
}

void cupvaFloatingPointNANErrorEnabled(bool enable);

void cupvaICachePrefetch(uintptr_t addr_in_words, uint32_t size);

void cupvaAllowDataFlowActiveAfterVpuExit();

#endif // CUPVA_DEVICE_H