dc1293d32fc2ba7b7fe20a968698646fbe7fe75d
[alexxy/gromacs.git] / src / gromacs / gpu_utils / gpu_utils_ocl.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015,2016,2017, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  *  \brief Define functions for detection and initialization for OpenCL devices.
37  *
38  *  \author Anca Hamuraru <anca@streamcomputing.eu>
39  *  \author Dimitrios Karkoulis <dimitris.karkoulis@gmail.com>
40  *  \author Teemu Virolainen <teemu@streamcomputing.eu>
41  */
42
43 #include "gmxpre.h"
44
45 #include <assert.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #ifdef __APPLE__
50 #    include <sys/sysctl.h>
51 #endif
52
53 #include <memory.h>
54
55 #include "gromacs/gpu_utils/gpu_utils.h"
56 #include "gromacs/gpu_utils/ocl_compiler.h"
57 #include "gromacs/gpu_utils/oclutils.h"
58 #include "gromacs/hardware/hw_info.h"
59 #include "gromacs/mdtypes/md_enums.h"
60 #include "gromacs/utility/cstringutil.h"
61 #include "gromacs/utility/fatalerror.h"
62 #include "gromacs/utility/smalloc.h"
63 #include "gromacs/utility/stringutil.h"
64
65 /*! \brief Helper macro for error handling */
66 #define CALLOCLFUNC_LOGERROR(func, err_str, retval) { \
67         cl_int opencl_ret = func; \
68         if (CL_SUCCESS != opencl_ret) \
69         { \
70             sprintf(err_str, "OpenCL error %d", opencl_ret); \
71             retval = -1; \
72         } \
73         else{ \
74             retval = 0; } \
75 }
76
77
78 /*! \brief Return true if executing on compatible OS for AMD OpenCL.
79  *
80  * This is assumed to be true for OS X version of at least 10.10.4 and
81  * all other OS flavors.
82  *
83  * Uses the BSD sysctl() interfaces to extract the kernel version.
84  *
85  * \return true if version is 14.4 or later (= OS X version 10.10.4),
86  *         or OS is not Darwin.
87  */
88 static bool
89 runningOnCompatibleOSForAmd()
90 {
91 #ifdef __APPLE__
92     int    mib[2];
93     char   kernelVersion[256];
94     size_t len = sizeof(kernelVersion);
95
96     mib[0] = CTL_KERN;
97     mib[1] = KERN_OSRELEASE;
98
99     sysctl(mib, sizeof(mib)/sizeof(mib[0]), kernelVersion, &len, NULL, 0);
100
101     int major = strtod(kernelVersion, NULL);
102     int minor = strtod(strchr(kernelVersion, '.')+1, NULL);
103
104     // Kernel 14.4 corresponds to OS X 10.10.4
105     return (major > 14 || (major == 14 && minor >= 4));
106 #else
107     return true;
108 #endif
109 }
110
111 /*! \brief Returns true if the gpu characterized by the device properties is
112  *  supported by the native gpu acceleration.
113  * \returns             true if the GPU properties passed indicate a compatible
114  *                      GPU, otherwise false.
115  */
116 static int is_gmx_supported_gpu_id(struct gmx_device_info_t *ocl_gpu_device)
117 {
118     if ((getenv("GMX_OCL_DISABLE_COMPATIBILITY_CHECK")) != NULL)
119     {
120         return egpuCompatible;
121     }
122
123     /* Only AMD and NVIDIA GPUs are supported for now */
124     switch (ocl_gpu_device->vendor_e)
125     {
126         case OCL_VENDOR_NVIDIA:
127             return egpuCompatible;
128         case OCL_VENDOR_AMD:
129             return runningOnCompatibleOSForAmd() ? egpuCompatible : egpuIncompatible;
130         default:
131             return egpuIncompatible;
132     }
133 }
134
135
136 /*! \brief Returns an ocl_vendor_id_t value corresponding to the input OpenCL vendor name.
137  *
138  *  \param[in] vendor_name String with OpenCL vendor name.
139  *  \returns               ocl_vendor_id_t value for the input vendor_name
140  */
141 static ocl_vendor_id_t get_vendor_id(char *vendor_name)
142 {
143     if (vendor_name)
144     {
145         if (strstr(vendor_name, "NVIDIA"))
146         {
147             return OCL_VENDOR_NVIDIA;
148         }
149         else
150         if (strstr(vendor_name, "AMD") ||
151             strstr(vendor_name, "Advanced Micro Devices"))
152         {
153             return OCL_VENDOR_AMD;
154         }
155         else
156         if (strstr(vendor_name, "Intel"))
157         {
158             return OCL_VENDOR_INTEL;
159         }
160     }
161     return OCL_VENDOR_UNKNOWN;
162 }
163
164
165 //! This function is documented in the header file
166 bool canDetectGpus()
167 {
168     cl_uint numPlatforms;
169     cl_int  status       = clGetPlatformIDs(0, nullptr, &numPlatforms);
170     GMX_ASSERT(status != CL_INVALID_VALUE, "Incorrect call of clGetPlatformIDs detected");
171     if (status == CL_PLATFORM_NOT_FOUND_KHR)
172     {
173         // No valid ICDs found
174         return false;
175     }
176     GMX_RELEASE_ASSERT(status == CL_SUCCESS,
177                        gmx::formatString("An unexpected value was returned from clGetPlatformIDs %u: %s",
178                                          status, ocl_get_error_string(status).c_str()).c_str());
179     bool foundPlatform = (numPlatforms > 0);
180     return foundPlatform;
181 }
182
183 //! This function is documented in the header file
184 int detect_gpus(gmx_gpu_info_t *gpu_info, char *err_str)
185 {
186     int             retval;
187     cl_uint         ocl_platform_count;
188     cl_platform_id *ocl_platform_ids;
189     cl_device_type  req_dev_type = CL_DEVICE_TYPE_GPU;
190
191     retval           = 0;
192     ocl_platform_ids = NULL;
193
194     if (getenv("GMX_OCL_FORCE_CPU") != NULL)
195     {
196         req_dev_type = CL_DEVICE_TYPE_CPU;
197     }
198
199     while (1)
200     {
201         CALLOCLFUNC_LOGERROR(clGetPlatformIDs(0, NULL, &ocl_platform_count), err_str, retval)
202         if (0 != retval)
203         {
204             break;
205         }
206
207         if (1 > ocl_platform_count)
208         {
209             break;
210         }
211
212         snew(ocl_platform_ids, ocl_platform_count);
213
214         CALLOCLFUNC_LOGERROR(clGetPlatformIDs(ocl_platform_count, ocl_platform_ids, NULL), err_str, retval)
215         if (0 != retval)
216         {
217             break;
218         }
219
220         for (unsigned int i = 0; i < ocl_platform_count; i++)
221         {
222             cl_uint ocl_device_count;
223
224             /* If requesting req_dev_type devices fails, just go to the next platform */
225             if (CL_SUCCESS != clGetDeviceIDs(ocl_platform_ids[i], req_dev_type, 0, NULL, &ocl_device_count))
226             {
227                 continue;
228             }
229
230             if (1 <= ocl_device_count)
231             {
232                 gpu_info->n_dev += ocl_device_count;
233             }
234         }
235
236         if (1 > gpu_info->n_dev)
237         {
238             break;
239         }
240
241         snew(gpu_info->gpu_dev, gpu_info->n_dev);
242
243         {
244             int           device_index;
245             cl_device_id *ocl_device_ids;
246
247             snew(ocl_device_ids, gpu_info->n_dev);
248             device_index = 0;
249
250             for (unsigned int i = 0; i < ocl_platform_count; i++)
251             {
252                 cl_uint ocl_device_count;
253
254                 /* If requesting req_dev_type devices fails, just go to the next platform */
255                 if (CL_SUCCESS != clGetDeviceIDs(ocl_platform_ids[i], req_dev_type, gpu_info->n_dev, ocl_device_ids, &ocl_device_count))
256                 {
257                     continue;
258                 }
259
260                 if (1 > ocl_device_count)
261                 {
262                     break;
263                 }
264
265                 for (unsigned int j = 0; j < ocl_device_count; j++)
266                 {
267                     gpu_info->gpu_dev[device_index].ocl_gpu_id.ocl_platform_id = ocl_platform_ids[i];
268                     gpu_info->gpu_dev[device_index].ocl_gpu_id.ocl_device_id   = ocl_device_ids[j];
269
270                     gpu_info->gpu_dev[device_index].device_name[0] = 0;
271                     clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_NAME, sizeof(gpu_info->gpu_dev[device_index].device_name), gpu_info->gpu_dev[device_index].device_name, NULL);
272
273                     gpu_info->gpu_dev[device_index].device_version[0] = 0;
274                     clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_VERSION, sizeof(gpu_info->gpu_dev[device_index].device_version), gpu_info->gpu_dev[device_index].device_version, NULL);
275
276                     gpu_info->gpu_dev[device_index].device_vendor[0] = 0;
277                     clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_VENDOR, sizeof(gpu_info->gpu_dev[device_index].device_vendor), gpu_info->gpu_dev[device_index].device_vendor, NULL);
278
279                     gpu_info->gpu_dev[device_index].compute_units = 0;
280                     clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(gpu_info->gpu_dev[device_index].compute_units), &(gpu_info->gpu_dev[device_index].compute_units), NULL);
281
282                     gpu_info->gpu_dev[device_index].adress_bits = 0;
283                     clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_ADDRESS_BITS, sizeof(gpu_info->gpu_dev[device_index].adress_bits), &(gpu_info->gpu_dev[device_index].adress_bits), NULL);
284
285                     gpu_info->gpu_dev[device_index].vendor_e = get_vendor_id(gpu_info->gpu_dev[device_index].device_vendor);
286
287                     gpu_info->gpu_dev[device_index].stat = is_gmx_supported_gpu_id(gpu_info->gpu_dev + device_index);
288
289                     if (egpuCompatible == gpu_info->gpu_dev[device_index].stat)
290                     {
291                         gpu_info->n_dev_compatible++;
292                     }
293
294                     device_index++;
295                 }
296             }
297
298             gpu_info->n_dev = device_index;
299
300             /* Dummy sort of devices -  AMD first, then NVIDIA, then Intel */
301             // TODO: Sort devices based on performance.
302             if (0 < gpu_info->n_dev)
303             {
304                 int last = -1;
305                 for (int i = 0; i < gpu_info->n_dev; i++)
306                 {
307                     if (OCL_VENDOR_AMD == gpu_info->gpu_dev[i].vendor_e)
308                     {
309                         last++;
310
311                         if (last < i)
312                         {
313                             gmx_device_info_t ocl_gpu_info;
314                             ocl_gpu_info            = gpu_info->gpu_dev[i];
315                             gpu_info->gpu_dev[i]    = gpu_info->gpu_dev[last];
316                             gpu_info->gpu_dev[last] = ocl_gpu_info;
317                         }
318                     }
319                 }
320
321                 /* if more than 1 device left to be sorted */
322                 if ((gpu_info->n_dev - 1 - last) > 1)
323                 {
324                     for (int i = 0; i < gpu_info->n_dev; i++)
325                     {
326                         if (OCL_VENDOR_NVIDIA == gpu_info->gpu_dev[i].vendor_e)
327                         {
328                             last++;
329
330                             if (last < i)
331                             {
332                                 gmx_device_info_t ocl_gpu_info;
333                                 ocl_gpu_info            = gpu_info->gpu_dev[i];
334                                 gpu_info->gpu_dev[i]    = gpu_info->gpu_dev[last];
335                                 gpu_info->gpu_dev[last] = ocl_gpu_info;
336                             }
337                         }
338                     }
339                 }
340             }
341
342             sfree(ocl_device_ids);
343         }
344
345         break;
346     }
347
348     sfree(ocl_platform_ids);
349
350     return retval;
351 }
352
353 //! This function is documented in the header file
354 void free_gpu_info(const gmx_gpu_info_t gmx_unused *gpu_info)
355 {
356     if (gpu_info == NULL)
357     {
358         return;
359     }
360
361     sfree(gpu_info->gpu_dev);
362 }
363
364 //! This function is documented in the header file
365 std::vector<int> getCompatibleGpus(const gmx_gpu_info_t &gpu_info)
366 {
367     // Possible minor over-allocation here, but not important for anything
368     std::vector<int> compatibleGpus;
369     compatibleGpus.reserve(gpu_info.n_dev);
370     for (int i = 0; i < gpu_info.n_dev; i++)
371     {
372         assert(gpu_info.gpu_dev);
373         if (gpu_info.gpu_dev[i].stat == egpuCompatible)
374         {
375             compatibleGpus.push_back(i);
376         }
377     }
378     return compatibleGpus;
379 }
380
381 //! This function is documented in the header file
382 const char *getGpuCompatibilityDescription(const gmx_gpu_info_t &gpu_info,
383                                            int                   index)
384 {
385     return (index >= gpu_info.n_dev ?
386             gpu_detect_res_str[egpuNonexistent] :
387             gpu_detect_res_str[gpu_info.gpu_dev[index].stat]);
388 }
389
390 //! This function is documented in the header file
391 void get_gpu_device_info_string(char *s, const gmx_gpu_info_t &gpu_info, int index)
392 {
393     assert(s);
394
395     if (index < 0 && index >= gpu_info.n_dev)
396     {
397         return;
398     }
399
400     gmx_device_info_t  *dinfo = &gpu_info.gpu_dev[index];
401
402     bool                bGpuExists =
403         dinfo->stat == egpuCompatible ||
404         dinfo->stat == egpuIncompatible;
405
406     if (!bGpuExists)
407     {
408         sprintf(s, "#%d: %s, stat: %s",
409                 index, "N/A",
410                 gpu_detect_res_str[dinfo->stat]);
411     }
412     else
413     {
414         sprintf(s, "#%d: name: %s, vendor: %s, device version: %s, stat: %s",
415                 index, dinfo->device_name, dinfo->device_vendor,
416                 dinfo->device_version,
417                 gpu_detect_res_str[dinfo->stat]);
418     }
419 }
420
421 //! This function is documented in the header file
422 void init_gpu(const gmx::MDLogger               & /*mdlog*/,
423               gmx_device_info_t                *deviceInfo)
424 {
425     assert(deviceInfo);
426
427     // If the device is NVIDIA, for safety reasons we disable the JIT
428     // caching as this is known to be broken at least until driver 364.19;
429     // the cache does not always get regenerated when the source code changes,
430     // e.g. if the path to the kernel sources remains the same
431
432     if (deviceInfo->vendor_e == OCL_VENDOR_NVIDIA)
433     {
434         // Ignore return values, failing to set the variable does not mean
435         // that something will go wrong later.
436 #ifdef _MSC_VER
437         _putenv("CUDA_CACHE_DISABLE=1");
438 #else
439         // Don't override, maybe a dev is testing.
440         setenv("CUDA_CACHE_DISABLE", "1", 0);
441 #endif
442     }
443 }
444
445 //! This function is documented in the header file
446 gmx_device_info_t *getDeviceInfo(const gmx_gpu_info_t &gpu_info,
447                                  int                   deviceId)
448 {
449     if (deviceId < 0 || deviceId >= gpu_info.n_dev)
450     {
451         gmx_incons("Invalid GPU deviceId requested");
452     }
453     return &gpu_info.gpu_dev[deviceId];
454 }
455
456 //! This function is documented in the header file
457 size_t sizeof_gpu_dev_info(void)
458 {
459     return sizeof(gmx_device_info_t);
460 }
461
462 void gpu_set_host_malloc_and_free(bool               bUseGpuKernels,
463                                   gmx_host_alloc_t **nb_alloc,
464                                   gmx_host_free_t  **nb_free)
465 {
466     if (bUseGpuKernels)
467     {
468         *nb_alloc = &ocl_pmalloc;
469         *nb_free  = &ocl_pfree;
470     }
471     else
472     {
473         *nb_alloc = NULL;
474         *nb_free  = NULL;
475     }
476 }