/*******************************************************************************
    Copyright (c) 2015 NVIDIA Corporation

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to
    deal in the Software without restriction, including without limitation the
    rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
    sell copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.

 *******************************************************************************/

#include "uvm_common_test.h"

static
NV_STATUS _uvmtest_get_pushbuffer(UvmChannelManager   *channelManager,
                                  UvmPushbuffer       **pushBuffer,
                                  UvmTracker          *trackerIn)
{
    NV_STATUS status =  NV_OK;

    status = uvm_get_pushbuffer(channelManager, pushBuffer);
    if (status != NV_OK)
        return status;

    if (trackerIn)
        uvm_reserve_acquire_space(channelManager, *pushBuffer, trackerIn);

    return NV_OK;
}

static
NV_STATUS _uvmtest_submit_pushbuffer(UvmPushbuffer       *pushBuffer,
                                     UvmTracker          *trackerIn,
                                     UvmTracker          *trackerOut)
{
    NV_STATUS           status =  NV_OK;
    UvmTrackerItem      trackerItem;

    uvm_submit_pushbuffer(pushBuffer->channel->pool->manager,
                          pushBuffer,
                          trackerIn,
                          &trackerItem);

    if (trackerOut)
    {
        // reset the tracker
        uvm_reset_tracker(trackerOut);
        status = uvm_grow_tracker(trackerOut, 1);
        if (status != NV_OK)
        {
            UVM_ERR_PRINT_NV_STATUS("Could not grow tracker.", status);
            return status;
        }
        status = uvm_merge_tracker_item(trackerOut, &trackerItem);
        if (status != NV_OK)
        {
            UVM_ERR_PRINT_NV_STATUS("Could not merge tracker item.", status);
            return status;
        }
    }
    else
    {
        UvmTracker tempTracker;
        uvm_init_tracker(&tempTracker);
        status = uvm_grow_tracker(&tempTracker, 1);
        if (status != NV_OK)
        {
            UVM_ERR_PRINT_NV_STATUS("Could not grow tracker", status);
            return status;
        }
        status = uvm_merge_tracker_item(&tempTracker, &trackerItem);
        if (status != NV_OK)
        {
            UVM_ERR_PRINT_NV_STATUS("Could not merge tracker item.", status);
            return status;
        }
        status = uvm_wait_for_tracker(&tempTracker);
        if (status != NV_OK)
        {
            UVM_ERR_PRINT_NV_STATUS("Could not wait for tracker", status);
            return status;
        }

        if (uvm_shrink_tracker(&tempTracker))
            UVM_ERR_PRINT("tracker state not as expected.");
    }
    return NV_OK;
}

NV_STATUS uvmtest_memcpy_virt(UvmChannelManager   *channelManager,
                              UvmGpuPointer       dst,
                              UvmGpuPointer       src,
                              NvU64               size,
                              UvmTracker          *trackerIn,
                              UvmTracker          *trackerOut)
{
    NV_STATUS           status =  NV_OK;
    NvU32               ret;
    UvmPushbuffer       *pushBuffer;

    status = _uvmtest_get_pushbuffer(channelManager, &pushBuffer, trackerIn);
    if (NV_OK != status)
        return status;

    UVM_PUSH_METHOD(ret, pushBuffer,
                    pushBuffer->channel->ceOps.launchDma,
                    src, 0,
                    dst, 0,
                    size,
                    NV_UVM_COPY_SRC_TYPE_VIRTUAL |
                    NV_UVM_COPY_DST_TYPE_VIRTUAL);
    if (!ret)
    {
        UVM_ERR_PRINT_NV_STATUS("Could not push copy method to pb.", status);
        return NV_ERR_NO_MEMORY;
    }

    return _uvmtest_submit_pushbuffer(pushBuffer, trackerIn, trackerOut);
}

