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 250560 : void offload_create_buffer(const int length, offload_buffer **buffer) { 21 250560 : const size_t requested_size = sizeof(double) * length; 22 : 23 250560 : if (*buffer != NULL) { 24 10692 : if ((*buffer)->size >= requested_size) { 25 : return; // reuse existing buffer 26 : } else { 27 50 : offload_free_buffer(*buffer); 28 : } 29 : } 30 : 31 239918 : (*buffer) = malloc(sizeof(offload_buffer)); 32 239918 : (*buffer)->size = requested_size; 33 239918 : (*buffer)->host_buffer = NULL; 34 239918 : (*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 239918 : (*buffer)->host_buffer = malloc(requested_size); 41 239918 : (*buffer)->device_buffer = NULL; 42 : #endif 43 239918 : 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 239918 : void offload_free_buffer(offload_buffer *buffer) { 53 239918 : if (NULL == buffer) 54 : return; 55 : #if defined(__OFFLOAD) 56 : offloadFreeHost(buffer->host_buffer); 57 : offloadFree(buffer->device_buffer); 58 : #else 59 239918 : free(buffer->host_buffer); 60 : #endif 61 239918 : free(buffer); 62 : } 63 : 64 : /******************************************************************************* 65 : * \brief Returns a pointer to the host buffer. 66 : * \author Ole Schuett 67 : ******************************************************************************/ 68 249668 : double *offload_get_buffer_host_pointer(offload_buffer *buffer) { 69 249668 : assert(NULL != buffer); 70 249668 : return buffer->host_buffer; 71 : } 72 : 73 : // EOF