xref: /libCEED/backends/cuda/ceed-cuda-common.c (revision 4febb80102c5c87c6a273a85e30d4673d8552be6)
1 // Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and other CEED contributors.
2 // All Rights Reserved. See the top-level LICENSE and NOTICE files for details.
3 //
4 // SPDX-License-Identifier: BSD-2-Clause
5 //
6 // This file is part of CEED:  http://github.com/ceed
7 
8 #include "ceed-cuda-common.h"
9 
10 #include <ceed.h>
11 #include <ceed/backend.h>
12 #include <cublas_v2.h>
13 #include <cuda_runtime.h>
14 #include <stdlib.h>
15 #include <string.h>
16 
17 //------------------------------------------------------------------------------
18 // Get root resource without device spec
19 //------------------------------------------------------------------------------
20 int CeedCudaGetResourceRoot(Ceed ceed, const char *resource, char **resource_root) {
21   char  *device_spec       = strstr(resource, ":device_id=");
22   size_t resource_root_len = device_spec ? (size_t)(device_spec - resource) + 1 : strlen(resource) + 1;
23   CeedCallBackend(CeedCalloc(resource_root_len, resource_root));
24   memcpy(*resource_root, resource, resource_root_len - 1);
25 
26   return CEED_ERROR_SUCCESS;
27 }
28 
29 //------------------------------------------------------------------------------
30 // Device information backend init
31 //------------------------------------------------------------------------------
32 int CeedCudaInit(Ceed ceed, const char *resource) {
33   const char *device_spec = strstr(resource, ":device_id=");
34   const int   device_id   = (device_spec) ? atoi(device_spec + 11) : -1;
35 
36   int current_device_id;
37   CeedCallCuda(ceed, cudaGetDevice(&current_device_id));
38   if (device_id >= 0 && current_device_id != device_id) {
39     CeedCallCuda(ceed, cudaSetDevice(device_id));
40     current_device_id = device_id;
41   }
42   Ceed_Cuda *data;
43   CeedCallBackend(CeedGetData(ceed, &data));
44   data->device_id = current_device_id;
45   CeedCallCuda(ceed, cudaGetDeviceProperties(&data->device_prop, current_device_id));
46   return CEED_ERROR_SUCCESS;
47 }
48 
49 //------------------------------------------------------------------------------
50 // Backend destroy
51 //------------------------------------------------------------------------------
52 int CeedDestroy_Cuda(Ceed ceed) {
53   Ceed_Cuda *data;
54   CeedCallBackend(CeedGetData(ceed, &data));
55   if (data->cublas_handle) CeedCallCublas(ceed, cublasDestroy(data->cublas_handle));
56   CeedCallBackend(CeedFree(&data));
57   return CEED_ERROR_SUCCESS;
58 }
59 
60 //------------------------------------------------------------------------------
61