Example #1
0
cl_context get_first_platform(){
	cl_uint num_platforms;
	cl_platform_id platform;
	cl_int err = clGetPlatformIDs(1, &platform, &num_platforms);
	if (check_cl_err(err, "Failed to find a platform") || num_platforms < 1){
		return NULL;
	}
	char name[64];
	err = clGetPlatformInfo(platform, CL_PLATFORM_NAME, 64, name, NULL);
	//This error probably shouldn't happen, but check anyway
	check_cl_err(err, "Failed to get platform name");
	printf("Selecting platform: %s\n", name);

	//Try to get a GPU context on the platform
	cl_context_properties properties[] = {
		CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0
	};
	cl_context context = clCreateContextFromType(properties, CL_DEVICE_TYPE_GPU,
		cl_err_callback, NULL, &err);
	if (check_cl_err(err, "Failed to create GPU context, retrying CPU")){
		context = clCreateContextFromType(properties, CL_DEVICE_TYPE_CPU,
			NULL, NULL, &err);
		if (check_cl_err(err, "Failed to create a GPU or CPU context")){
			return NULL;
		}
	}
	return context;
}
Example #2
0
cl_context CreateContext() {
  cl_int errNum;
  cl_uint numPlatforms;
  cl_platform_id firstPlatformId;
  cl_context context = NULL;
  
  //Select platform to run on
  errNum = clGetPlatformIDs(1, &firstPlatformId, &numPlatforms);
  if(errNum != CL_SUCCESS || numPlatforms <= 0) {
    printf("Failed to find an OpenCL platform");
    return NULL;
  }
  
  //Create context on platform (try GPU if fails then CPU)
  cl_context_properties contextProperties[] = {
    CL_CONTEXT_PLATFORM,
    (cl_context_properties)firstPlatformId,
    0
  };
  context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_GPU, NULL, NULL, &errNum);
  if(errNum != CL_SUCCESS) {
    context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_CPU, NULL, NULL, &errNum);
    if(errNum != CL_SUCCESS) {
      printf("Failed to create an OpenCL context");
      return NULL;
    }
  }
  return context;
}
cl_context QHoneycombWidget::CreateContext()
{
  cl_int errNum;
  cl_uint numPlatforms;
  cl_platform_id firstPlatformId;
  cl_context context = NULL;

  // First, select an OpenCL platform to run on.  For this example, we
  // simply choose the first available platform.  Normally, you would
  // query for all available platforms and select the most appropriate one.
  errNum = clGetPlatformIDs(1, &firstPlatformId, &numPlatforms);
  if (errNum != CL_SUCCESS || numPlatforms <= 0)
  {
    std::cerr << "Failed to find any OpenCL platforms." << std::endl;
    return NULL;
  }

  // Next, create an OpenCL context on the platform.  Attempt to
  // create a GPU-based context, and if that fails, try to create
  // a CPU-based context.
  cl_context_properties contextProperties[] =
  {
#ifdef _WIN32
    CL_CONTEXT_PLATFORM,
    (cl_context_properties)firstPlatformId,
    CL_GL_CONTEXT_KHR,
    (cl_context_properties)wglGetCurrentContext(),
    CL_WGL_HDC_KHR,
    (cl_context_properties)wglGetCurrentDC(),
#elif defined( __GNUC__)
    CL_CONTEXT_PLATFORM, (cl_context_properties)clSelectedPlatformID,
    CL_GL_CONTEXT_KHR, (cl_context_properties)glXGetCurrentContext(),
    CL_GLX_DISPLAY_KHR, (cl_context_properties)glXGetCurrentDisplay(),
#elif defined(__APPLE__) 
    //todo
#endif
    0



  };
  context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_GPU,
    NULL, NULL, &errNum);
  if (errNum != CL_SUCCESS)
  {
    std::cout << "Could not create GPU context, trying CPU..." << std::endl;
    context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_CPU,
      NULL, NULL, &errNum);
    if (errNum != CL_SUCCESS)
    {
      std::cerr << "Failed to create an OpenCL GPU or CPU context." << std::endl;
      return NULL;
    }
  }

  return context;
}
Example #4
0
cl_context CreateContext() {
    cl_int errNum;
    cl_uint numPlatforms;
    cl_platform_id firstPlatformId;
    cl_context context = NULL;

    // First, select an OpenCL platform to run on.  For this example, we
    // simply choose the first available platform.  Normally, you would
    // query for all available platforms and select the most appropriate one.



    errNum = clGetPlatformIDs(1, &firstPlatformId, &numPlatforms);



    if (errNum != CL_SUCCESS || numPlatforms <= 0)
    {
        printf("Failed to find any OpenCL platforms.\n");
        return NULL;
    }



    // Next, create an OpenCL context on the platform.  Attempt to
    // create a GPU-based context, and if that fails, try to create
    // a CPU-based context.
    cl_context_properties contextProperties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)firstPlatformId, 0 };


    if (CPUGPUFLAG == 1)
    {
    	context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_GPU, NULL, NULL, &errNum);
    	if (errNum != CL_SUCCESS)
    	{
    		printf("Could not create GPU context.\n");
    		return NULL;
    	}
    }


    if (CPUGPUFLAG == 0)
    {
    	context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_CPU, NULL, NULL, &errNum);
    	if (errNum != CL_SUCCESS)
    	{
    		printf("Failed to create an OpenCL GPU or CPU context.\n");
    		return NULL;
    	}

    }


    return context;
}
cl_int OCL_Platform::init(cl_platform_id id)
{
	cl_int err;
	mID = id;

	// store name
	size_t nameSize;
	OCL_RETURN_ON_ERR( clGetPlatformInfo( mID, CL_PLATFORM_NAME, 0, NULL, &nameSize ) );

	sPlatformName = new char[nameSize];
	OCL_RETURN_ON_ERR( clGetPlatformInfo( mID, CL_PLATFORM_NAME, nameSize, sPlatformName, NULL ) );

	// store extensions
	size_t extensionsSize;
	OCL_RETURN_ON_ERR( clGetPlatformInfo( mID, CL_PLATFORM_EXTENSIONS, 0, NULL, &extensionsSize ) );

	sPlatformExtensions = new char[extensionsSize];
	OCL_RETURN_ON_ERR( clGetPlatformInfo( mID, CL_PLATFORM_EXTENSIONS, extensionsSize, sPlatformExtensions, NULL ) );

	// default device type 
	cl_device_type deviceType = CL_DEVICE_TYPE_ALL;

	cl_context_properties ctxProps[] = 
	{
		CL_CONTEXT_PLATFORM, 
		(cl_context_properties)mID, 
		0 
	};

	OCL_RETURN_ON_ERR( ( mContext = clCreateContextFromType( ctxProps, deviceType, NULL, NULL, &err ), err));

	// Create array of devices
	size_t dev_ids_size;
	OCL_RETURN_ON_ERR( clGetContextInfo( mContext, CL_CONTEXT_DEVICES, 0, NULL, &dev_ids_size ) );

	uiNumDevices = (cl_uint)dev_ids_size/sizeof(cl_device_id);
	cl_device_id* pDeviceIDs = (cl_device_id*)calloc(1,dev_ids_size);

	mpDevices = new OCL_DeviceAndQueue[uiNumDevices];

	OCL_RETURN_ON_ERR( clGetContextInfo( mContext, CL_CONTEXT_DEVICES, dev_ids_size, pDeviceIDs, NULL ) );

	for( cl_uint j=0; j<uiNumDevices; j++ )
	{
		OCL_RETURN_ON_ERR( mpDevices[j].init( mContext, pDeviceIDs[j] ) );
		OCL_RETURN_ON_ERR( 
			(mpDevices[j].mContext = clCreateContextFromType( ctxProps, deviceType, NULL, NULL, &err )
			,err ));
	}

	delete pDeviceIDs;

	return CL_SUCCESS;
}
Example #6
0
bool createContext()
{
    cl_int err = 0;
    cl_uint numberOfPlatforms = 0;
    cl_platform_id firstPlatformID = 0;

    /* Retrieve a single platform ID. */
    err = clGetPlatformIDs(1, &firstPlatformID, &numberOfPlatforms);
    if(err != CL_SUCCESS)
    {
        printf("Error: Failed clGetPlatformIds\n");
        return false;
    }

    if (numberOfPlatforms <= 0)
    {
        printf("No OpenCL platforms found.\n");
        return false;
    }

    /* Get a context with a GPU device from the platform found above. */
    cl_context_properties contextProperties [] = {CL_CONTEXT_PLATFORM, (cl_context_properties)firstPlatformID, 0};
    ocl.context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_GPU, NULL, NULL, &err);
    if (err != CL_SUCCESS)
    {
        printf("Creating an OpenCL context failed.\n");
        return false;
    }

    return true;

}
Example #7
0
oclHardware getOclHardware(cl_device_type type)
{
    oclHardware hardware = {0, 0, 0, 0, 0, 0};
    cl_platform_id platforms[16] = { 0 };
    cl_device_id devices[16];
    char platformName[256];
    char deviceName[256];
    cl_uint platformCount = 0;
    cl_int err = clGetPlatformIDs(0, 0, &platformCount);
    err = clGetPlatformIDs(16, platforms, &platformCount);
    if (err != CL_SUCCESS) {
        std::cout << oclErrorCode(err) << "\n";
        return hardware;
    }

    for (cl_uint i = 0; i < platformCount; i++) {
        err = clGetPlatformInfo(platforms[i], CL_PLATFORM_NAME, 256, platformName, 0);
        if (err != CL_SUCCESS) {
            std::cout << oclErrorCode(err) << "\n";
            return hardware;
        }
        cl_uint deviceCount = 0;
        
        err = clGetDeviceIDs(platforms[i], type, 16, devices, &deviceCount);
          
          
        //err = clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_CPU, 16, devices, &deviceCount);

        if ((err != CL_SUCCESS) || (deviceCount == 0)) {
            continue;
        }

        err = clGetDeviceInfo(devices[0], CL_DEVICE_NAME, 256, deviceName, 0);
        if (err != CL_SUCCESS) {
            std::cout << oclErrorCode(err) << "\n";
            return hardware;
        }

        cl_context_properties contextData[3] = {CL_CONTEXT_PLATFORM, (cl_context_properties)platforms[i], 0};
        cl_context context = clCreateContextFromType(contextData, type, 0, 0, &err);
        if (err != CL_SUCCESS) {
            continue;
        }
        cl_command_queue queue = clCreateCommandQueue(context, devices[0], 0, &err);
        if (err != CL_SUCCESS) {
            std::cout << oclErrorCode(err) << "\n";
            return hardware;
        }
        hardware.mPlatform = platforms[i];
        hardware.mContext = context;
        hardware.mDevice = devices[0];
        hardware.mQueue = queue;
        getDeviceVersion(hardware);
        std::cout << "Platform = " << platformName << "\n";
        std::cout << "Device = " << deviceName << "\n";
        std::cout << "OpenCL Version = " << hardware.mMajorVersion << '.' << hardware.mMinorVersion << "\n";
        return hardware;
    }
    return hardware;
}
Example #8
0
static int initialize(int use_gpu)
{
	cl_int result;
	size_t size;

#ifndef POCL_HSA
	// create OpenCL context
	cl_platform_id platform_id;
	if (clGetPlatformIDs(1, &platform_id, NULL) != CL_SUCCESS) { printf("ERROR: clGetPlatformIDs(1,*,0) failed\n"); return -1; }
	cl_context_properties ctxprop[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform_id, 0};
	device_type = use_gpu ? CL_DEVICE_TYPE_GPU : CL_DEVICE_TYPE_CPU;
	context = clCreateContextFromType( ctxprop, device_type, NULL, NULL, NULL );
#else
	context = poclu_create_any_context();
#endif
	if( !context ) { printf("ERROR: clCreateContextFromType(%s) failed\n", use_gpu ? "GPU" : "CPU"); return -1; }

	// get the list of GPUs
	result = clGetContextInfo( context, CL_CONTEXT_DEVICES, 0, NULL, &size );
	num_devices = (int) (size / sizeof(cl_device_id));
	
	if( result != CL_SUCCESS || num_devices < 1 ) { printf("ERROR: clGetContextInfo() failed\n"); return -1; }
	device_list = new cl_device_id[num_devices];
	if( !device_list ) { printf("ERROR: new cl_device_id[] failed\n"); return -1; }
	result = clGetContextInfo( context, CL_CONTEXT_DEVICES, size, device_list, NULL );
	if( result != CL_SUCCESS ) { printf("ERROR: clGetContextInfo() failed\n"); return -1; }

	// create command queue for the first device
	cmd_queue = clCreateCommandQueue( context, device_list[0], 0, NULL );
	if( !cmd_queue ) { printf("ERROR: clCreateCommandQueue() failed\n"); return -1; }

	return 0;
}
Example #9
0
static int initialize(int use_device)
{
	cl_int result;
	size_t size;

	// create OpenCL context
	cl_platform_id platform_id;
	if (clGetPlatformIDs(1, &platform_id, NULL) != CL_SUCCESS) { printf("ERROR: clGetPlatformIDs(1,*,0) failed\n"); return -1; }
	cl_context_properties ctxprop[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform_id, 0};
	//device_type = use_device ? CL_DEVICE_TYPE_GPU : CL_DEVICE_TYPE_CPU;
        switch(use_device) {
            case 0: device_type = CL_DEVICE_TYPE_CPU; break;
            case 1: device_type = CL_DEVICE_TYPE_GPU; break;
            case 2: device_type = CL_DEVICE_TYPE_ACCELERATOR; break;
        }
	context = clCreateContextFromType( ctxprop, device_type, NULL, NULL, NULL );
	if( !context ) { printf("ERROR: clCreateContextFromType(%s) failed\n", use_device ? "GPU" : "CPU"); return -1; }

	// get the list of GPUs
	result = clGetContextInfo( context, CL_CONTEXT_DEVICES, 0, NULL, &size );
	num_devices = (int) (size / sizeof(cl_device_id));
	printf("num_devices = %d\n", num_devices);
	
	if( result != CL_SUCCESS || num_devices < 1 ) { printf("ERROR: clGetContextInfo() failed\n"); return -1; }
	device_list = new cl_device_id[num_devices];
	//device_list = (cl_device_id *)malloc(sizeof(cl_device_id)*num_devices);
	if( !device_list ) { printf("ERROR: new cl_device_id[] failed\n"); return -1; }
	result = clGetContextInfo( context, CL_CONTEXT_DEVICES, size, device_list, NULL );
	if( result != CL_SUCCESS ) { printf("ERROR: clGetContextInfo() failed\n"); return -1; }

	// create command queue for the first device
	cmd_queue = clCreateCommandQueue( context, device_list[0], 0, NULL );
	if( !cmd_queue ) { printf("ERROR: clCreateCommandQueue() failed\n"); return -1; }
	return 0;
}
Example #10
0
 context(cl_device_type t, cl_context_properties *props = 0)
 {
   cl_int status;
   impl_ = clCreateContextFromType(props, t, context::callback, this, &status);
   if (status < 0)
     OVXX_DO_THROW(exception("clCreateContextFromType", status));
 }
