2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2012,2013,2014,2015,2016,2017,2018,2019, 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.
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.
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.
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.
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.
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.
36 * \brief Define functions for detection and initialization for OpenCL devices.
38 * \author Anca Hamuraru <anca@streamcomputing.eu>
39 * \author Dimitrios Karkoulis <dimitris.karkoulis@gmail.com>
40 * \author Teemu Virolainen <teemu@streamcomputing.eu>
41 * \author Mark Abraham <mark.j.abraham@gmail.com>
42 * \author Szilárd Páll <pall.szilard@gmail.com>
56 # include <sys/sysctl.h>
61 #include "gromacs/gpu_utils/gpu_utils.h"
62 #include "gromacs/gpu_utils/ocl_compiler.h"
63 #include "gromacs/gpu_utils/oclraii.h"
64 #include "gromacs/gpu_utils/oclutils.h"
65 #include "gromacs/hardware/hw_info.h"
66 #include "gromacs/utility/cstringutil.h"
67 #include "gromacs/utility/exceptions.h"
68 #include "gromacs/utility/fatalerror.h"
69 #include "gromacs/utility/smalloc.h"
70 #include "gromacs/utility/stringutil.h"
72 /*! \brief Return true if executing on compatible OS for AMD OpenCL.
74 * This is assumed to be true for OS X version of at least 10.10.4 and
75 * all other OS flavors.
77 * Uses the BSD sysctl() interfaces to extract the kernel version.
79 * \return true if version is 14.4 or later (= OS X version 10.10.4),
80 * or OS is not Darwin.
82 static bool runningOnCompatibleOSForAmd()
86 char kernelVersion[256];
87 size_t len = sizeof(kernelVersion);
90 mib[1] = KERN_OSRELEASE;
92 sysctl(mib, sizeof(mib) / sizeof(mib[0]), kernelVersion, &len, NULL, 0);
94 int major = strtod(kernelVersion, NULL);
95 int minor = strtod(strchr(kernelVersion, '.') + 1, NULL);
97 // Kernel 14.4 corresponds to OS X 10.10.4
98 return (major > 14 || (major == 14 && minor >= 4));
107 /*! \brief Make an error string following an OpenCL API call.
109 * It is meant to be called with \p status != CL_SUCCESS, but it will
110 * work correctly even if it is called with no OpenCL failure.
112 * \param[in] message Supplies context, e.g. the name of the API call that returned the error.
113 * \param[in] status OpenCL API status code
114 * \returns A string describing the OpenCL error.
116 static std::string makeOpenClInternalErrorString(const char* message, cl_int status)
118 if (message != nullptr)
120 return formatString("%s did %ssucceed %d: %s", message, ((status != CL_SUCCESS) ? "not " : ""),
121 status, ocl_get_error_string(status).c_str());
125 return formatString("%sOpenCL error encountered %d: %s", ((status != CL_SUCCESS) ? "" : "No "),
126 status, ocl_get_error_string(status).c_str());
131 * \brief Checks that device \c devInfo is sane (ie can run a kernel).
133 * Compiles and runs a dummy kernel to determine whether the given
134 * OpenCL device functions properly.
137 * \param[in] devInfo The device info pointer.
138 * \param[out] errorMessage An error message related to a failing OpenCL API call.
139 * \throws std::bad_alloc When out of memory.
140 * \returns Whether the device passed sanity checks
142 static bool isDeviceSane(const gmx_device_info_t* devInfo, std::string* errorMessage)
144 cl_context_properties properties[] = {
145 CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(devInfo->ocl_gpu_id.ocl_platform_id), 0
147 // uncrustify spacing
150 auto deviceId = devInfo->ocl_gpu_id.ocl_device_id;
151 ClContext context(clCreateContext(properties, 1, &deviceId, nullptr, nullptr, &status));
152 if (status != CL_SUCCESS)
154 errorMessage->assign(makeOpenClInternalErrorString("clCreateContext", status));
157 ClCommandQueue commandQueue(clCreateCommandQueue(context, deviceId, 0, &status));
158 if (status != CL_SUCCESS)
160 errorMessage->assign(makeOpenClInternalErrorString("clCreateCommandQueue", status));
164 // Some compilers such as Apple's require kernel functions to have at least one argument
165 const char* lines[] = { "__kernel void dummyKernel(__global void* input){}" };
166 ClProgram program(clCreateProgramWithSource(context, 1, lines, nullptr, &status));
167 if (status != CL_SUCCESS)
169 errorMessage->assign(makeOpenClInternalErrorString("clCreateProgramWithSource", status));
173 if ((status = clBuildProgram(program, 0, nullptr, nullptr, nullptr, nullptr)) != CL_SUCCESS)
175 errorMessage->assign(makeOpenClInternalErrorString("clBuildProgram", status));
179 ClKernel kernel(clCreateKernel(program, "dummyKernel", &status));
180 if (status != CL_SUCCESS)
182 errorMessage->assign(makeOpenClInternalErrorString("clCreateKernel", status));
186 clSetKernelArg(kernel, 0, sizeof(void*), nullptr);
188 const size_t localWorkSize = 1, globalWorkSize = 1;
189 if ((status = clEnqueueNDRangeKernel(commandQueue, kernel, 1, nullptr, &globalWorkSize,
190 &localWorkSize, 0, nullptr, nullptr))
193 errorMessage->assign(makeOpenClInternalErrorString("clEnqueueNDRangeKernel", status));
200 * \brief Checks that device \c devInfo is compatible with GROMACS.
202 * Vendor and OpenCL version support checks are executed an the result
205 * \param[in] devInfo The device info pointer.
206 * \returns The result of the compatibility checks.
208 static int isDeviceSupported(const gmx_device_info_t* devInfo)
210 if (getenv("GMX_OCL_DISABLE_COMPATIBILITY_CHECK") != nullptr)
212 // Assume the device is compatible because checking has been disabled.
213 return egpuCompatible;
216 // OpenCL device version check, ensure >= REQUIRED_OPENCL_MIN_VERSION
217 constexpr unsigned int minVersionMajor = REQUIRED_OPENCL_MIN_VERSION_MAJOR;
218 constexpr unsigned int minVersionMinor = REQUIRED_OPENCL_MIN_VERSION_MINOR;
220 // Based on the OpenCL spec we're checking the version supported by
221 // the device which has the following format:
222 // OpenCL<space><major_version.minor_version><space><vendor-specific information>
223 unsigned int deviceVersionMinor, deviceVersionMajor;
224 const int valuesScanned = std::sscanf(devInfo->device_version, "OpenCL %u.%u",
225 &deviceVersionMajor, &deviceVersionMinor);
226 const bool versionLargeEnough =
227 ((valuesScanned == 2)
228 && ((deviceVersionMajor > minVersionMajor)
229 || (deviceVersionMajor == minVersionMajor && deviceVersionMinor >= minVersionMinor)));
230 if (!versionLargeEnough)
232 return egpuIncompatible;
235 /* Only AMD, Intel, and NVIDIA GPUs are supported for now */
236 switch (devInfo->vendor_e)
238 case OCL_VENDOR_NVIDIA: return egpuCompatible;
240 return runningOnCompatibleOSForAmd() ? egpuCompatible : egpuIncompatible;
241 case OCL_VENDOR_INTEL:
242 return GMX_OPENCL_NB_CLUSTER_SIZE == 4 ? egpuCompatible : egpuIncompatibleClusterSize;
243 default: return egpuIncompatible;
248 /*! \brief Check whether the \c ocl_gpu_device is suitable for use by mdrun
250 * Runs sanity checks: checking that the runtime can compile a dummy kernel
251 * and this can be executed;
252 * Runs compatibility checks verifying the device OpenCL version requirement
253 * and vendor/OS support.
255 * \param[in] deviceId The runtime-reported numeric ID of the device.
256 * \param[in] deviceInfo The device info pointer.
257 * \returns An e_gpu_detect_res_t to indicate how the GPU coped with
258 * the sanity and compatibility check.
260 static int checkGpu(size_t deviceId, const gmx_device_info_t* deviceInfo)
263 int supportStatus = isDeviceSupported(deviceInfo);
264 if (supportStatus != egpuCompatible)
266 return supportStatus;
269 std::string errorMessage;
270 if (!isDeviceSane(deviceInfo, &errorMessage))
272 gmx_warning("While sanity checking device #%zu, %s", deviceId, errorMessage.c_str());
276 return egpuCompatible;
281 /*! \brief Returns an ocl_vendor_id_t value corresponding to the input OpenCL vendor name.
283 * \param[in] vendor_name String with OpenCL vendor name.
284 * \returns ocl_vendor_id_t value for the input vendor_name
286 static ocl_vendor_id_t get_vendor_id(char* vendor_name)
290 if (strstr(vendor_name, "NVIDIA"))
292 return OCL_VENDOR_NVIDIA;
294 else if (strstr(vendor_name, "AMD") || strstr(vendor_name, "Advanced Micro Devices"))
296 return OCL_VENDOR_AMD;
298 else if (strstr(vendor_name, "Intel"))
300 return OCL_VENDOR_INTEL;
303 return OCL_VENDOR_UNKNOWN;
306 bool isGpuDetectionFunctional(std::string* errorMessage)
308 cl_uint numPlatforms;
309 cl_int status = clGetPlatformIDs(0, nullptr, &numPlatforms);
310 GMX_ASSERT(status != CL_INVALID_VALUE, "Incorrect call of clGetPlatformIDs detected");
312 if (status == CL_PLATFORM_NOT_FOUND_KHR)
314 // No valid ICDs found
315 if (errorMessage != nullptr)
317 errorMessage->assign("No valid OpenCL driver found");
323 status == CL_SUCCESS,
324 gmx::formatString("An unexpected value was returned from clGetPlatformIDs %d: %s",
325 status, ocl_get_error_string(status).c_str())
327 bool foundPlatform = (numPlatforms > 0);
328 if (!foundPlatform && errorMessage != nullptr)
330 errorMessage->assign("No OpenCL platforms found even though the driver was valid");
332 return foundPlatform;
335 void findGpus(gmx_gpu_info_t* gpu_info)
337 cl_uint ocl_platform_count;
338 cl_platform_id* ocl_platform_ids;
339 cl_device_type req_dev_type = CL_DEVICE_TYPE_GPU;
341 ocl_platform_ids = nullptr;
343 if (getenv("GMX_OCL_FORCE_CPU") != nullptr)
345 req_dev_type = CL_DEVICE_TYPE_CPU;
350 cl_int status = clGetPlatformIDs(0, nullptr, &ocl_platform_count);
351 if (CL_SUCCESS != status)
353 GMX_THROW(gmx::InternalError(
354 gmx::formatString("An unexpected value %d was returned from clGetPlatformIDs: ", status)
355 + ocl_get_error_string(status)));
358 if (1 > ocl_platform_count)
360 // TODO this should have a descriptive error message that we only support one OpenCL platform
364 snew(ocl_platform_ids, ocl_platform_count);
366 status = clGetPlatformIDs(ocl_platform_count, ocl_platform_ids, nullptr);
367 if (CL_SUCCESS != status)
369 GMX_THROW(gmx::InternalError(
370 gmx::formatString("An unexpected value %d was returned from clGetPlatformIDs: ", status)
371 + ocl_get_error_string(status)));
374 for (unsigned int i = 0; i < ocl_platform_count; i++)
376 cl_uint ocl_device_count;
378 /* If requesting req_dev_type devices fails, just go to the next platform */
379 if (CL_SUCCESS != clGetDeviceIDs(ocl_platform_ids[i], req_dev_type, 0, nullptr, &ocl_device_count))
384 if (1 <= ocl_device_count)
386 gpu_info->n_dev += ocl_device_count;
390 if (1 > gpu_info->n_dev)
395 snew(gpu_info->gpu_dev, gpu_info->n_dev);
399 cl_device_id* ocl_device_ids;
401 snew(ocl_device_ids, gpu_info->n_dev);
404 for (unsigned int i = 0; i < ocl_platform_count; i++)
406 cl_uint ocl_device_count;
408 /* If requesting req_dev_type devices fails, just go to the next platform */
410 != clGetDeviceIDs(ocl_platform_ids[i], req_dev_type, gpu_info->n_dev,
411 ocl_device_ids, &ocl_device_count))
416 if (1 > ocl_device_count)
421 for (unsigned int j = 0; j < ocl_device_count; j++)
423 gpu_info->gpu_dev[device_index].ocl_gpu_id.ocl_platform_id = ocl_platform_ids[i];
424 gpu_info->gpu_dev[device_index].ocl_gpu_id.ocl_device_id = ocl_device_ids[j];
426 gpu_info->gpu_dev[device_index].device_name[0] = 0;
427 clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_NAME,
428 sizeof(gpu_info->gpu_dev[device_index].device_name),
429 gpu_info->gpu_dev[device_index].device_name, nullptr);
431 gpu_info->gpu_dev[device_index].device_version[0] = 0;
432 clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_VERSION,
433 sizeof(gpu_info->gpu_dev[device_index].device_version),
434 gpu_info->gpu_dev[device_index].device_version, nullptr);
436 gpu_info->gpu_dev[device_index].device_vendor[0] = 0;
437 clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_VENDOR,
438 sizeof(gpu_info->gpu_dev[device_index].device_vendor),
439 gpu_info->gpu_dev[device_index].device_vendor, nullptr);
441 gpu_info->gpu_dev[device_index].compute_units = 0;
442 clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_MAX_COMPUTE_UNITS,
443 sizeof(gpu_info->gpu_dev[device_index].compute_units),
444 &(gpu_info->gpu_dev[device_index].compute_units), nullptr);
446 gpu_info->gpu_dev[device_index].adress_bits = 0;
447 clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_ADDRESS_BITS,
448 sizeof(gpu_info->gpu_dev[device_index].adress_bits),
449 &(gpu_info->gpu_dev[device_index].adress_bits), nullptr);
451 gpu_info->gpu_dev[device_index].vendor_e =
452 get_vendor_id(gpu_info->gpu_dev[device_index].device_vendor);
454 clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_MAX_WORK_ITEM_SIZES, 3 * sizeof(size_t),
455 &gpu_info->gpu_dev[device_index].maxWorkItemSizes, nullptr);
457 clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t),
458 &gpu_info->gpu_dev[device_index].maxWorkGroupSize, nullptr);
460 gpu_info->gpu_dev[device_index].stat =
461 gmx::checkGpu(device_index, gpu_info->gpu_dev + device_index);
463 if (egpuCompatible == gpu_info->gpu_dev[device_index].stat)
465 gpu_info->n_dev_compatible++;
472 gpu_info->n_dev = device_index;
474 /* Dummy sort of devices - AMD first, then NVIDIA, then Intel */
475 // TODO: Sort devices based on performance.
476 if (0 < gpu_info->n_dev)
479 for (int i = 0; i < gpu_info->n_dev; i++)
481 if (OCL_VENDOR_AMD == gpu_info->gpu_dev[i].vendor_e)
487 gmx_device_info_t ocl_gpu_info;
488 ocl_gpu_info = gpu_info->gpu_dev[i];
489 gpu_info->gpu_dev[i] = gpu_info->gpu_dev[last];
490 gpu_info->gpu_dev[last] = ocl_gpu_info;
495 /* if more than 1 device left to be sorted */
496 if ((gpu_info->n_dev - 1 - last) > 1)
498 for (int i = 0; i < gpu_info->n_dev; i++)
500 if (OCL_VENDOR_NVIDIA == gpu_info->gpu_dev[i].vendor_e)
506 gmx_device_info_t ocl_gpu_info;
507 ocl_gpu_info = gpu_info->gpu_dev[i];
508 gpu_info->gpu_dev[i] = gpu_info->gpu_dev[last];
509 gpu_info->gpu_dev[last] = ocl_gpu_info;
516 sfree(ocl_device_ids);
522 sfree(ocl_platform_ids);
525 void get_gpu_device_info_string(char* s, const gmx_gpu_info_t& gpu_info, int index)
529 if (index < 0 && index >= gpu_info.n_dev)
534 gmx_device_info_t* dinfo = &gpu_info.gpu_dev[index];
536 bool bGpuExists = (dinfo->stat != egpuNonexistent && dinfo->stat != egpuInsane);
540 sprintf(s, "#%d: %s, stat: %s", index, "N/A", gpu_detect_res_str[dinfo->stat]);
544 sprintf(s, "#%d: name: %s, vendor: %s, device version: %s, stat: %s", index, dinfo->device_name,
545 dinfo->device_vendor, dinfo->device_version, gpu_detect_res_str[dinfo->stat]);
550 void init_gpu(const gmx_device_info_t* deviceInfo)
554 // If the device is NVIDIA, for safety reasons we disable the JIT
555 // caching as this is known to be broken at least until driver 364.19;
556 // the cache does not always get regenerated when the source code changes,
557 // e.g. if the path to the kernel sources remains the same
559 if (deviceInfo->vendor_e == OCL_VENDOR_NVIDIA)
561 // Ignore return values, failing to set the variable does not mean
562 // that something will go wrong later.
564 _putenv("CUDA_CACHE_DISABLE=1");
566 // Don't override, maybe a dev is testing.
567 setenv("CUDA_CACHE_DISABLE", "1", 0);
572 gmx_device_info_t* getDeviceInfo(const gmx_gpu_info_t& gpu_info, int deviceId)
574 if (deviceId < 0 || deviceId >= gpu_info.n_dev)
576 gmx_incons("Invalid GPU deviceId requested");
578 return &gpu_info.gpu_dev[deviceId];
581 size_t sizeof_gpu_dev_info()
583 return sizeof(gmx_device_info_t);
586 int gpu_info_get_stat(const gmx_gpu_info_t& info, int index)
588 return info.gpu_dev[index].stat;