Line data Source code
1 : /*----------------------------------------------------------------------------*/ 2 : /* CP2K: A general program to perform molecular dynamics simulations */ 3 : /* Copyright 2000-2024 CP2K developers group <https://cp2k.org> */ 4 : /* */ 5 : /* SPDX-License-Identifier: BSD-3-Clause */ 6 : /*----------------------------------------------------------------------------*/ 7 : 8 : #include <assert.h> 9 : #include <stdio.h> 10 : #include <stdlib.h> 11 : 12 : #include "offload_buffer.h" 13 : #include "offload_library.h" 14 : #include "offload_runtime.h" 15 : 16 : /******************************************************************************* 17 : * \brief Allocates a buffer of given length, ie., number of elements. 18 : * \author Ole Schuett 19 : ******************************************************************************/ 20 261862 : void offload_create_buffer(const int length, offload_buffer **buffer) { 21 261862 : const size_t requested_size = sizeof(double) * length; 22 : 23 261862 : if (*buffer != NULL) { 24 10772 : if ((*buffer)->size >= requested_size) { 25 : return; // reuse existing buffer 26 : } else { 27 50 : offload_free_buffer(*buffer); 28 : } 29 : } 30 : 31 251140 : (*buffer) = malloc(sizeof(offload_buffer)); 32 251140 : (*buffer)->size = requested_size; 33 251140 : (*buffer)->host_buffer = NULL; 34 251140 : (*buffer)->device_buffer = NULL; 35 : #if defined(__OFFLOAD) 36 : offload_activate_chosen_device(); 37 : offloadMallocHost((void **)&(*buffer)->host_buffer, requested_size); 38 : offloadMalloc((void **)&(*buffer)->device_buffer, requested_size); 39 : #else 40 251140 : (*buffer)->host_buffer = malloc(requested_size); 41 251140 : (*buffer)->device_buffer = NULL; 42 : #endif 43 251140 : if (NULL == (*buffer)->host_buffer) { /* unified memory */ 44 0 : (*buffer)->host_buffer = (*buffer)->device_buffer; 45 : } 46 : } 47 : 48 : /******************************************************************************* 49 : * \brief Deallocate given buffer. 50 : * \author Ole Schuett 51 : ******************************************************************************/ 52 251140 : void offload_free_buffer(offload_buffer *buffer) { 53 251140 : if (NULL == buffer) 54 : return; 55 : #if defined(__OFFLOAD) 56 : offloadFreeHost(buffer->host_buffer); 57 : offloadFree(buffer->device_buffer); 58 : #else 59 251140 : free(buffer->host_buffer); 60 : #endif 61 251140 : free(buffer); 62 : } 63 : 64 : /******************************************************************************* 65 : * \brief Returns a pointer to the host buffer. 66 : * \author Ole Schuett 67 : ******************************************************************************/ 68 260964 : double *offload_get_buffer_host_pointer(offload_buffer *buffer) { 69 260964 : assert(NULL != buffer); 70 260964 : return buffer->host_buffer; 71 : } 72 : 73 : // EOF