Example #11
0
nsresult dpoCContext::InitContext(cl_platform_id platform)
{
	cl_int err_code;
	cl_device_id *devices;
	size_t cb;

	cl_context_properties context_properties[3] = {CL_CONTEXT_PLATFORM, (cl_context_properties)platform, NULL};
	
	context = clCreateContextFromType(context_properties, CL_DEVICE_TYPE_CPU, ReportCLError, this, &err_code);
	if (err_code != CL_SUCCESS) {
		DEBUG_LOG_ERROR("InitContext", err_code);
		return NS_ERROR_NOT_AVAILABLE;
	}

	err_code = clGetContextInfo(context, CL_CONTEXT_DEVICES, 0, NULL, &cb);
	if (err_code != CL_SUCCESS) {
		DEBUG_LOG_ERROR("InitContext", err_code);
		return NS_ERROR_NOT_AVAILABLE;
	}

	devices = (cl_device_id *)nsMemory::Alloc(sizeof(cl_device_id)*cb);
	if (devices == NULL) {
		DEBUG_LOG_STATUS("InitContext", "Cannot allocate device list");
		return NS_ERROR_OUT_OF_MEMORY;
	}

	err_code = clGetContextInfo(context, CL_CONTEXT_DEVICES, cb, devices, NULL);
	if (err_code != CL_SUCCESS) {
		DEBUG_LOG_ERROR("InitContext", err_code);
		nsMemory::Free(devices);
		return NS_ERROR_NOT_AVAILABLE;
	}

	cmdQueue = clCreateCommandQueue(context, devices[0], 
#ifdef CLPROFILE 
		CL_QUEUE_PROFILING_ENABLE |
#endif /* CLPROFILE */
#ifdef OUTOFORDERQUEUE
		CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE |
#endif /* OUTOFORDERQUEUE */
		0,
		&err_code);
	if (err_code != CL_SUCCESS) {
		DEBUG_LOG_ERROR("InitContext", err_code);
		nsMemory::Free(devices);
		return NS_ERROR_NOT_AVAILABLE;
	}

	DEBUG_LOG_STATUS("InitContext", "queue is " << cmdQueue);

	nsMemory::Free(devices);

	kernelFailureMem = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(int), NULL, &err_code);
	if (err_code != CL_SUCCESS) {
		DEBUG_LOG_ERROR("InitContext", err_code);
		return NS_ERROR_NOT_AVAILABLE;
	}

	return NS_OK;
}
Example #12
0
cl_context OCLContexts::GetContextByPlatformName(
    const std::string &platName, OCLContextProperties ctx_props) {
    OCLErrorExp clerr;
    cl_context found_ctx = m_contextMap[platName];

    if ( found_ctx != NULL ) {
        return found_ctx;
    }
    cl_platform_id platform = NULL;

    for (size_t i=0; i<get_num_platforms(); i++) {
        if (get_platform_name(i) == platName ) {
            platform = m_platforms[i];
            break;
        }
    }

    ctx_props.AddProperty(CL_CONTEXT_PLATFORM, (cl_context_properties) platform);
    found_ctx = clCreateContextFromType(ctx_props, CL_DEVICE_TYPE_ALL,
                                        NULL, NULL, clerr);
    clerr.CheckError();
    if ( platform != NULL ) {
        m_contextMap[platName] = found_ctx;
    }

    return found_ctx;
}
Example #13
0
JNIContext::JNIContext(JNIEnv *jenv, jobject _kernelObject, jobject _openCLDeviceObject, jint _flags): 
      kernelObject(jenv->NewGlobalRef(_kernelObject)),
      kernelClass((jclass)jenv->NewGlobalRef(jenv->GetObjectClass(_kernelObject))), 
      openCLDeviceObject(jenv->NewGlobalRef(_openCLDeviceObject)),
      flags(_flags),
      profileBaseTime(0),
      passes(0),
      exec(NULL),
      deviceType(((flags&com_amd_aparapi_internal_jni_KernelRunnerJNI_JNI_FLAG_USE_GPU)==com_amd_aparapi_internal_jni_KernelRunnerJNI_JNI_FLAG_USE_GPU)?CL_DEVICE_TYPE_GPU:CL_DEVICE_TYPE_CPU),
      profileFile(NULL), 
      valid(JNI_FALSE){
   cl_int status = CL_SUCCESS;
   jobject platformInstance = OpenCLDevice::getPlatformInstance(jenv, openCLDeviceObject);
   cl_platform_id platformId = OpenCLPlatform::getPlatformId(jenv, platformInstance);
   deviceId = OpenCLDevice::getDeviceId(jenv, openCLDeviceObject);
   cl_device_type returnedDeviceType;
   clGetDeviceInfo(deviceId, CL_DEVICE_TYPE,  sizeof(returnedDeviceType), &returnedDeviceType, NULL);
   //fprintf(stderr, "device[%d] CL_DEVICE_TYPE = %x\n", deviceId, returnedDeviceType);


   cl_context_properties cps[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platformId, 0 };
   cl_context_properties* cprops = (NULL == platformId) ? NULL : cps;
   context = clCreateContextFromType( cprops, returnedDeviceType, NULL, NULL, &status); 
   CLException::checkCLError(status, "clCreateContextFromType()");
   if (status == CL_SUCCESS){
      valid = JNI_TRUE;
   }
}
Example #14
0
cl_context get_platform(cl_device_type type){
	cl_uint num_platforms;
	cl_int err = clGetPlatformIDs(0, NULL, &num_platforms);
	cl_platform_id *platforms = malloc(sizeof(cl_platform_id) * num_platforms);
	err = clGetPlatformIDs(num_platforms, platforms, NULL);
	if (check_cl_err(err, "Failed to find platforms") || num_platforms < 1){
		return NULL;
	}
	cl_context_properties properties[] = {
		CL_CONTEXT_PLATFORM, 0, 0
	};
	cl_context context = NULL;
	for (size_t i = 0; i < num_platforms; ++i){
		properties[1] = (cl_context_properties)platforms[i];
		context = clCreateContextFromType(properties, type, cl_err_callback, NULL, &err);
		if (err == CL_SUCCESS){
			char name[64];
			clGetPlatformInfo(platforms[i], CL_PLATFORM_NAME, 64, name, NULL);
			printf("Selected platform: %s\n", name);
			break;
		}
	}
	free(platforms);
	return context;
}
Example #15
0
bool get_cl_context(cl_context *context, cl_device_id **devices, int num_platform)
{
    if (context == NULL || devices == NULL) return false;
    cl_platform_id *platforms = NULL;
    // The iteration variable
    int i;

    cl_uint num;
    check_err(clGetPlatformIDs(0, 0, &num), "Unable to get platforms");

    platforms = (cl_platform_id *)malloc(sizeof(cl_platform_id) * num);
    check_err(clGetPlatformIDs(num, platforms, NULL), "Unable to get platform ID");

    check_err(clGetPlatformIDs(0, 0, &num), "Unable to get platforms");

    printf("Found %d platforms:\n", num);
    for (i = 0; i < num; i++) {
        char str[1024];
        clGetPlatformInfo(platforms[i], CL_PLATFORM_NAME, 1024, str, NULL);
        printf("\t%d: %s\n", i, str);
    }

    cl_context_properties prop[3];
    prop[0] = CL_CONTEXT_PLATFORM;
    prop[1] = (cl_context_properties)platforms[num_platform];
    prop[2] = 0;
    cl_int err;
    *context = clCreateContextFromType(prop, CL_DEVICE_TYPE_ALL, NULL, NULL, &err);
    if (err != CL_SUCCESS) {
        printf("Can't create OpenCL context\n");
        return false;
    }

    size_t size_b;
    int    num_total_devices;
    clGetContextInfo(*context, CL_CONTEXT_DEVICES, 0, NULL, &size_b);
    *devices = (cl_device_id *)malloc(size_b);
    clGetContextInfo(*context, CL_CONTEXT_DEVICES, size_b, *devices, 0);
    if (size_b == 0) {
        printf("Can't get devices\n");
        return false;
    }
    num_total_devices = size_b / sizeof(cl_device_id);

    printf("Found %d devices:\n", num_total_devices);
    for (i = 0; i < num_total_devices; i++) {
        char devname[16][256] = {};
        clGetDeviceInfo(*devices[i], CL_DEVICE_NAME, 256, devname[i], 0);
        printf("\t%d: %s", i, devname[i]);
        clGetDeviceInfo(*devices[i], // Set the device info
                        CL_DEVICE_MAX_COMPUTE_UNITS,
                        sizeof(int),
                        &size_b,
                        0);
        printf("  - %d\n", (int)size_b);
    }

    return true;
}
Example #16
0
static cl_int create_opencl_context(cl_context *context, cl_platform_id *platform)
{
  cl_context_properties cps[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)*platform, 0 };
  cl_int status;

  *context = clCreateContextFromType(cps, CL_DEVICE_TYPE_GPU, NULL, NULL, &status);
  return status;
}
Example #17
0
ClHelper::ClHelper()
    : mContext((cl_context)0), mDeviceId((cl_device_id)0),
      mCommandQueue((cl_command_queue)0), mProgram((cl_program)0),
      mKernel((cl_kernel)0)
{
    cl_int status;

    // 플랫폼
    cl_platform_id platforms[10];
    cl_uint num_platforms;
    status = clGetPlatformIDs(sizeof(platforms) / sizeof(platforms[0]),
                              platforms,
                              &num_platforms);
    if (status != CL_SUCCESS || num_platforms <= 0) {        
        fprintf(stderr, "clGetPlatformIDs failed.\n");
        printError(status);
        throw MyError("failed to get platform IDs.",  __FUNCTION__);
    }

    cl_context_properties properties[]
        = {CL_CONTEXT_PLATFORM, (cl_context_properties)platforms[0], 0};

    // 디바이스에 따른 컨텍스트 취득
    mContext = clCreateContextFromType(properties,
                                       // CL_DEVICE_TYPE_CPU, // CPUを使用
                                       CL_DEVICE_TYPE_GPU,    // GPUを使用
                                       NULL,
                                       NULL,
                                       &status);
    if (status != CL_SUCCESS) {
        printError(status);
        throw MyError("failed to create context.",  __FUNCTION__);
    }

    // 디바이스 아이디 취득
    cl_device_id devices[10];
    status = clGetContextInfo(mContext,
                              CL_CONTEXT_DEVICES,
                              sizeof(devices),
                              devices,
                              NULL);
    if (status != CL_SUCCESS) {
        printError(status);
        throw MyError("failed to get device id.", __FUNCTION__);
    }
    mDeviceId = devices[0];

    // 커맨드 큐 생성
    mCommandQueue = clCreateCommandQueue(mContext,
                                         devices[0],
                                         0,
                                         &status);
    if (status != CL_SUCCESS) {
        printError(status);
        throw MyError("failed to create command queue.", __FUNCTION__);
    }
}
Example #18
0
SEXP createContextFromType(SEXP deviceType){
    //We need to look at this, because this does not seem to work...
    std::string deviceString = Rcpp::as<std::string>(deviceType);
    cl_context *context = new cl_context;
    if(deviceString == "CL_DEVICE_TYPE_GPU"){
        *context = clCreateContextFromType(NULL, CL_DEVICE_TYPE_GPU, NULL, NULL, NULL);
    }
    Rcpp::XPtr<cl_context> tempXPtr(context);
    return tempXPtr;
}
Example #19
0
///
// functions for preparing create opencl program, contains CreateContext, CreateProgram, CreateCommandQueue, CreateMemBuffer, and Cleanup
// Create an OpenCL context on the first available GPU platform. 
cl_context CreateContext()
{
    cl_context context = NULL;
    cl_uint platformIdCount = 0;
    cl_int errNum;

 #ifndef POCL_HSA
    // get number of platforms
    clGetPlatformIDs (0, NULL, &platformIdCount);

    std::vector<cl_platform_id> platformIds(platformIdCount);
    clGetPlatformIDs (platformIdCount, platformIds.data(), NULL);
	
	// In this example, first platform is a CPU, the second one is a GPU. we just choose the first available device.  
    cl_context_properties contextProperties[] =
    {
        CL_CONTEXT_PLATFORM,
        (cl_context_properties)platformIds[1],
        0
    };
    context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_GPU,
                                      NULL, NULL, &errNum);
    if (errNum != CL_SUCCESS)
    {
        std::cout << "Could not create GPU context, trying CPU..." << std::endl;
        context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_CPU,
                                          NULL, NULL, &errNum);
        if (errNum != CL_SUCCESS)
        {
            std::cerr << "Failed to create an OpenCL GPU or CPU context." << std::endl;
            return NULL;
        }
    }
   #else
	context = poclu_create_any_context();
   #endif
    
    return context;

}
Example #20
0
cl_context CreateContext()
{
    cl_int error_number;
    cl_uint number_platforms;
    cl_platform_id first_platform_id;
    cl_context context = NULL;

    error_number = clGetPlatformIDs(1, &first_platform_id, &number_platforms);
    if (error_number != CL_SUCCESS || number_platforms <= 0)
    {
        std::cerr << "Failed to find any OpenCL platforms." << std::endl;
        return NULL;
    }

    cl_context_properties context_properties[] = {
        CL_CONTEXT_PLATFORM,
        (cl_context_properties)first_platform_id,
        0
    };
    context = clCreateContextFromType(context_properties,
                                      CL_DEVICE_TYPE_GPU,
                                      NULL,
                                      NULL,
                                      &error_number);
    if (error_number != CL_SUCCESS)
    {
        std::cout << "Could not create GPU context, trying CPU..." << std::endl;
        context = clCreateContextFromType(context_properties,
                                          CL_DEVICE_TYPE_CPU,
                                          NULL,
                                          NULL,
                                          &error_number);
        if (error_number != CL_SUCCESS)
        {
            std::cerr << "Failed to create an OpenCL GPU or CPU context." << std::endl;
            return NULL;
        }
    }
    return context;
}
//  Create an OpenCL context on the first available platform using
//  either a GPU or CPU depending on what is available.
cl_context CreateContext(CLPlatform* platform)
{
    // Create a context from the first platform (for now)
    cl_context_properties contextProperties[] =
    {
        CL_CONTEXT_PLATFORM,
        (cl_context_properties)platform->id,
        0
    };
    cl_context context = NULL;
    cl_int errNum;
    context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_ALL, NULL, NULL, &errNum);
    return errNum == CL_SUCCESS ? context : NULL;
}
Example #22
0
cl_int init_cl_context_from_gl(clctx_t *c, cl_platform_id platform)
{
	cl_int ret=0;

	ret = clewInit();
	if (ret)
	{
		fprintf_rl(stderr, "clewInit() failed with code %d\n", ret);
		return -1024;
	}

	#ifdef RL_OPENCL_GL

	#if defined(_WIN32)		// Windows	from http://stackoverflow.com/a/30529217/1675589
	cl_context_properties properties[] =
	{
		CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(),
		CL_WGL_HDC_KHR, (cl_context_properties)wglGetCurrentDC(),
		CL_CONTEXT_PLATFORM, (cl_context_properties)platform,
		0
	};
	#elif defined(__APPLE__)	// OS X
	CGLContextObj     kCGLContext     = CGLGetCurrentContext();
	CGLShareGroupObj  kCGLShareGroup  = CGLGetShareGroup(kCGLContext);

	cl_context_properties properties[] =
	{
		CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE,
		(cl_context_properties) kCGLShareGroup,
		0
	};
	#else				// Linux
	cl_context_properties properties[] =
	{
		CL_GL_CONTEXT_KHR, (cl_context_properties)glXGetCurrentContext(),
		CL_GLX_DISPLAY_KHR, (cl_context_properties)glXGetCurrentDisplay(),
		CL_CONTEXT_PLATFORM, (cl_context_properties)platform,
		0
	};
	#endif

	//c->context = clCreateContext(NULL, ret_num_devices, device_id, NULL, NULL, &ret);
	c->context = clCreateContextFromType(properties, CL_DEVICE_TYPE_GPU, NULL, NULL, &ret);
	CL_ERR_RET("clCreateContextFromType (in init_cl_context_from_gl)", ret);

	#endif
	return ret;
}
Example #23
0
int createContext(cl_context* context)
{
    cl_int errorNumber = 0;
    cl_uint numberOfPlatforms = 0;
    cl_platform_id firstPlatformID = 0;

    /* Retrieve a single platform ID. */
    clGetPlatformIDs(1, &firstPlatformID, &numberOfPlatforms);

    /* Get a context with a GPU device from the platform found above. */
    cl_context_properties contextProperties [] = {CL_CONTEXT_PLATFORM, (cl_context_properties)firstPlatformID, 0};
    *context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_GPU, NULL, NULL, &errorNumber);

    LOGD("createContext code %d",errorNumber);
    return 1;
}
Example #24
0
File: sieve.c Project: manish05/TCR
void init() {
	cl_uint n;
	cl_platform_id *ids,id=NULL;
	int i,status;
	char s[MAXCHAR];
	/*  choose AMD platform if possible, otherwise just pick one */
	if(CL_SUCCESS!=clGetPlatformIDs(0,NULL,&n))
		error("error getting platforms 1");
	if(NULL==(ids=malloc(sizeof(cl_platform_id)*n))) error("out of memory");
	if(CL_SUCCESS!=clGetPlatformIDs(n,ids,NULL))
		error("error getting platforms 2");
	for(i=0;i<n;i++) {
		if(CL_SUCCESS!=clGetPlatformInfo(ids[i],CL_PLATFORM_VENDOR,MAXCHAR,s,NULL))
			error("error getting platform 3");
		if(!strcmp(s,"Advanced Micro Devices, Inc.")) {
			id=ids[i];
			break;
		}
	}
	if(i==n) id=ids[0];
	free(ids);
	/* get context stuff */
	cl_context_properties cps[3]={CL_CONTEXT_PLATFORM,(cl_context_properties)id,0};
	context=clCreateContextFromType(cps,CL_DEVICE_TYPE_CPU,NULL,NULL,&status);
	if(CL_SUCCESS!=status) error("couldn't create context");
	if(CL_SUCCESS!=clGetContextInfo(context,CL_CONTEXT_DEVICES,0,NULL,(size_t *)&n))
		error("error getting context info 1");
	if(!n) error("no devices!");
	if(NULL==(devices=malloc(n))) error("out of memory");
	if(CL_SUCCESS!=clGetContextInfo(context,CL_CONTEXT_DEVICES,n,devices,NULL))
		error("error getting context info 2");
	/* create opencl command queue */
	cmdq=clCreateCommandQueue(context,devices[0],0,&status);
	if(CL_SUCCESS!=status) error("error creating command queue");
	/* create memory buffers */
	initmem();
	/* copy contents of in to inbuffer */
	inbuffer=clCreateBuffer(context,CL_MEM_READ_WRITE|CL_MEM_USE_HOST_PTR,
		MAXP,in,&status);
	if(CL_SUCCESS!=status) {
		printf("max alloc %d\n",(int)CL_DEVICE_MAX_MEM_ALLOC_SIZE);
		printf("status %d\n",status);
		error("error creating input buffer");
	}
	loadkernel("sieve.cl");
}
Example #25
0
void createContextFromType(v8::FunctionArgs args)
{
    if (args.Length() == 5)
    {
        auto array = GetArray(args[0]);
        auto flags = GetNumber(args[1]);
   
        const auto platformID = cl_context_properties(UnwrapPointer(array->Get(1)));
        const auto platformType = array->Get(0)->NumberValue();
        const auto platformIndex = array->Get(2)->NumberValue();

        cl_context_properties properties[] = { (cl_prop)platformType, (cl_prop)platformID, (cl_prop)platformIndex };
        cl_context context = clCreateContextFromType(properties, flags, nullptr, nullptr, nullptr);
        
        Return(args, v8::WrapPointer(context));
    }
}
Example #26
0
/*------------------------------------------------------------------------------------------------------------
 * コンストラクタ
 */
ClHelper::ClHelper()
    :mContext((cl_context)0), mDevaiceId((cl_device_id)0),
    mCommandQueue((cl_command_queue)0), mProgram((cl_program)0),
    mKernel((cl_kernel)0)
{
    cl_int status;
    
    // create context for specified device
    mContext = clCreateContextFromType(NULL,
                               // CL_DEVICE_TYPE_CPU, // CPUを使用
                               CL_DEVICE_TYPE_GPU,    // GPUを使用
                               NULL,
                               NULL,
                               &status);
    
    if (status != CL_SUCCESS) {
        printError(status);
        throw MyError("failed to create context.", __FUNCTION__);
    }
    
    
    // get device id from context
    cl_device_id devices[10];
    
    status = clGetContextInfo(mContext,
                              CL_CONTEXT_DEVICES,
                              sizeof(devices),
                              devices,
                              NULL);
    if(status != CL_SUCCESS){
        printError(status);
        throw MyError("failed to get device id.", __FUNCTION__);
    }
    mDevaiceId = devices[0];
    
    // Create command queue
    mCommandQueue = clCreateCommandQueue(mContext,
                                         devices[0],
                                         0,
                                         &status);
    if(status != CL_SUCCESS){
        printError(status);
        throw MyError("failed to create command queue.", __FUNCTION__);
    }
}
Example #27
0
int SetCont(int plt_sel, int dev_sel, cl_context *cont)
{
    // check if the environment is valid
    // gain the device numbers
    cl_int ret = clGetDeviceIDs(platforms[plt_sel], CL_DEVICE_TYPE_ALL, 
            0, NULL, &numDevices);
    cl_errChk(ret,"Error >> clGetDeviceIDs");
    if (dev_sel > numDevices)
    {
        printf("Invalid Device Number\n");
        exit(1);
    }
    // get the select platform & device
    ret = clGetDeviceIDs(platforms[plt_sel], CL_DEVICE_TYPE_ALL,
             numDevices, Devices, NULL);

    // check the device is a CPU or GPU
    cl_device_type DeviceTyep;
    //cl_device_id DeviceID;
    //DeviceID = Devices[dev_sel];
    ret = clGetDeviceInfo(Devices[dev_sel], CL_DEVICE_TYPE,
            sizeof(DeviceTyep),(void *)&DeviceTyep,NULL);
    cl_errChk(ret,"Error >> clGetDeviceInfo_DeviceTyep");

    if(DeviceTyep == CL_DEVICE_TYPE_GPU) 
        printf("Creating GPU Context\n");
    else if (DeviceTyep == CL_DEVICE_TYPE_CPU) 
        printf("Creating CPU Context\n");
    else
        printf("This Context Type not Supported.\n");

    // Create a context
    cl_context_properties prop[3] = {CL_CONTEXT_PLATFORM, 
                    (cl_context_properties) platforms[plt_sel], 0 };
    *cont = clCreateContextFromType(prop, 
                    (cl_device_type)DeviceTyep, NULL, NULL, &ret);

    if (*cont == 0)
    {
        printf("Cannot create OpenCL context\n");
        return 0;
    }    
    
	  return 0;
}
Example #28
0
cl_context WINAPI wine_clCreateContextFromType(const cl_context_properties * properties, cl_device_type device_type,
                                               void WINAPI (*pfn_notify)(const char *errinfo, const void *private_info, size_t cb, void *user_data),
                                               void * user_data, cl_int * errcode_ret)
{
    cl_context ret;
    CONTEXT_CALLBACK *ccb;
    TRACE("(%p, 0x%lx, %p, %p, %p)\n", properties, (long unsigned int)device_type, pfn_notify, user_data, errcode_ret);
    /* FIXME: The CONTEXT_CALLBACK structure is currently leaked.
     * Pointers to callback redirectors should be remembered and free()d when the context is destroyed.
     * The problem is determining when a context is being destroyed. clReleaseContext only decrements
     * the use count for a context, its destruction can come much later and therefore there is a risk
     * that the callback could be invoked after the user_data memory has been free()d.
     */
    ccb = HeapAlloc(GetProcessHeap(), 0, sizeof(CONTEXT_CALLBACK));
    ccb->pfn_notify = pfn_notify;
    ccb->user_data = user_data;
    ret = clCreateContextFromType(properties, device_type, context_fn_notify, ccb, errcode_ret);
    TRACE("(%p, 0x%lx, %p, %p, %p (%d)))=%p\n", properties, (long unsigned int)device_type, pfn_notify, user_data, errcode_ret, errcode_ret ? *errcode_ret : 0, ret);
    return ret;
}
static void
init_context(void)
{
  cl_int err;
  cl_uint n;
  cl_platform_id *plats;
  cl_context_properties props[3];
  cl_context c;

  if (ctx != NULL) return;

  err = clGetPlatformIDs(0, NULL, &n);
  if (err != CL_SUCCESS) return;

  plats = (cl_platform_id *)calloc(n, sizeof(cl_platform_id));
  if (plats == NULL) return;

  err = clGetPlatformIDs(n, plats, NULL);
  if (err != CL_SUCCESS) goto fail_id;

  props[0] = CL_CONTEXT_PLATFORM;
  props[1] = (cl_context_properties)plats[0];
  props[2] = 0;

  c = clCreateContextFromType(props, CL_DEVICE_TYPE_GPU, NULL, NULL, &err);
  if (err != CL_SUCCESS) {
    fprintf(stderr, "Could not create context, will fail later (%d)!\n", err);
    /* error - error - error */
    /* but we do nothing */
    goto fail_id;
  }

  free(plats);

  setup_context(c);
  clReleaseContext(c);

  return;
 fail_id:
  free(plats);
}
Example #30
0
/*   Java->C glue code:
 *   Java package: com.jogamp.opencl.impl.CLImpl
 *    Java method: long clCreateContextFromType(java.nio.IntBuffer props, long device_type, CreateContextCallback pfn_notify, Object userData, IntBuffer errcode_ret)
 *     C function: cl_context clCreateContextFromType(  cl_context_properties *  properties ,
 *                                                      cl_uint                  num_devices ,
 *                                                      const cl_device_id *     devices ,
 *                                                      void (*pfn_notify)(const char *, const void *, size_t, void *)  pfn_notify/,
 *                                                      void *                   user_data ,
 *                                                      cl_int *                 errcode_ret );
 */
JNIEXPORT jlong JNICALL
Java_com_jogamp_opencl_impl_CLImpl_clCreateContextFromType0(JNIEnv *env, jobject _unused,
        jobject props, jint props_byte_offset, jobject device_type, jobject cb, jobject data, jobject errcode, jint errcode_byte_offset) {

    cl_context_properties* _props_ptr  = NULL;
    int32_t * _errcode_ptr = NULL;
    cl_context _ctx;

    if (props != NULL) {
        _props_ptr = (cl_context_properties*) (((char*) (*env)->GetDirectBufferAddress(env, props)) + props_byte_offset);
    }

    if (errcode != NULL) {
        _errcode_ptr = (void *) (((char*) (*env)->GetDirectBufferAddress(env, errcode)) + errcode_byte_offset);
    }

    //TODO callback; payload
    _ctx = clCreateContextFromType(_props_ptr, (uint64_t) device_type, NULL, NULL, (int32_t *) _errcode_ptr);

    return (jlong) (intptr_t)_ctx;
}