1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
10 #include <config_folders.h>
12 #include "opencl_device.hxx"
14 #include <comphelper/string.hxx>
15 #include <opencl/openclconfig.hxx>
16 #include <opencl/openclwrapper.hxx>
17 #include <osl/file.hxx>
18 #include <rtl/bootstrap.hxx>
19 #include <rtl/digest.h>
20 #include <rtl/strbuf.hxx>
21 #include <rtl/ustring.hxx>
22 #include <sal/config.h>
23 #include <sal/log.hxx>
24 #include <opencl/OpenCLZone.hxx>
27 #include <unicode/regex.h>
35 #include <officecfg/Office/Common.hxx>
40 #define OPENCL_DLL_NAME "OpenCL.dll"
42 #define OPENCL_DLL_NAME nullptr
44 #define OPENCL_DLL_NAME "libOpenCL.so.1"
47 #ifdef _WIN32_WINNT_WINBLUE
48 #include <VersionHelpers.h>
51 #define DEVICE_NAME_LENGTH 1024
52 #define DRIVER_VERSION_LENGTH 1024
53 #define PLATFORM_VERSION_LENGTH 1024
55 #define CHECK_OPENCL(status,name) \
56 if( status != CL_SUCCESS ) \
58 SAL_WARN( "opencl", "OpenCL error code " << status << " at " SAL_DETAIL_WHERE "from " name ); \
67 sal_uInt64 kernelFailures
= 0;
72 bool bIsInited
= false;
74 OString
generateMD5(const void* pData
, size_t length
)
76 sal_uInt8 pBuffer
[RTL_DIGEST_LENGTH_MD5
];
77 rtlDigestError aError
= rtl_digest_MD5(pData
, length
,
78 pBuffer
, RTL_DIGEST_LENGTH_MD5
);
79 SAL_WARN_IF(aError
!= rtl_Digest_E_None
, "opencl", "md5 generation failed");
81 OStringBuffer aBuffer
;
82 const char* pString
= "0123456789ABCDEF";
83 for(sal_uInt8 val
: pBuffer
)
85 aBuffer
.append(pString
[val
/16]);
86 aBuffer
.append(pString
[val
%16]);
88 return aBuffer
.makeStringAndClear();
91 OString
const & getCacheFolder()
93 static OString aCacheFolder
;
95 if (aCacheFolder
.isEmpty())
97 OUString
url("${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER
"/" SAL_CONFIGFILE("bootstrap") ":UserInstallation}/cache/");
98 rtl::Bootstrap::expandMacros(url
);
100 osl::Directory::create(url
);
102 aCacheFolder
= rtl::OUStringToOString(url
, RTL_TEXTENCODING_UTF8
);
109 bool initializeCommandQueue(GPUEnv
& aGpuEnv
)
114 cl_command_queue command_queue
[OPENCL_CMDQUEUE_SIZE
];
116 for (int i
= 0; i
< OPENCL_CMDQUEUE_SIZE
; ++i
)
118 command_queue
[i
] = clCreateCommandQueue(aGpuEnv
.mpContext
, aGpuEnv
.mpDevID
, 0, &nState
);
119 if (nState
!= CL_SUCCESS
)
120 SAL_WARN("opencl", "clCreateCommandQueue failed: " << errorString(nState
));
122 if (command_queue
[i
] == nullptr || nState
!= CL_SUCCESS
)
124 // Release all command queues created so far.
125 for (int j
= 0; j
<= i
; ++j
)
127 if (command_queue
[j
])
129 clReleaseCommandQueue(command_queue
[j
]);
130 command_queue
[j
] = nullptr;
134 clReleaseContext(aGpuEnv
.mpContext
);
135 SAL_WARN("opencl", "failed to set/switch opencl device");
139 SAL_INFO("opencl", "Created command queue " << command_queue
[i
] << " for context " << aGpuEnv
.mpContext
);
142 for (int i
= 0; i
< OPENCL_CMDQUEUE_SIZE
; ++i
)
144 aGpuEnv
.mpCmdQueue
[i
] = command_queue
[i
];
146 aGpuEnv
.mbCommandQueueInitialized
= true;
150 void setKernelEnv( KernelEnv
*envInfo
)
152 if (!gpuEnv
.mbCommandQueueInitialized
)
154 initializeCommandQueue(gpuEnv
);
157 envInfo
->mpkContext
= gpuEnv
.mpContext
;
158 envInfo
->mpkProgram
= gpuEnv
.mpArryPrograms
[0];
160 assert(gpuEnv
.mnCmdQueuePos
< OPENCL_CMDQUEUE_SIZE
);
161 envInfo
->mpkCmdQueue
= gpuEnv
.mpCmdQueue
[gpuEnv
.mnCmdQueuePos
];
166 OString
createFileName(cl_device_id deviceId
, const char* clFileName
)
168 OString
fileName(clFileName
);
169 sal_Int32 nIndex
= fileName
.lastIndexOf(".cl");
171 fileName
= fileName
.copy(0, nIndex
);
173 char deviceName
[DEVICE_NAME_LENGTH
] = {0};
174 clGetDeviceInfo(deviceId
, CL_DEVICE_NAME
,
175 sizeof(deviceName
), deviceName
, nullptr);
177 char driverVersion
[DRIVER_VERSION_LENGTH
] = {0};
178 clGetDeviceInfo(deviceId
, CL_DRIVER_VERSION
,
179 sizeof(driverVersion
), driverVersion
, nullptr);
181 cl_platform_id platformId
;
182 clGetDeviceInfo(deviceId
, CL_DEVICE_PLATFORM
,
183 sizeof(platformId
), &platformId
, nullptr);
185 char platformVersion
[PLATFORM_VERSION_LENGTH
] = {0};
186 clGetPlatformInfo(platformId
, CL_PLATFORM_VERSION
, sizeof(platformVersion
),
187 platformVersion
, nullptr);
189 // create hash for deviceName + driver version + platform version
190 OString aString
= OString(deviceName
) + driverVersion
+ platformVersion
;
191 OString aHash
= generateMD5(aString
.getStr(), aString
.getLength());
193 return getCacheFolder() + fileName
+ "-" + aHash
+ ".bin";
196 std::vector
<std::shared_ptr
<osl::File
> > binaryGenerated( const char * clFileName
, cl_context context
)
200 std::vector
<std::shared_ptr
<osl::File
> > aGeneratedFiles
;
201 cl_int clStatus
= clGetContextInfo( context
, CL_CONTEXT_DEVICES
,
202 0, nullptr, &numDevices
);
203 numDevices
/= sizeof(numDevices
);
205 if(clStatus
!= CL_SUCCESS
)
206 return aGeneratedFiles
;
208 assert(numDevices
== 1);
210 // grab the handle to the device in the context.
212 clStatus
= clGetContextInfo( context
, CL_CONTEXT_DEVICES
,
213 sizeof( cl_device_id
), &pDevID
, nullptr );
215 if(clStatus
!= CL_SUCCESS
)
216 return aGeneratedFiles
;
218 assert(pDevID
== gpuEnv
.mpDevID
);
220 OString fileName
= createFileName(gpuEnv
.mpDevID
, clFileName
);
221 osl::File
* pNewFile
= new osl::File(rtl::OStringToOUString(fileName
, RTL_TEXTENCODING_UTF8
));
222 if(pNewFile
->open(osl_File_OpenFlag_Read
) == osl::FileBase::E_None
)
224 aGeneratedFiles
.push_back(std::shared_ptr
<osl::File
>(pNewFile
));
225 SAL_INFO("opencl.file", "Opening binary file '" << fileName
<< "' for reading: success");
229 SAL_INFO("opencl.file", "Opening binary file '" << fileName
<< "' for reading: FAIL");
233 return aGeneratedFiles
;
236 bool writeBinaryToFile( const OString
& rFileName
, const char* binary
, size_t numBytes
)
238 osl::File
file(rtl::OStringToOUString(rFileName
, RTL_TEXTENCODING_UTF8
));
239 osl::FileBase::RC status
= file
.open(
240 osl_File_OpenFlag_Write
| osl_File_OpenFlag_Create
);
242 if(status
!= osl::FileBase::E_None
)
245 sal_uInt64 nBytesWritten
= 0;
246 file
.write( binary
, numBytes
, nBytesWritten
);
248 assert(numBytes
== nBytesWritten
);
255 bool generatBinFromKernelSource( cl_program program
, const char * clFileName
)
259 cl_int clStatus
= clGetProgramInfo( program
, CL_PROGRAM_NUM_DEVICES
,
260 sizeof(numDevices
), &numDevices
, nullptr );
261 CHECK_OPENCL( clStatus
, "clGetProgramInfo" );
263 assert(numDevices
== 1);
266 /* grab the handle to the device in the program. */
267 clStatus
= clGetProgramInfo( program
, CL_PROGRAM_DEVICES
,
268 sizeof(cl_device_id
), &pDevID
, nullptr );
269 CHECK_OPENCL( clStatus
, "clGetProgramInfo" );
271 /* figure out the size of the binary. */
274 clStatus
= clGetProgramInfo( program
, CL_PROGRAM_BINARY_SIZES
,
275 sizeof(size_t), &binarySize
, nullptr );
276 CHECK_OPENCL( clStatus
, "clGetProgramInfo" );
278 /* copy over the generated binary. */
279 if ( binarySize
!= 0 )
281 std::unique_ptr
<char[]> binary(new char[binarySize
]);
282 clStatus
= clGetProgramInfo( program
, CL_PROGRAM_BINARIES
,
283 sizeof(char *), &binary
, nullptr );
284 CHECK_OPENCL(clStatus
,"clGetProgramInfo");
286 OString fileName
= createFileName(pDevID
, clFileName
);
287 if ( !writeBinaryToFile( fileName
,
288 binary
.get(), binarySize
) )
289 SAL_INFO("opencl.file", "Writing binary file '" << fileName
<< "': FAIL");
291 SAL_INFO("opencl.file", "Writing binary file '" << fileName
<< "': success");
300 cl_platform_id mpOclPlatformID
;
301 cl_context mpOclContext
;
302 cl_device_id mpOclDevsID
;
303 cl_command_queue mpOclCmdQueue
[OPENCL_CMDQUEUE_SIZE
];
306 bool initOpenCLAttr( OpenCLEnv
* env
)
308 if ( gpuEnv
.mnIsUserCreated
)
311 gpuEnv
.mpContext
= env
->mpOclContext
;
312 gpuEnv
.mpPlatformID
= env
->mpOclPlatformID
;
313 gpuEnv
.mpDevID
= env
->mpOclDevsID
;
315 gpuEnv
.mnIsUserCreated
= 1;
317 gpuEnv
.mbCommandQueueInitialized
= false;
319 gpuEnv
.mnCmdQueuePos
= 0; // default to 0.
326 void releaseOpenCLEnv( GPUEnv
*gpuInfo
)
335 for (_cl_command_queue
* & i
: gpuEnv
.mpCmdQueue
)
339 clReleaseCommandQueue(i
);
343 gpuEnv
.mnCmdQueuePos
= 0;
345 if ( gpuEnv
.mpContext
)
347 clReleaseContext( gpuEnv
.mpContext
);
348 gpuEnv
.mpContext
= nullptr;
351 gpuInfo
->mnIsUserCreated
= 0;
358 bool buildProgram(const char* buildOption
, GPUEnv
* gpuInfo
, int idx
)
362 // create a cl program executable for all the devices specified
363 clStatus
= clBuildProgram(gpuInfo
->mpArryPrograms
[idx
], 1, &gpuInfo
->mpDevID
,
364 buildOption
, nullptr, nullptr);
366 if ( clStatus
!= CL_SUCCESS
)
369 clStatus
= clGetProgramBuildInfo( gpuInfo
->mpArryPrograms
[idx
], gpuInfo
->mpDevID
,
370 CL_PROGRAM_BUILD_LOG
, 0, nullptr, &length
);
371 if ( clStatus
!= CL_SUCCESS
)
376 std::unique_ptr
<char[]> buildLog(new char[length
]);
377 clStatus
= clGetProgramBuildInfo( gpuInfo
->mpArryPrograms
[idx
], gpuInfo
->mpDevID
,
378 CL_PROGRAM_BUILD_LOG
, length
, buildLog
.get(), &length
);
379 if ( clStatus
!= CL_SUCCESS
)
384 OString aBuildLogFileURL
= getCacheFolder() + "kernel-build.log";
385 osl::File
aBuildLogFile(rtl::OStringToOUString(aBuildLogFileURL
, RTL_TEXTENCODING_UTF8
));
386 osl::FileBase::RC status
= aBuildLogFile
.open(
387 osl_File_OpenFlag_Write
| osl_File_OpenFlag_Create
);
389 if(status
!= osl::FileBase::E_None
)
392 sal_uInt64 nBytesWritten
= 0;
393 aBuildLogFile
.write( buildLog
.get(), length
, nBytesWritten
);
403 bool buildProgramFromBinary(const char* buildOption
, GPUEnv
* gpuInfo
, const char* filename
, int idx
)
406 cl_int clStatus
= clGetContextInfo( gpuInfo
->mpContext
, CL_CONTEXT_DEVICES
,
407 0, nullptr, &numDevices
);
408 numDevices
/= sizeof(numDevices
);
409 CHECK_OPENCL( clStatus
, "clGetContextInfo" );
411 std::vector
<std::shared_ptr
<osl::File
> > aGeneratedFiles
= binaryGenerated(
412 filename
, gpuInfo
->mpContext
);
414 if (aGeneratedFiles
.size() == numDevices
)
416 std::unique_ptr
<size_t[]> length(new size_t[numDevices
]);
417 std::unique_ptr
<unsigned char*[]> pBinary(new unsigned char*[numDevices
]);
418 for(size_t i
= 0; i
< numDevices
; ++i
)
421 aGeneratedFiles
[i
]->getSize(nSize
);
422 unsigned char* binary
= new unsigned char[nSize
];
423 sal_uInt64 nBytesRead
;
424 aGeneratedFiles
[i
]->read(binary
, nSize
, nBytesRead
);
425 if(nSize
!= nBytesRead
)
428 length
[i
] = nBytesRead
;
433 // grab the handles to all of the devices in the context.
434 std::unique_ptr
<cl_device_id
[]> pArryDevsID(new cl_device_id
[numDevices
]);
435 clStatus
= clGetContextInfo( gpuInfo
->mpContext
, CL_CONTEXT_DEVICES
,
436 sizeof( cl_device_id
) * numDevices
, pArryDevsID
.get(), nullptr );
438 if(clStatus
!= CL_SUCCESS
)
440 for(size_t i
= 0; i
< numDevices
; ++i
)
447 cl_int binary_status
;
449 gpuInfo
->mpArryPrograms
[idx
] = clCreateProgramWithBinary( gpuInfo
->mpContext
,numDevices
,
450 pArryDevsID
.get(), length
.get(), const_cast<const unsigned char**>(pBinary
.get()),
451 &binary_status
, &clStatus
);
452 if(clStatus
!= CL_SUCCESS
)
454 // something went wrong, fall back to compiling from source
457 SAL_INFO("opencl", "Created program " << gpuInfo
->mpArryPrograms
[idx
] << " from binary");
458 for(size_t i
= 0; i
< numDevices
; ++i
)
464 if ( !gpuInfo
->mpArryPrograms
[idx
] )
468 return buildProgram(buildOption
, gpuInfo
, idx
);
473 void checkDeviceForDoubleSupport(cl_device_id deviceId
, bool& bKhrFp64
, bool& bAmdFp64
)
480 // Check device extensions for double type
481 size_t aDevExtInfoSize
= 0;
483 cl_uint clStatus
= clGetDeviceInfo( deviceId
, CL_DEVICE_EXTENSIONS
, 0, nullptr, &aDevExtInfoSize
);
484 if( clStatus
!= CL_SUCCESS
)
487 std::unique_ptr
<char[]> pExtInfo(new char[aDevExtInfoSize
]);
489 clStatus
= clGetDeviceInfo( deviceId
, CL_DEVICE_EXTENSIONS
,
490 sizeof(char) * aDevExtInfoSize
, pExtInfo
.get(), nullptr);
492 if( clStatus
!= CL_SUCCESS
)
495 if ( strstr( pExtInfo
.get(), "cl_khr_fp64" ) )
501 // Check if cl_amd_fp64 extension is supported
502 if ( strstr( pExtInfo
.get(), "cl_amd_fp64" ) )
507 bool initOpenCLRunEnv( GPUEnv
*gpuInfo
)
510 cl_uint nPreferredVectorWidthFloat
;
513 bool bKhrFp64
= false;
514 bool bAmdFp64
= false;
516 checkDeviceForDoubleSupport(gpuInfo
->mpDevID
, bKhrFp64
, bAmdFp64
);
518 gpuInfo
->mnKhrFp64Flag
= bKhrFp64
;
519 gpuInfo
->mnAmdFp64Flag
= bAmdFp64
;
521 gpuInfo
->mbNeedsTDRAvoidance
= false;
523 clGetDeviceInfo(gpuInfo
->mpDevID
, CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT
, sizeof(cl_uint
),
524 &nPreferredVectorWidthFloat
, nullptr);
525 SAL_INFO("opencl", "CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT=" << nPreferredVectorWidthFloat
);
527 clGetPlatformInfo(gpuInfo
->mpPlatformID
, CL_PLATFORM_NAME
, 64,
531 // the Win32 SDK 8.1 deprecates GetVersionEx()
532 # ifdef _WIN32_WINNT_WINBLUE
533 const bool bIsNotWinOrIsWin8OrGreater
= IsWindows8OrGreater();
535 bool bIsNotWinOrIsWin8OrGreater
= true;
536 OSVERSIONINFO aVersionInfo
;
537 memset( &aVersionInfo
, 0, sizeof(aVersionInfo
) );
538 aVersionInfo
.dwOSVersionInfoSize
= sizeof( aVersionInfo
);
539 if (GetVersionEx( &aVersionInfo
))
541 // Windows 7 or lower?
542 if (aVersionInfo
.dwMajorVersion
< 6 ||
543 (aVersionInfo
.dwMajorVersion
== 6 && aVersionInfo
.dwMinorVersion
< 2))
544 bIsNotWinOrIsWin8OrGreater
= false;
548 const bool bIsNotWinOrIsWin8OrGreater
= true;
551 // Heuristic: Certain old low-end OpenCL implementations don't
552 // work for us with too large group lengths. Looking at the preferred
553 // float vector width seems to be a way to detect these devices, except
554 // the non-working NVIDIA cards on Windows older than version 8.
555 gpuInfo
->mbNeedsTDRAvoidance
= ( nPreferredVectorWidthFloat
== 4 ) ||
556 ( !bIsNotWinOrIsWin8OrGreater
&&
557 OUString::createFromAscii(pName
).indexOf("NVIDIA") > -1 );
559 size_t nMaxParameterSize
;
560 clGetDeviceInfo(gpuInfo
->mpDevID
, CL_DEVICE_MAX_PARAMETER_SIZE
, sizeof(size_t),
561 &nMaxParameterSize
, nullptr);
562 SAL_INFO("opencl", "CL_DEVICE_MAX_PARAMETER_SIZE=" << nMaxParameterSize
);
567 bool initOpenCLRunEnv( int argc
)
569 if ( ( argc
> MAX_CLFILE_NUM
) || ( argc
< 0 ) )
574 if ( !gpuEnv
.mnIsUserCreated
)
575 memset( &gpuEnv
, 0, sizeof(gpuEnv
) );
577 //initialize devices, context, command_queue
578 bool status
= initOpenCLRunEnv( &gpuEnv
);
583 //initialize program, kernelName, kernelCount
584 if( getenv( "SC_FLOAT" ) )
586 gpuEnv
.mnKhrFp64Flag
= false;
587 gpuEnv
.mnAmdFp64Flag
= false;
589 if( gpuEnv
.mnKhrFp64Flag
)
591 SAL_INFO("opencl", "Use Khr double");
593 else if( gpuEnv
.mnAmdFp64Flag
)
595 SAL_INFO("opencl", "Use AMD double type");
599 SAL_INFO("opencl", "USE float type");
606 // based on crashes and hanging during kernel compilation
607 void createDeviceInfo(cl_device_id aDeviceId
, OpenCLPlatformInfo
& rPlatformInfo
)
609 OpenCLDeviceInfo aDeviceInfo
;
610 aDeviceInfo
.device
= aDeviceId
;
612 char pName
[DEVICE_NAME_LENGTH
];
613 cl_int nState
= clGetDeviceInfo(aDeviceId
, CL_DEVICE_NAME
, DEVICE_NAME_LENGTH
, pName
, nullptr);
614 if(nState
!= CL_SUCCESS
)
617 aDeviceInfo
.maName
= OUString::createFromAscii(pName
);
619 char pVendor
[DEVICE_NAME_LENGTH
];
620 nState
= clGetDeviceInfo(aDeviceId
, CL_DEVICE_VENDOR
, DEVICE_NAME_LENGTH
, pVendor
, nullptr);
621 if(nState
!= CL_SUCCESS
)
624 aDeviceInfo
.maVendor
= OUString::createFromAscii(pVendor
);
627 nState
= clGetDeviceInfo(aDeviceId
, CL_DEVICE_GLOBAL_MEM_SIZE
, sizeof(nMemSize
), &nMemSize
, nullptr);
628 if(nState
!= CL_SUCCESS
)
631 aDeviceInfo
.mnMemory
= nMemSize
;
633 cl_uint nClockFrequency
;
634 nState
= clGetDeviceInfo(aDeviceId
, CL_DEVICE_MAX_CLOCK_FREQUENCY
, sizeof(nClockFrequency
), &nClockFrequency
, nullptr);
635 if(nState
!= CL_SUCCESS
)
638 aDeviceInfo
.mnFrequency
= nClockFrequency
;
640 cl_uint nComputeUnits
;
641 nState
= clGetDeviceInfo(aDeviceId
, CL_DEVICE_MAX_COMPUTE_UNITS
, sizeof(nComputeUnits
), &nComputeUnits
, nullptr);
642 if(nState
!= CL_SUCCESS
)
645 char pDriver
[DEVICE_NAME_LENGTH
];
646 nState
= clGetDeviceInfo(aDeviceId
, CL_DRIVER_VERSION
, DEVICE_NAME_LENGTH
, pDriver
, nullptr);
648 if(nState
!= CL_SUCCESS
)
651 aDeviceInfo
.maDriver
= OUString::createFromAscii(pDriver
);
653 bool bKhrFp64
= false;
654 bool bAmdFp64
= false;
655 checkDeviceForDoubleSupport(aDeviceId
, bKhrFp64
, bAmdFp64
);
657 // only list devices that support double
658 if(!bKhrFp64
&& !bAmdFp64
)
661 aDeviceInfo
.mnComputeUnits
= nComputeUnits
;
663 if(!OpenCLConfig::get().checkImplementation(rPlatformInfo
, aDeviceInfo
))
664 rPlatformInfo
.maDevices
.push_back(aDeviceInfo
);
667 bool createPlatformInfo(cl_platform_id nPlatformId
, OpenCLPlatformInfo
& rPlatformInfo
)
669 rPlatformInfo
.platform
= nPlatformId
;
671 cl_int nState
= clGetPlatformInfo(nPlatformId
, CL_PLATFORM_NAME
, 64,
673 if(nState
!= CL_SUCCESS
)
675 rPlatformInfo
.maName
= OUString::createFromAscii(pName
);
678 nState
= clGetPlatformInfo(nPlatformId
, CL_PLATFORM_VENDOR
, 64,
680 if(nState
!= CL_SUCCESS
)
683 rPlatformInfo
.maVendor
= OUString::createFromAscii(pVendor
);
686 nState
= clGetDeviceIDs(nPlatformId
, CL_DEVICE_TYPE_ALL
, 0, nullptr, &nDevices
);
687 if(nState
!= CL_SUCCESS
)
690 // memory leak that does not matter
691 // memory is stored in static variable that lives through the whole program
692 cl_device_id
* pDevices
= new cl_device_id
[nDevices
];
693 nState
= clGetDeviceIDs(nPlatformId
, CL_DEVICE_TYPE_ALL
, nDevices
, pDevices
, nullptr);
694 if(nState
!= CL_SUCCESS
)
697 for(size_t i
= 0; i
< nDevices
; ++i
)
699 createDeviceInfo(pDevices
[i
], rPlatformInfo
);
707 const std::vector
<OpenCLPlatformInfo
>& fillOpenCLInfo()
709 static std::vector
<OpenCLPlatformInfo
> aPlatforms
;
711 // return early if we already initialized or can't use OpenCL
712 if (!aPlatforms
.empty() || !canUseOpenCL())
715 int status
= clewInit(OPENCL_DLL_NAME
);
720 cl_int nState
= clGetPlatformIDs(0, nullptr, &nPlatforms
);
722 if(nState
!= CL_SUCCESS
)
725 // memory leak that does not matter,
726 // memory is stored in static instance aPlatforms
727 cl_platform_id
* pPlatforms
= new cl_platform_id
[nPlatforms
];
728 nState
= clGetPlatformIDs(nPlatforms
, pPlatforms
, nullptr);
730 if(nState
!= CL_SUCCESS
)
733 for(size_t i
= 0; i
< nPlatforms
; ++i
)
735 OpenCLPlatformInfo aPlatformInfo
;
736 if(createPlatformInfo(pPlatforms
[i
], aPlatformInfo
))
737 aPlatforms
.push_back(aPlatformInfo
);
745 cl_device_id
findDeviceIdByDeviceString(const OUString
& rString
, const std::vector
<OpenCLPlatformInfo
>& rPlatforms
)
747 for (const OpenCLPlatformInfo
& rPlatform
: rPlatforms
)
749 for (const OpenCLDeviceInfo
& rDeviceInfo
: rPlatform
.maDevices
)
751 OUString aDeviceId
= rDeviceInfo
.maVendor
+ " " + rDeviceInfo
.maName
;
752 if (rString
== aDeviceId
)
754 return rDeviceInfo
.device
;
762 void findDeviceInfoFromDeviceId(cl_device_id aDeviceId
, size_t& rDeviceId
, size_t& rPlatformId
)
764 cl_platform_id platformId
;
765 cl_int nState
= clGetDeviceInfo(aDeviceId
, CL_DEVICE_PLATFORM
,
766 sizeof(platformId
), &platformId
, nullptr);
768 if(nState
!= CL_SUCCESS
)
771 const std::vector
<OpenCLPlatformInfo
>& rPlatforms
= fillOpenCLInfo();
772 for(size_t i
= 0; i
< rPlatforms
.size(); ++i
)
774 cl_platform_id platId
= static_cast<cl_platform_id
>(rPlatforms
[i
].platform
);
775 if(platId
!= platformId
)
778 for(size_t j
= 0; j
< rPlatforms
[i
].maDevices
.size(); ++j
)
780 cl_device_id id
= static_cast<cl_device_id
>(rPlatforms
[i
].maDevices
[j
].device
);
795 if (getenv("SAL_DISABLE_OPENCL") || !officecfg::Office::Common::Misc::UseOpenCL::get())
800 bool switchOpenCLDevice(const OUString
* pDevice
, bool bAutoSelect
, bool bForceEvaluation
, OUString
& rOutSelectedDeviceVersionIDString
)
802 if (!canUseOpenCL() || fillOpenCLInfo().empty())
805 cl_device_id pDeviceId
= nullptr;
807 pDeviceId
= findDeviceIdByDeviceString(*pDevice
, fillOpenCLInfo());
809 if(!pDeviceId
|| bAutoSelect
)
811 int status
= clewInit(OPENCL_DLL_NAME
);
815 OUString
url("${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER
"/" SAL_CONFIGFILE("bootstrap") ":UserInstallation}/cache/");
816 rtl::Bootstrap::expandMacros(url
);
818 osl::FileBase::getSystemPathFromFileURL(url
,path
);
819 ds_device aSelectedDevice
= getDeviceSelection(path
, bForceEvaluation
);
820 if ( aSelectedDevice
.eType
!= DeviceType::OpenCLDevice
)
822 pDeviceId
= aSelectedDevice
.aDeviceID
;
825 if(gpuEnv
.mpDevID
== pDeviceId
)
827 // we don't need to change anything
828 // still the same device
829 return pDeviceId
!= nullptr;
833 cl_platform_id platformId
;
837 cl_int nState
= clGetDeviceInfo(pDeviceId
, CL_DEVICE_PLATFORM
,
838 sizeof(platformId
), &platformId
, nullptr);
840 cl_context_properties cps
[3];
841 cps
[0] = CL_CONTEXT_PLATFORM
;
842 cps
[1] = reinterpret_cast<cl_context_properties
>(platformId
);
844 context
= clCreateContext( cps
, 1, &pDeviceId
, nullptr, nullptr, &nState
);
845 if (nState
!= CL_SUCCESS
)
846 SAL_WARN("opencl", "clCreateContext failed: " << errorString(nState
));
848 if(nState
!= CL_SUCCESS
|| context
== nullptr)
850 if(context
!= nullptr)
851 clReleaseContext(context
);
853 SAL_WARN("opencl", "failed to set/switch opencl device");
856 SAL_INFO("opencl", "Created context " << context
<< " for platform " << platformId
<< ", device " << pDeviceId
);
858 OString sDeviceID
= getDeviceInfoString(pDeviceId
, CL_DEVICE_VENDOR
) + " " + getDeviceInfoString(pDeviceId
, CL_DRIVER_VERSION
);
859 rOutSelectedDeviceVersionIDString
= OStringToOUString(sDeviceID
, RTL_TEXTENCODING_UTF8
);
862 setOpenCLCmdQueuePosition(0); // Call this just to avoid the method being deleted from unused function deleter.
864 releaseOpenCLEnv(&gpuEnv
);
867 env
.mpOclPlatformID
= platformId
;
868 env
.mpOclContext
= context
;
869 env
.mpOclDevsID
= pDeviceId
;
871 initOpenCLAttr(&env
);
873 return !initOpenCLRunEnv(0);
876 void getOpenCLDeviceInfo(size_t& rDeviceId
, size_t& rPlatformId
)
881 int status
= clewInit(OPENCL_DLL_NAME
);
885 cl_device_id id
= gpuEnv
.mpDevID
;
886 findDeviceInfoFromDeviceId(id
, rDeviceId
, rPlatformId
);
889 void setOpenCLCmdQueuePosition( int nPos
)
891 if (nPos
< 0 || nPos
>= OPENCL_CMDQUEUE_SIZE
)
892 // Out of range. Ignore this.
895 gpuEnv
.mnCmdQueuePos
= nPos
;
898 const char* errorString(cl_int nError
)
900 #define CASE(val) case CL_##val: return #val
904 CASE(DEVICE_NOT_FOUND
);
905 CASE(DEVICE_NOT_AVAILABLE
);
906 CASE(COMPILER_NOT_AVAILABLE
);
907 CASE(MEM_OBJECT_ALLOCATION_FAILURE
);
908 CASE(OUT_OF_RESOURCES
);
909 CASE(OUT_OF_HOST_MEMORY
);
910 CASE(PROFILING_INFO_NOT_AVAILABLE
);
911 CASE(MEM_COPY_OVERLAP
);
912 CASE(IMAGE_FORMAT_MISMATCH
);
913 CASE(IMAGE_FORMAT_NOT_SUPPORTED
);
914 CASE(BUILD_PROGRAM_FAILURE
);
917 CASE(INVALID_DEVICE_TYPE
);
918 CASE(INVALID_PLATFORM
);
919 CASE(INVALID_DEVICE
);
920 CASE(INVALID_CONTEXT
);
921 CASE(INVALID_QUEUE_PROPERTIES
);
922 CASE(INVALID_COMMAND_QUEUE
);
923 CASE(INVALID_HOST_PTR
);
924 CASE(INVALID_MEM_OBJECT
);
925 CASE(INVALID_IMAGE_FORMAT_DESCRIPTOR
);
926 CASE(INVALID_IMAGE_SIZE
);
927 CASE(INVALID_SAMPLER
);
928 CASE(INVALID_BINARY
);
929 CASE(INVALID_BUILD_OPTIONS
);
930 CASE(INVALID_PROGRAM
);
931 CASE(INVALID_PROGRAM_EXECUTABLE
);
932 CASE(INVALID_KERNEL_NAME
);
933 CASE(INVALID_KERNEL_DEFINITION
);
934 CASE(INVALID_KERNEL
);
935 CASE(INVALID_ARG_INDEX
);
936 CASE(INVALID_ARG_VALUE
);
937 CASE(INVALID_ARG_SIZE
);
938 CASE(INVALID_KERNEL_ARGS
);
939 CASE(INVALID_WORK_DIMENSION
);
940 CASE(INVALID_WORK_GROUP_SIZE
);
941 CASE(INVALID_WORK_ITEM_SIZE
);
942 CASE(INVALID_GLOBAL_OFFSET
);
943 CASE(INVALID_EVENT_WAIT_LIST
);
945 CASE(INVALID_OPERATION
);
946 CASE(INVALID_GL_OBJECT
);
947 CASE(INVALID_BUFFER_SIZE
);
948 CASE(INVALID_MIP_LEVEL
);
949 CASE(INVALID_GLOBAL_WORK_SIZE
);
951 return "Unknown OpenCL error code";
956 bool GPUEnv::isOpenCLEnabled()
958 return gpuEnv
.mpDevID
&& gpuEnv
.mpContext
;
963 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */