initialization.cpp 41.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Institute Of Software Chinese Academy Of Science, all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
Y
yao 已提交
15
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
16 17 18 19
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Guoping Long, longguoping@gmail.com
Y
yao 已提交
20 21
//    Niko Li, newlife20080214@gmail.com
//    Yao Wang, bitwangyaoyao@gmail.com
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other oclMaterials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"
#include <iomanip>
Y
yao 已提交
50
#include <fstream>
51
#include "binarycaching.hpp"
52 53 54 55 56 57 58 59 60

using namespace cv;
using namespace cv::ocl;
using namespace std;
using std::cout;
using std::endl;

//#define PRINT_KERNEL_RUN_TIME
#define RUN_TIMES 100
Y
yao 已提交
61 62 63
#ifndef CL_MEM_USE_PERSISTENT_MEM_AMD
#define CL_MEM_USE_PERSISTENT_MEM_AMD 0
#endif
64 65 66 67 68 69
//#define AMD_DOUBLE_DIFFER

namespace cv
{
    namespace ocl
    {
70
        extern void fft_teardown();
71
        extern void clBlasTeardown();
72 73 74 75 76 77 78
        /*
         * The binary caching system to eliminate redundant program source compilation.
         * Strictly, this is not a cache because we do not implement evictions right now.
         * We shall add such features to trade-off memory consumption and performance when necessary.
         */
        auto_ptr<ProgramCache> ProgramCache::programCache;
        ProgramCache *programCache = NULL;
79 80
        DevMemType gDeviceMemType = DEVICE_MEM_DEFAULT;
        DevMemRW gDeviceMemRW = DEVICE_MEM_R_W;
81
        int gDevMemTypeValueMap[5] = {0,
82 83 84 85 86 87
                                      CL_MEM_ALLOC_HOST_PTR,
                                      CL_MEM_USE_HOST_PTR,
                                      CL_MEM_COPY_HOST_PTR,
                                      CL_MEM_USE_PERSISTENT_MEM_AMD};
        int gDevMemRWValueMap[3] = {CL_MEM_READ_WRITE, CL_MEM_READ_ONLY, CL_MEM_WRITE_ONLY};

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
        ProgramCache::ProgramCache()
        {
            codeCache.clear();
            cacheSize = 0;
        }

        ProgramCache::~ProgramCache()
        {
            releaseProgram();
        }

        cl_program ProgramCache::progLookup(string srcsign)
        {
            map<string, cl_program>::iterator iter;
            iter = codeCache.find(srcsign);
            if(iter != codeCache.end())
                return iter->second;
            else
                return NULL;
        }

        void ProgramCache::addProgram(string srcsign , cl_program program)
        {
            if(!progLookup(srcsign))
            {
                codeCache.insert(map<string, cl_program>::value_type(srcsign, program));
            }
        }

        void ProgramCache::releaseProgram()
        {
            map<string, cl_program>::iterator iter;
            for(iter = codeCache.begin(); iter != codeCache.end(); iter++)
            {
                openCLSafeCall(clReleaseProgram(iter->second));
            }
            codeCache.clear();
            cacheSize = 0;
        }
127
        struct Info::Impl
128 129 130 131
        {
            cl_platform_id oclplatform;
            std::vector<cl_device_id> devices;
            std::vector<std::string> devName;
132
            std::string clVersion;
133 134 135 136 137

            cl_context oclcontext;
            cl_command_queue clCmdQueue;
            int devnum;
            size_t maxWorkGroupSize;
138 139
            cl_uint maxDimensions; // == maxWorkItemSizes.size()
            std::vector<size_t> maxWorkItemSizes;
140 141 142
            cl_uint maxComputeUnits;
            char extra_options[512];
            int  double_support;
143 144 145
            int unified_memory; //1 means integrated GPU, otherwise this value is 0
            int refcounter;

146
            Impl();
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162

            void setDevice(void *ctx, void *q, int devnum);

            void release()
            {
                if(1 == CV_XADD(&refcounter, -1))
                {
                    releaseResources();
                    delete this;
                }
            }

            Impl* copy()
            {
                CV_XADD(&refcounter, 1);
                return this;
163
            }
164 165 166 167 168

        private:
            Impl(const Impl&);
            Impl& operator=(const Impl&);
            void releaseResources();
169 170
        };

P
peng xiao 已提交
171
        // global variables to hold binary cache properties
172
        static int enable_disk_cache =
P
peng xiao 已提交
173 174 175 176 177
#ifdef _DEBUG
            false;
#else
            true;
#endif
P
peng xiao 已提交
178
        static int update_disk_cache = false;
P
peng xiao 已提交
179 180
        static String binpath = "";

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
        Info::Impl::Impl()
            :oclplatform(0),
            oclcontext(0),
            clCmdQueue(0),
            devnum(-1),
            maxWorkGroupSize(0),
            maxDimensions(0),
            maxComputeUnits(0),
            double_support(0),
            unified_memory(0),
            refcounter(1)
        {
            memset(extra_options, 0, 512);
        }

196 197 198 199 200 201
        void Info::Impl::releaseResources()
        {
            devnum = -1;

            if(clCmdQueue)
            {
202 203
                //temporarily disable command queue release as it causes program hang at exit
                //openCLSafeCall(clReleaseCommandQueue(clCmdQueue));
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
                clCmdQueue = 0;
            }

            if(oclcontext)
            {
                openCLSafeCall(clReleaseContext(oclcontext));
                oclcontext = 0;
            }
        }

        void Info::Impl::setDevice(void *ctx, void *q, int dnum)
        {
            if((ctx && q) || devnum != dnum)
                releaseResources();

            CV_Assert(dnum >= 0 && dnum < (int)devices.size());
            devnum = dnum;
            if(ctx && q)
            {
                oclcontext = (cl_context)ctx;
                clCmdQueue = (cl_command_queue)q;
                clRetainContext(oclcontext);
                clRetainCommandQueue(clCmdQueue);
            }
            else
            {
                cl_int status = 0;
                cl_context_properties cps[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(oclplatform), 0 };
                oclcontext = clCreateContext(cps, 1, &devices[devnum], 0, 0, &status);
                openCLVerifyCall(status);
                clCmdQueue = clCreateCommandQueue(oclcontext, devices[devnum], CL_QUEUE_PROFILING_ENABLE, &status);
                openCLVerifyCall(status);
            }

            openCLSafeCall(clGetDeviceInfo(devices[devnum], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), (void *)&maxWorkGroupSize, 0));
            openCLSafeCall(clGetDeviceInfo(devices[devnum], CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof(cl_uint), (void *)&maxDimensions, 0));
            maxWorkItemSizes.resize(maxDimensions);
            openCLSafeCall(clGetDeviceInfo(devices[devnum], CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(size_t)*maxDimensions, (void *)&maxWorkItemSizes[0], 0));
            openCLSafeCall(clGetDeviceInfo(devices[devnum], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(cl_uint), (void *)&maxComputeUnits, 0));

            cl_bool unfymem = false;
            openCLSafeCall(clGetDeviceInfo(devices[devnum], CL_DEVICE_HOST_UNIFIED_MEMORY, sizeof(cl_bool), (void *)&unfymem, 0));
            unified_memory = unfymem ? 1 : 0;

            //initialize extra options for compilation. Currently only fp64 is included.
            //Assume 4KB is enough to store all possible extensions.
            const int EXT_LEN = 4096 + 1 ;
            char extends_set[EXT_LEN];
            size_t extends_size;
            openCLSafeCall(clGetDeviceInfo(devices[devnum], CL_DEVICE_EXTENSIONS, EXT_LEN, (void *)extends_set, &extends_size));
            extends_set[EXT_LEN - 1] = 0;
            size_t fp64_khr = std::string(extends_set).find("cl_khr_fp64");

            if(fp64_khr != std::string::npos)
            {
                sprintf(extra_options, "-D DOUBLE_SUPPORT");
                double_support = 1;
            }
            else
            {
                memset(extra_options, 0, 512);
                double_support = 0;
            }
        }

        ////////////////////////Common OpenCL specific calls///////////////
        int getDevMemType(DevMemRW& rw_type, DevMemType& mem_type)
        {
            rw_type = gDeviceMemRW;
            mem_type = gDeviceMemType;
            return Context::getContext()->impl->unified_memory;
        }

        int setDevMemType(DevMemRW rw_type, DevMemType mem_type)
        {
            if( (mem_type == DEVICE_MEM_PM && Context::getContext()->impl->unified_memory == 0) ||
                 mem_type == DEVICE_MEM_UHP ||
                 mem_type == DEVICE_MEM_CHP )
                return -1;
            gDeviceMemRW = rw_type;
            gDeviceMemType = mem_type;
            return 0;
        }

288 289 290 291 292 293 294
        inline int divUp(int total, int grain)
        {
            return (total + grain - 1) / grain;
        }

        int getDevice(std::vector<Info> &oclinfo, int devicetype)
        {
295 296 297
            //TODO: cache oclinfo vector
            oclinfo.clear();

298 299
            switch(devicetype)
            {
300 301 302 303 304 305 306
            case CVCL_DEVICE_TYPE_DEFAULT:
            case CVCL_DEVICE_TYPE_CPU:
            case CVCL_DEVICE_TYPE_GPU:
            case CVCL_DEVICE_TYPE_ACCELERATOR:
            case CVCL_DEVICE_TYPE_ALL:
                break;
            default:
307
                return 0;
308
            }
309

310 311
            // Platform info
            cl_uint numPlatforms;
312 313 314 315 316
            openCLSafeCall(clGetPlatformIDs(0, 0, &numPlatforms));
            if(numPlatforms < 1) return 0;

            std::vector<cl_platform_id> platforms(numPlatforms);
            openCLSafeCall(clGetPlatformIDs(numPlatforms, &platforms[0], 0));
317 318

            char deviceName[256];
319
            int devcienums = 0;
320
            char clVersion[256];
321 322
            for (unsigned i = 0; i < numPlatforms; ++i)
            {
323
                cl_uint numsdev = 0;
324
                cl_int status = clGetDeviceIDs(platforms[i], devicetype, 0, NULL, &numsdev);
325 326
                if(status != CL_DEVICE_NOT_FOUND)
                    openCLVerifyCall(status);
327

328 329 330
                if(numsdev > 0)
                {
                    devcienums += numsdev;
331 332 333 334
                    std::vector<cl_device_id> devices(numsdev);
                    openCLSafeCall(clGetDeviceIDs(platforms[i], devicetype, numsdev, &devices[0], 0));

                    Info ocltmpinfo;
335
                    ocltmpinfo.impl->oclplatform = platforms[i];
336 337
                    openCLSafeCall(clGetPlatformInfo(platforms[i], CL_PLATFORM_VERSION, sizeof(clVersion), clVersion, NULL));
                    ocltmpinfo.impl->clVersion = clVersion;
338
                    for(unsigned j = 0; j < numsdev; ++j)
339 340
                    {
                        ocltmpinfo.impl->devices.push_back(devices[j]);
341 342 343
                        openCLSafeCall(clGetDeviceInfo(devices[j], CL_DEVICE_NAME, sizeof(deviceName), deviceName, 0));
                        ocltmpinfo.impl->devName.push_back(deviceName);
                        ocltmpinfo.DeviceName.push_back(deviceName);
344 345 346 347
                    }
                    oclinfo.push_back(ocltmpinfo);
                }
            }
348 349 350 351
            if(devcienums > 0)
            {
                setDevice(oclinfo[0]);
            }
352 353 354
            return devcienums;
        }

Y
yao 已提交
355 356
        void setDevice(Info &oclinfo, int devnum)
        {
357 358
            oclinfo.impl->setDevice(0, 0, devnum);
            Context::setContext(oclinfo);
Y
yao 已提交
359 360 361 362
        }

        void setDeviceEx(Info &oclinfo, void *ctx, void *q, int devnum)
        {
363 364
            oclinfo.impl->setDevice(ctx, q, devnum);
            Context::setContext(oclinfo);
Y
yao 已提交
365 366
         }

367 368
        void *getoclContext()
        {
369
            return &(Context::getContext()->impl->oclcontext);
370 371 372 373 374 375
        }

        void *getoclCommandQueue()
        {
            return &(Context::getContext()->impl->clCmdQueue);
        }
376

Y
yao 已提交
377 378 379 380 381
        void finish()
        {
            clFinish(Context::getContext()->impl->clCmdQueue);
        }

382 383 384
        //template specializations of queryDeviceInfo
        template<>
        bool queryDeviceInfo<IS_CPU_DEVICE, bool>(cl_kernel)
385
        {
386 387 388 389 390 391 392
            Info::Impl* impl = Context::getContext()->impl;
            cl_device_type devicetype;
            openCLSafeCall(clGetDeviceInfo(impl->devices[impl->devnum],
                CL_DEVICE_TYPE, sizeof(cl_device_type),
                &devicetype, NULL));
            return (devicetype == CVCL_DEVICE_TYPE_CPU);
        }
P
peng xiao 已提交
393

394 395 396 397 398 399 400 401 402
        template<typename _ty>
        static _ty queryWavesize(cl_kernel kernel)
        {
            size_t info = 0;
            Info::Impl* impl = Context::getContext()->impl;
            bool is_cpu = queryDeviceInfo<IS_CPU_DEVICE, bool>();
            if(is_cpu)
            {
                return 1;
403
            }
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
            CV_Assert(kernel != NULL);
            openCLSafeCall(clGetKernelWorkGroupInfo(kernel, impl->devices[impl->devnum],
                CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, sizeof(size_t), &info, NULL));
            return static_cast<_ty>(info);
        }

        template<>
        size_t queryDeviceInfo<WAVEFRONT_SIZE, size_t>(cl_kernel kernel)
        {
            return queryWavesize<size_t>(kernel);
        }
        template<>
        int queryDeviceInfo<WAVEFRONT_SIZE, int>(cl_kernel kernel)
        {
            return queryWavesize<int>(kernel);
419 420
        }

421 422 423 424
        void openCLReadBuffer(Context *clCxt, cl_mem dst_buffer, void *host_buffer, size_t size)
        {
            cl_int status;
            status = clEnqueueReadBuffer(clCxt->impl->clCmdQueue, dst_buffer, CL_TRUE, 0,
425
                                         size, host_buffer, 0, NULL, NULL);
426 427 428 429 430 431
            openCLVerifyCall(status);
        }

        cl_mem openCLCreateBuffer(Context *clCxt, size_t flag , size_t size)
        {
            cl_int status;
432
            cl_mem buffer = clCreateBuffer(clCxt->impl->oclcontext, (cl_mem_flags)flag, size, NULL, &status);
433 434 435 436 437
            openCLVerifyCall(status);
            return buffer;
        }

        void openCLMallocPitch(Context *clCxt, void **dev_ptr, size_t *pitch,
438
                               size_t widthInBytes, size_t height)
439 440 441 442 443 444
        {
            openCLMallocPitchEx(clCxt, dev_ptr, pitch, widthInBytes, height, gDeviceMemRW, gDeviceMemType);
        }

        void openCLMallocPitchEx(Context *clCxt, void **dev_ptr, size_t *pitch,
                               size_t widthInBytes, size_t height, DevMemRW rw_type, DevMemType mem_type)
445 446
        {
            cl_int status;
447
            *dev_ptr = clCreateBuffer(clCxt->impl->oclcontext, gDevMemRWValueMap[rw_type]|gDevMemTypeValueMap[mem_type],
448
                                      widthInBytes * height, 0, &status);
449 450 451 452 453
            openCLVerifyCall(status);
            *pitch = widthInBytes;
        }

        void openCLMemcpy2D(Context *clCxt, void *dst, size_t dpitch,
454
                            const void *src, size_t spitch,
A
Andrey Kamaev 已提交
455
                            size_t width, size_t height, openCLMemcpyKind kind, int channels)
456 457 458 459 460 461
        {
            size_t buffer_origin[3] = {0, 0, 0};
            size_t host_origin[3] = {0, 0, 0};
            size_t region[3] = {width, height, 1};
            if(kind == clMemcpyHostToDevice)
            {
462 463 464 465 466 467 468 469 470 471
                if(dpitch == width || channels == 3 || height == 1)
                {
                    openCLSafeCall(clEnqueueWriteBuffer(clCxt->impl->clCmdQueue, (cl_mem)dst, CL_TRUE,
                                                        0, width * height, src, 0, NULL, NULL));
                }
                else
                {
                    openCLSafeCall(clEnqueueWriteBufferRect(clCxt->impl->clCmdQueue, (cl_mem)dst, CL_TRUE,
                                                            buffer_origin, host_origin, region, dpitch, 0, spitch, 0, src, 0, 0, 0));
                }
472 473 474
            }
            else if(kind == clMemcpyDeviceToHost)
            {
475 476 477 478 479 480 481 482 483 484
                if(spitch == width || channels == 3 || height == 1)
                {
                    openCLSafeCall(clEnqueueReadBuffer(clCxt->impl->clCmdQueue, (cl_mem)src, CL_TRUE,
                                                       0, width * height, dst, 0, NULL, NULL));
                }
                else
                {
                    openCLSafeCall(clEnqueueReadBufferRect(clCxt->impl->clCmdQueue, (cl_mem)src, CL_TRUE,
                                                           buffer_origin, host_origin, region, spitch, 0, dpitch, 0, dst, 0, 0, 0));
                }
485 486 487 488
            }
        }

        void openCLCopyBuffer2D(Context *clCxt, void *dst, size_t dpitch, int dst_offset,
489
                                const void *src, size_t spitch,
N
Niko 已提交
490
                                size_t width, size_t height, int src_offset)
491 492 493 494 495 496
        {
            size_t src_origin[3] = {src_offset % spitch, src_offset / spitch, 0};
            size_t dst_origin[3] = {dst_offset % dpitch, dst_offset / dpitch, 0};
            size_t region[3] = {width, height, 1};

            openCLSafeCall(clEnqueueCopyBufferRect(clCxt->impl->clCmdQueue, (cl_mem)src, (cl_mem)dst, src_origin, dst_origin,
497
                                                   region, spitch, 0, dpitch, 0, 0, 0, 0));
498 499 500 501 502 503 504 505 506 507 508
        }

        void openCLFree(void *devPtr)
        {
            openCLSafeCall(clReleaseMemObject((cl_mem)devPtr));
        }
        cl_kernel openCLGetKernelFromSource(const Context *clCxt, const char **source, string kernelName)
        {
            return openCLGetKernelFromSource(clCxt, source, kernelName, NULL);
        }

P
peng xiao 已提交
509
        void setBinaryDiskCache(int mode, String path)
510
        {
P
peng xiao 已提交
511 512 513 514 515 516 517
            if(mode == CACHE_NONE)
            {
                update_disk_cache = 0;
                enable_disk_cache = 0;
                return;
            }
            update_disk_cache |= (mode & CACHE_UPDATE) == CACHE_UPDATE;
518 519
            enable_disk_cache |=
#ifdef _DEBUG
520 521 522 523
                (mode & CACHE_DEBUG)   == CACHE_DEBUG;
#else
                (mode & CACHE_RELEASE) == CACHE_RELEASE;
#endif
P
peng xiao 已提交
524
            if(enable_disk_cache && !path.empty())
525
            {
P
peng xiao 已提交
526
                binpath = path;
527 528
            }
        }
529

530 531
        void setBinpath(const char *path)
        {
P
peng xiao 已提交
532
            binpath = path;
533 534
        }

Y
yao 已提交
535 536 537
        int savetofile(const Context*,  cl_program &program, const char *fileName)
        {
            size_t binarySize;
538
            openCLSafeCall(clGetProgramInfo(program,
Y
yao 已提交
539 540 541 542 543
                                    CL_PROGRAM_BINARY_SIZES,
                                    sizeof(size_t),
                                    &binarySize, NULL));
            char* binary = (char*)malloc(binarySize);
            if(binary == NULL)
544
            {
Y
yao 已提交
545
                CV_Error(CV_StsNoMem, "Failed to allocate host memory.");
546 547
            }
            openCLSafeCall(clGetProgramInfo(program,
Y
yao 已提交
548 549 550 551
                                    CL_PROGRAM_BINARIES,
                                    sizeof(char *),
                                    &binary,
                                    NULL));
552

Y
yao 已提交
553 554
            FILE *fp = fopen(fileName, "wb+");
            if(fp != NULL)
555
            {
Y
yao 已提交
556 557 558
                fwrite(binary, binarySize, 1, fp);
                free(binary);
                fclose(fp);
559 560 561 562 563
            }
            return 1;
        }

        cl_kernel openCLGetKernelFromSource(const Context *clCxt, const char **source, string kernelName,
564
                                            const char *build_options)
565 566 567 568 569 570
        {
            cl_kernel kernel;
            cl_program program ;
            cl_int status = 0;
            stringstream src_sign;
            string srcsign;
571
            string filename;
572 573 574
            CV_Assert(programCache != NULL);

            if(NULL != build_options)
575
            {
576
                src_sign << (int64)(*source) << clCxt->impl->oclcontext << "_" << build_options;
577
            }
578
            else
579
            {
580
                src_sign << (int64)(*source) << clCxt->impl->oclcontext;
581
            }
582 583 584 585 586 587 588 589 590 591
            srcsign = src_sign.str();

            program = NULL;
            program = programCache->progLookup(srcsign);

            if(!program)
            {
                //config build programs
                char all_build_options[1024];
                memset(all_build_options, 0, 1024);
592 593
                char zeromem[512] = {0};
                if(0 != memcmp(clCxt -> impl->extra_options, zeromem, 512))
594 595 596 597
                    strcat(all_build_options, clCxt -> impl->extra_options);
                strcat(all_build_options, " ");
                if(build_options != NULL)
                    strcat(all_build_options, build_options);
598 599
                if(all_build_options != NULL)
                {
P
peng xiao 已提交
600
                    filename = binpath + kernelName + "_" + clCxt->impl->devName[clCxt->impl->devnum] + all_build_options + ".clb";
601 602 603
                }
                else
                {
P
peng xiao 已提交
604
                    filename = binpath + kernelName + "_" + clCxt->impl->devName[clCxt->impl->devnum] + ".clb";
605
                }
606

P
peng xiao 已提交
607 608
                FILE *fp = enable_disk_cache ? fopen(filename.c_str(), "rb") : NULL;
                if(fp == NULL || update_disk_cache)
609
                {
610 611 612
                    if(fp != NULL)
                        fclose(fp);

613
                    program = clCreateProgramWithSource(
614
                                  clCxt->impl->oclcontext, 1, source, NULL, &status);
615
                    openCLVerifyCall(status);
616
                    status = clBuildProgram(program, 1, &(clCxt->impl->devices[clCxt->impl->devnum]), all_build_options, NULL, NULL);
P
peng xiao 已提交
617
                    if(status == CL_SUCCESS && enable_disk_cache)
618
                        savetofile(clCxt, program, filename.c_str());
619 620 621 622 623 624 625
                }
                else
                {
                    fseek(fp, 0, SEEK_END);
                    size_t binarySize = ftell(fp);
                    fseek(fp, 0, SEEK_SET);
                    char *binary = new char[binarySize];
A
Andrey Kamaev 已提交
626
                    CV_Assert(1 == fread(binary, binarySize, 1, fp));
627 628
                    fclose(fp);
                    cl_int status = 0;
629
                    program = clCreateProgramWithBinary(clCxt->impl->oclcontext,
630
                                                        1,
631
                                                        &(clCxt->impl->devices[clCxt->impl->devnum]),
632 633 634 635
                                                        (const size_t *)&binarySize,
                                                        (const unsigned char **)&binary,
                                                        NULL,
                                                        &status);
636
                    openCLVerifyCall(status);
637
                    status = clBuildProgram(program, 1, &(clCxt->impl->devices[clCxt->impl->devnum]), all_build_options, NULL, NULL);
Y
yao 已提交
638
                    delete[] binary;
639 640 641 642 643 644 645 646 647 648
                }

                if(status != CL_SUCCESS)
                {
                    if(status == CL_BUILD_PROGRAM_FAILURE)
                    {
                        cl_int logStatus;
                        char *buildLog = NULL;
                        size_t buildLogSize = 0;
                        logStatus = clGetProgramBuildInfo(program,
649
                                                          clCxt->impl->devices[clCxt->impl->devnum], CL_PROGRAM_BUILD_LOG, buildLogSize,
650
                                                          buildLog, &buildLogSize);
651 652 653 654 655
                        if(logStatus != CL_SUCCESS)
                            cout << "Failed to build the program and get the build info." << endl;
                        buildLog = new char[buildLogSize];
                        CV_DbgAssert(!!buildLog);
                        memset(buildLog, 0, buildLogSize);
656
                        openCLSafeCall(clGetProgramBuildInfo(program, clCxt->impl->devices[clCxt->impl->devnum],
657
                                                             CL_PROGRAM_BUILD_LOG, buildLogSize, buildLog, NULL));
658 659
                        cout << "\n\t\t\tBUILD LOG\n";
                        cout << buildLog << endl;
660
                        delete [] buildLog;
661 662 663 664 665 666
                    }
                    openCLVerifyCall(status);
                }
                //Cache the binary for future use if build_options is null
                if( (programCache->cacheSize += 1) < programCache->MAX_PROG_CACHE_SIZE)
                    programCache->addProgram(srcsign, program);
667 668
                else
                    cout << "Warning: code cache has been full.\n";
669 670 671 672 673 674
            }
            kernel = clCreateKernel(program, kernelName.c_str(), &status);
            openCLVerifyCall(status);
            return kernel;
        }

N
Niko 已提交
675
        void openCLVerifyKernel(const Context *clCxt, cl_kernel kernel, size_t *localThreads)
676 677
        {
            size_t kernelWorkGroupSize;
678
            openCLSafeCall(clGetKernelWorkGroupInfo(kernel, clCxt->impl->devices[clCxt->impl->devnum],
679
                                                    CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &kernelWorkGroupSize, 0));
A
Andrey Kamaev 已提交
680 681 682 683 684
            CV_Assert( localThreads[0] <= clCxt->impl->maxWorkItemSizes[0] );
            CV_Assert( localThreads[1] <= clCxt->impl->maxWorkItemSizes[1] );
            CV_Assert( localThreads[2] <= clCxt->impl->maxWorkItemSizes[2] );
            CV_Assert( localThreads[0] * localThreads[1] * localThreads[2] <= kernelWorkGroupSize );
            CV_Assert( localThreads[0] * localThreads[1] * localThreads[2] <= clCxt->impl->maxWorkGroupSize );
685 686 687 688 689 690 691
        }

#ifdef PRINT_KERNEL_RUN_TIME
        static double total_execute_time = 0;
        static double total_kernel_time = 0;
#endif
        void openCLExecuteKernel_(Context *clCxt , const char **source, string kernelName, size_t globalThreads[3],
692 693
                                  size_t localThreads[3],  vector< pair<size_t, const void *> > &args, int channels,
                                  int depth, const char *build_options)
694 695 696 697 698 699 700 701 702 703 704 705 706
        {
            //construct kernel name
            //The rule is functionName_Cn_Dn, C represent Channels, D Represent DataType Depth, n represent an integer number
            //for exmaple split_C2_D2, represent the split kernel with channels =2 and dataType Depth = 2(Data type is char)
            stringstream idxStr;
            if(channels != -1)
                idxStr << "_C" << channels;
            if(depth != -1)
                idxStr << "_D" << depth;
            kernelName += idxStr.str();

            cl_kernel kernel;
            kernel = openCLGetKernelFromSource(clCxt, source, kernelName, build_options);
707

N
niko 已提交
708
            if ( localThreads != NULL)
709
            {
N
niko 已提交
710 711 712
                globalThreads[0] = divUp(globalThreads[0], localThreads[0]) * localThreads[0];
                globalThreads[1] = divUp(globalThreads[1], localThreads[1]) * localThreads[1];
                globalThreads[2] = divUp(globalThreads[2], localThreads[2]) * localThreads[2];
713

N
Niko 已提交
714 715
                //size_t blockSize = localThreads[0] * localThreads[1] * localThreads[2];
                cv::ocl::openCLVerifyKernel(clCxt, kernel, localThreads);
N
niko 已提交
716
            }
N
Niko 已提交
717
            for(size_t i = 0; i < args.size(); i ++)
718 719 720 721
                openCLSafeCall(clSetKernelArg(kernel, i, args[i].first, args[i].second));

#ifndef PRINT_KERNEL_RUN_TIME
            openCLSafeCall(clEnqueueNDRangeKernel(clCxt->impl->clCmdQueue, kernel, 3, NULL, globalThreads,
722
                                                  localThreads, 0, NULL, NULL));
723 724 725
#else
            cl_event event = NULL;
            openCLSafeCall(clEnqueueNDRangeKernel(clCxt->impl->clCmdQueue, kernel, 3, NULL, globalThreads,
726
                                                  localThreads, 0, NULL, &event));
727 728 729 730 731 732 733

            cl_ulong start_time, end_time, queue_time;
            double execute_time = 0;
            double total_time   = 0;

            openCLSafeCall(clWaitForEvents(1, &event));
            openCLSafeCall(clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START,
734
                                                   sizeof(cl_ulong), &start_time, 0));
735 736

            openCLSafeCall(clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END,
737
                                                   sizeof(cl_ulong), &end_time, 0));
738 739

            openCLSafeCall(clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_QUEUED,
740
                                                   sizeof(cl_ulong), &queue_time, 0));
741 742 743 744 745 746 747 748 749 750 751 752 753

            execute_time = (double)(end_time - start_time) / (1000 * 1000);
            total_time = (double)(end_time - queue_time) / (1000 * 1000);

            //	cout << setiosflags(ios::left) << setw(15) << execute_time;
            //	cout << setiosflags(ios::left) << setw(15) << total_time - execute_time;
            //	cout << setiosflags(ios::left) << setw(15) << total_time << endl;

            total_execute_time += execute_time;
            total_kernel_time += total_time;
            clReleaseEvent(event);
#endif

Y
yao 已提交
754
            clFlush(clCxt->impl->clCmdQueue);
755 756 757 758
            openCLSafeCall(clReleaseKernel(kernel));
        }

        void openCLExecuteKernel(Context *clCxt , const char **source, string kernelName,
759 760
                                 size_t globalThreads[3], size_t localThreads[3],
                                 vector< pair<size_t, const void *> > &args, int channels, int depth)
761 762
        {
            openCLExecuteKernel(clCxt, source, kernelName, globalThreads, localThreads, args,
763
                                channels, depth, NULL);
764 765
        }
        void openCLExecuteKernel(Context *clCxt , const char **source, string kernelName,
766 767
                                 size_t globalThreads[3], size_t localThreads[3],
                                 vector< pair<size_t, const void *> > &args, int channels, int depth, const char *build_options)
768 769 770 771

        {
#ifndef PRINT_KERNEL_RUN_TIME
            openCLExecuteKernel_(clCxt, source, kernelName, globalThreads, localThreads, args, channels, depth,
772
                                 build_options);
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
#else
            string data_type[] = { "uchar", "char", "ushort", "short", "int", "float", "double"};
            cout << endl;
            cout << "Function Name: " << kernelName;
            if(depth >= 0)
                cout << " |data type: " << data_type[depth];
            cout << " |channels: " << channels;
            cout << " |Time Unit: " << "ms" << endl;

            total_execute_time = 0;
            total_kernel_time = 0;
            cout << "-------------------------------------" << endl;

            cout << setiosflags(ios::left) << setw(15) << "excute time";
            cout << setiosflags(ios::left) << setw(15) << "lauch time";
            cout << setiosflags(ios::left) << setw(15) << "kernel time" << endl;
            int i = 0;
            for(i = 0; i < RUN_TIMES; i++)
                openCLExecuteKernel_(clCxt, source, kernelName, globalThreads, localThreads, args, channels, depth,
792
                                     build_options);
793 794 795 796 797

            cout << "average kernel excute time: " << total_execute_time / RUN_TIMES << endl; // "ms" << endl;
            cout << "average kernel total time:  " << total_kernel_time / RUN_TIMES << endl; // "ms" << endl;
#endif
        }
798

Y
yao 已提交
799 800
       double openCLExecuteKernelInterop(Context *clCxt , const char **source, string kernelName,
                                 size_t globalThreads[3], size_t localThreads[3],
801
                                 vector< pair<size_t, const void *> > &args, int channels, int depth, const char *build_options,
Y
yao 已提交
802
                                 bool finish, bool measureKernelTime, bool cleanUp)
803

Y
yao 已提交
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
        {
            //construct kernel name
            //The rule is functionName_Cn_Dn, C represent Channels, D Represent DataType Depth, n represent an integer number
            //for exmaple split_C2_D2, represent the split kernel with channels =2 and dataType Depth = 2(Data type is char)
            stringstream idxStr;
            if(channels != -1)
                idxStr << "_C" << channels;
            if(depth != -1)
                idxStr << "_D" << depth;
            kernelName += idxStr.str();

            cl_kernel kernel;
            kernel = openCLGetKernelFromSource(clCxt, source, kernelName, build_options);

            double kernelTime = 0.0;

            if( globalThreads != NULL)
            {
                if ( localThreads != NULL)
                {
                    globalThreads[0] = divUp(globalThreads[0], localThreads[0]) * localThreads[0];
                    globalThreads[1] = divUp(globalThreads[1], localThreads[1]) * localThreads[1];
                    globalThreads[2] = divUp(globalThreads[2], localThreads[2]) * localThreads[2];

                    //size_t blockSize = localThreads[0] * localThreads[1] * localThreads[2];
                    cv::ocl::openCLVerifyKernel(clCxt, kernel, localThreads);
                }
                for(size_t i = 0; i < args.size(); i ++)
                    openCLSafeCall(clSetKernelArg(kernel, i, args[i].first, args[i].second));

                if(measureKernelTime == false)
                {
                    openCLSafeCall(clEnqueueNDRangeKernel(clCxt->impl->clCmdQueue, kernel, 3, NULL, globalThreads,
                                    localThreads, 0, NULL, NULL));
                }
                else
                {
                    cl_event event = NULL;
                    openCLSafeCall(clEnqueueNDRangeKernel(clCxt->impl->clCmdQueue, kernel, 3, NULL, globalThreads,
                                    localThreads, 0, NULL, &event));

                    cl_ulong end_time, queue_time;

                    openCLSafeCall(clWaitForEvents(1, &event));

                    openCLSafeCall(clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END,
                                    sizeof(cl_ulong), &end_time, 0));

                    openCLSafeCall(clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_QUEUED,
                                    sizeof(cl_ulong), &queue_time, 0));

                    kernelTime = (double)(end_time - queue_time) / (1000 * 1000);

                    clReleaseEvent(event);
                }
            }

            if(finish)
            {
                clFinish(clCxt->impl->clCmdQueue);
            }

            if(cleanUp)
            {
                openCLSafeCall(clReleaseKernel(kernel));
            }

            return kernelTime;
        }

        // Converts the contents of a file into a string
        static int convertToString(const char *filename, std::string& s)
        {
            size_t size;
            char*  str;

            std::fstream f(filename, (std::fstream::in | std::fstream::binary));
            if(f.is_open())
            {
                size_t fileSize;
                f.seekg(0, std::fstream::end);
                size = fileSize = (size_t)f.tellg();
                f.seekg(0, std::fstream::beg);

                str = new char[size+1];
                if(!str)
                {
                    f.close();
                    return -1;
                }

                f.read(str, fileSize);
                f.close();
                str[size] = '\0';
898

Y
yao 已提交
899 900 901 902 903 904 905 906 907 908
                s = str;
                delete[] str;
                return 0;
            }
            printf("Error: Failed to open file %s\n", filename);
            return -1;
        }

        double openCLExecuteKernelInterop(Context *clCxt , const char **fileName, const int numFiles, string kernelName,
                                 size_t globalThreads[3], size_t localThreads[3],
909
                                 vector< pair<size_t, const void *> > &args, int channels, int depth, const char *build_options,
Y
yao 已提交
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
                                 bool finish, bool measureKernelTime, bool cleanUp)

        {
            std::vector<std::string> fsource;
            for (int i = 0 ; i < numFiles ; i++)
            {
                std::string str;
                if (convertToString(fileName[i], str) >= 0)
                    fsource.push_back(str);
            }
            const char **source = new const char *[numFiles];
            for (int i = 0 ; i < numFiles ; i++)
                source[i] = fsource[i].c_str();
            double kernelTime = openCLExecuteKernelInterop(clCxt ,source, kernelName, globalThreads, localThreads,
                                 args, channels, depth, build_options, finish, measureKernelTime, cleanUp);
            fsource.clear();
            delete []source;
            return kernelTime;
        }
929 930

        cl_mem load_constant(cl_context context, cl_command_queue command_queue, const void *value,
931
                             const size_t size)
932 933 934 935 936 937 938 939
        {
            int status;
            cl_mem con_struct;

            con_struct = clCreateBuffer(context, CL_MEM_READ_ONLY, size, NULL, &status);
            openCLSafeCall(status);

            openCLSafeCall(clEnqueueWriteBuffer(command_queue, con_struct, 1, 0, size,
940
                                                value, 0, 0, 0));
941 942 943 944 945 946 947 948

            return con_struct;

        }

        /////////////////////////////OpenCL initialization/////////////////
        auto_ptr<Context> Context::clCxt;
        int Context::val = 0;
949
        static Mutex cs;
950
        static volatile int context_tear_down = 0;
951 952 953

        bool initialized()
        {
954 955
            return *((volatile int*)&Context::val) != 0 &&
                Context::clCxt->impl->clCmdQueue != NULL&&
956 957 958
                Context::clCxt->impl->oclcontext != NULL;
        }

959
        Context* Context::getContext()
960
        {
961
            if(*((volatile int*)&val) != 1)
962
            {
N
niko 已提交
963
                AutoLock al(cs);
964 965
                if(*((volatile int*)&val) != 1)
                {
966 967
                    if (context_tear_down)
                        return clCxt.get();
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
                    if( 0 == clCxt.get())
                        clCxt.reset(new Context);
                    std::vector<Info> oclinfo;
                    CV_Assert(getDevice(oclinfo, CVCL_DEVICE_TYPE_ALL) > 0);

                    *((volatile int*)&val) = 1;
                }
            }
            return clCxt.get();
        }

        void Context::setContext(Info &oclinfo)
        {
            AutoLock guard(cs);
            if(*((volatile int*)&val) != 1)
            {
                if( 0 == clCxt.get())
985 986
                    clCxt.reset(new Context);

987 988 989
                clCxt.get()->impl = oclinfo.impl->copy();

                *((volatile int*)&val) = 1;
990 991 992
            }
            else
            {
993 994
                clCxt.get()->impl->release();
                clCxt.get()->impl = oclinfo.impl->copy();
995 996
            }
        }
997

998 999
        Context::Context()
        {
1000
            impl = 0;
1001 1002 1003 1004 1005
            programCache = ProgramCache::getProgramCache();
        }

        Context::~Context()
        {
1006 1007 1008 1009 1010 1011 1012
            release();
        }

        void Context::release()
        {
            if (impl)
                impl->release();
1013 1014
            programCache->releaseProgram();
        }
1015 1016 1017 1018 1019 1020 1021 1022 1023

        bool Context::supportsFeature(int ftype)
        {
            switch(ftype)
            {
            case CL_DOUBLE:
                return impl->double_support == 1;
            case CL_UNIFIED_MEM:
                return impl->unified_memory == 1;
1024 1025
            case CL_VER_1_2:
                return impl->clVersion.find("OpenCL 1.2") != string::npos;
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
            default:
                return false;
            }
        }

        size_t Context::computeUnits()
        {
            return impl->maxComputeUnits;
        }

        void* Context::oclContext()
        {
            return impl->oclcontext;
        }

        void* Context::oclCommandQueue()
        {
            return impl->clCmdQueue;
        }

1046 1047 1048 1049
        Info::Info()
        {
            impl = new Impl;
        }
1050

1051 1052
        void Info::release()
        {
1053
            fft_teardown();
1054
            clBlasTeardown();
1055 1056
            impl->release();
            impl = new Impl;
1057
            DeviceName.clear();
1058
        }
1059

1060 1061
        Info::~Info()
        {
1062
            fft_teardown();
1063
            clBlasTeardown();
1064
            impl->release();
1065
        }
1066

1067 1068
        Info &Info::operator = (const Info &m)
        {
1069 1070 1071
            impl->release();
            impl = m.impl->copy();
            DeviceName = m.DeviceName;
1072 1073
            return *this;
        }
1074

1075 1076
        Info::Info(const Info &m)
        {
1077 1078
            impl = m.impl->copy();
            DeviceName = m.DeviceName;
1079 1080 1081 1082
        }
    }//namespace ocl

}//namespace cv