NV_STATUS uvmtest_inline_memcpy_virt(UvmChannelManager   *channelManager,
                                     UvmGpuPointer       dst,
                                     const void*         src,
                                     NvU64               size,
                                     UvmTracker          *trackerIn,
                                     UvmTracker          *trackerOut)
{
    NV_STATUS           status =  NV_OK;
    NvU32               ret;
    UvmPushbuffer       *pushBuffer;
    UvmPbInlineRegion   copyRegion = {0};

    status = _uvmtest_get_pushbuffer(channelManager, &pushBuffer, trackerIn);
    if (NV_OK != status)
        return status;

    // Create an inline region in the pushbuffer and fill it with data
    uvm_pushbuffer_inline_start(pushBuffer, &copyRegion);
    copyRegion.size = size;
    memcpy((void*)copyRegion.regionStart, src, size);
    uvm_pushbuffer_inline_end(pushBuffer, &copyRegion);

    // Now push a copy using the previously create inline region
    copyRegion.copy.bValid = NV_TRUE;
    copyRegion.copy.copySize = size;
    copyRegion.copy.dstAddr = dst;
    copyRegion.copy.dstAperture = 0;
    copyRegion.copy.dstCopyFlags = 0;
    ret = uvm_pushbuffer_copy_region(pushBuffer, &copyRegion);
    if (!ret)
    {
        UVM_ERR_PRINT_NV_STATUS("Could not push copy method to pb.", status);
        return NV_ERR_NO_MEMORY;
    }

    return _uvmtest_submit_pushbuffer(pushBuffer, trackerIn, trackerOut);
}

NV_STATUS uvmtest_alloc_virt_cpu(uvmGpuAddressSpaceHandle     hVaSpace,
                                 UvmtestMemblock              *memblock,
                                 NvU64                        size,
                                 enum UvmtestMemblockMapping  map)
{
    NV_STATUS status = NV_OK;

    memset(memblock, 0, sizeof(*memblock));

    status = nvUvmInterfaceMemoryAllocSys(hVaSpace,
                                          size,
                                          &(memblock->gpu),
                                          NULL);
    if (NV_OK != status)
    {
        UVM_ERR_PRINT_NV_STATUS("Could not allocate SYSMEM region", status);
        memset(memblock, 0, sizeof(*memblock));
        return status;
    }

    if (map & MAP_CPU)
    {
        status = nvUvmInterfaceMemoryCpuMap(hVaSpace,
                                            memblock->gpu,
                                            size,
                                            &(memblock->cpu),
                                            UVM_PAGE_SIZE_DEFAULT);
        if (NV_OK != status)
        {
            UVM_ERR_PRINT_NV_STATUS("Could not map GPU mem to CPU VA.", status);
            nvUvmInterfaceMemoryFree(hVaSpace, memblock->gpu);
            memset(memblock, 0, sizeof(*memblock));
            return status;
        }
    }

    memblock->hVaSpace = hVaSpace;
    memblock->size = size;
    memblock->location = MEMBLOCK_CPU;
    return NV_OK;
}

NV_STATUS uvmtest_alloc_virt_gpu(uvmGpuAddressSpaceHandle     hVaSpace,
                                 UvmtestMemblock              *memblock,
                                 NvU64                        size,
                                 enum UvmtestMemblockMapping  map)
{
    NV_STATUS status = NV_OK;

    memset(memblock, 0, sizeof(*memblock));

    status = nvUvmInterfaceMemoryAllocFB(hVaSpace,
                                         size,
                                         &(memblock->gpu),
                                         NULL);
    if (NV_OK != status)
    {
        UVM_ERR_PRINT_NV_STATUS("Could not allocate VIDMEM region", status);
        return status;
    }

    if (map & MAP_CPU)
    {
        status = nvUvmInterfaceMemoryCpuMap(hVaSpace,
                                            memblock->gpu,
                                            size,
                                            &(memblock->cpu),
                                            UVM_PAGE_SIZE_DEFAULT);
        if (NV_OK != status)
        {
            UVM_ERR_PRINT_NV_STATUS("Could not map VIDMEM to CPU VA.", status);
            nvUvmInterfaceMemoryFree(hVaSpace, memblock->gpu);
            memset(memblock, 0, sizeof(*memblock));
            return status;
        }
    }

    memblock->hVaSpace = hVaSpace;
    memblock->size = size;
    memblock->location = MEMBLOCK_GPU;
    return NV_OK;
}

void uvmtest_free_virt(UvmtestMemblock *memblock)
{
    if (memblock && memblock->gpu)
        nvUvmInterfaceMemoryFree(memblock->hVaSpace, memblock->gpu);
}
