Exemple #1
0
 /// Creates a new context object for \p context. If \p retain is
 /// \c true, the reference count for \p context will be incremented.
 explicit context(cl_context context, bool retain = true)
     : m_context(context)
 {
     if(m_context && retain){
         clRetainContext(m_context);
     }
 }
Exemple #2
0
status_t ocl_engine_t::init() {
    CHECK(cl_engine_t::init());

    cl_int err = CL_SUCCESS;
    if (is_user_context_) {
        err = clRetainContext(context_);
        if (err != CL_SUCCESS)
            context_ = nullptr;
    } else {
        context_
                = clCreateContext(nullptr, 1, &device_, nullptr, nullptr, &err);
    }

    OCL_CHECK(err);

    status_t status
            = ocl_utils::check_device(engine_kind::gpu, device_, context_);
    if (status != status::success)
        return status;

    stream_t *service_stream_ptr;
    status = create_stream(&service_stream_ptr, stream_flags::default_flags);
    if (status != status::success)
        return status;
    service_stream_.reset(service_stream_ptr);
    return status::success;
}
Exemple #3
0
 /// Creates a new context object as a copy of \p other.
 context(const context &other)
     : m_context(other.m_context)
 {
     if(m_context){
         clRetainContext(m_context);
     }
 }
Exemple #4
0
cl_int WINAPI wine_clRetainContext(cl_context context)
{
    cl_int ret;
    TRACE("(%p)\n", context);
    ret = clRetainContext(context);
    TRACE("(%p)=%d\n", context, ret);
    return ret;
}
Exemple #5
0
 Context Context::operator=(const Context rhs) {
     if (contextId != rhs.contextId) {
         if (contextId != 0) CHECK_FOR_CL_ERROR(clReleaseContext(contextId));
         contextId = rhs.contextId;
         if (contextId != 0) CHECK_FOR_CL_ERROR(clRetainContext(contextId));
     } 
     return *this;
 }
Exemple #6
0
			Context& Context::operator=( const Context& other ) {
				if( *this != other ){
					clReleaseContext( mID );
					mID = other.mID;
					clRetainContext( mID );
				}
				
				return *this;
			}
int main() {
  
   /* Host/device data structures */
   cl_platform_id platform;
   cl_device_id device;
   cl_context context;
   cl_int err;
   cl_uint ref_count;

   /* Access the first installed platform */
   err = clGetPlatformIDs(1, &platform, NULL);
   if(err < 0) {
      perror("Couldn't find any platforms");
      exit(1);
   }

   /* Access the first available device */
   err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL);
   if(err == CL_DEVICE_NOT_FOUND) {
      err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_CPU, 1, &device, NULL);
   }
   if(err < 0) {
      perror("Couldn't find any devices");
      exit(1);
   }

   /* Create the context */
   context = clCreateContext(NULL, 1, &device, NULL, NULL, &err);
   if(err < 0) {
      perror("Couldn't create a context");
      exit(1);   
   }

   /* Determine the reference count */
   err = clGetContextInfo(context, CL_CONTEXT_REFERENCE_COUNT, 	
         sizeof(ref_count), &ref_count, NULL);			
   if(err < 0) {		
      perror("Couldn't read the reference count.");
      exit(1);
   }
   printf("Initial reference count: %u\n", ref_count);

   /* Update and display the reference count */
   clRetainContext(context);						
   clGetContextInfo(context, CL_CONTEXT_REFERENCE_COUNT, 		
         sizeof(ref_count), &ref_count, NULL);			
   printf("Reference count: %u\n", ref_count);			
   
   clReleaseContext(context);						
   clGetContextInfo(context, CL_CONTEXT_REFERENCE_COUNT, 		
         sizeof(ref_count), &ref_count, NULL);			
   printf("Reference count: %u\n", ref_count);			

   clReleaseContext(context);						
   return 0;
}
Exemple #8
0
/*!
    Sets the native OpenCL context identifier associated with this
    object to \a id.

    This function will call \c{clRetainContext()} to increase the
    reference count on \a id.  If the identifier was previously set
    to something else, then \c{clReleaseContext()} will be called
    on the previous value.

    \sa contextId(), create()
*/
void QCLContext::setContextId(cl_context id)
{
    Q_D(QCLContext);
    if (d->id == id || !id)
        return;
    release();
    clRetainContext(id);
    d->id = id;
    d->isCreated = true;
}
Exemple #9
0
/**
 * 
 * Creates an OpenCL context from a device type that identifies
 * the specific device(s) to use
 * 
 * properties specifies a list of context property names and their
 * corresponding values. Each property name is immediately
 * followed by the corresponding desired value. The list is
 * terminated with 0. properties is currently is reserved and
 * must be NULL.
 * 
 * device_type is a bit-field that identifies the type of device
 * and is described in table 4.2 in section 4.2.
 * 
 * pfn_notify and user_data are described in clCreateContext.
 * 
 * errcode_ret will return an appropriate error code. If
 * errcode_ret is NULL, no error code is returned.
 * 
 */
extern cl_context clCreateContextFromType
  (cl_context_properties * properties,
   cl_device_type device_type,
   logging_fn pfn_notify, void *user_data, cl_int * errcode_ret)
{

  PRINT_DEBUG("\n====\tCreating context from type\t====\n");

  if (properties != NULL)
    {
      setErrCode(errcode_ret, CL_INVALID_VALUE);
      return (cl_context) 0;
    }


  if (device_type == CL_DEVICE_TYPE_CPU)
    {
      PRINT_DEBUG("Creating cell context\n");

      cl_context context = createCellContext (errcode_ret);

      if (errcode_ret != NULL && *errcode_ret != CL_SUCCESS)
	return (cl_context) 0;

      context->prop = properties;
      context->device_count = 1;
      context->ref_count = 0;
      
      cl_device_id *device_id = malloc(sizeof (cl_device_id *));

      cl_int err = clGetDeviceIDs(CL_DEVICE_TYPE_CPU, 1, device_id, NULL);

      if (err != CL_SUCCESS)
	{
	  setErrCode(errcode_ret, err);
	  return (cl_context) 0;
	}

      context->device_list = device_id;

      PRINT_DEBUG("Performing implicit context retain\n");

      clRetainContext (context);

      PRINT_DEBUG("====\tReturning context from type\t====\n");

      return context;
    }
  else
    {
      *errcode_ret = CL_INVALID_DEVICE;
      return (cl_context) 0;
    }

}
Exemple #10
0
/**
 * gopencl_context_ref:
 * @self: an instance of GopenclContext.
 *
 * Increments the object reference count.
 *
 * Returns: the instance itself.
 *
 * Since: 0.1
 */
gpointer
gopencl_context_ref (GopenclContext *self)
{
    GopenclContextPrivate *priv = GOPENCL_CONTEXT_GET_PRIVATE(self);
    cl_int err = CL_SUCCESS;

    err = clRetainContext(priv->cl_context);
    if (err != CL_SUCCESS) {
        // TODO
    }
    g_object_ref(self);
}
Exemple #11
0
    /// Copies the context object from \p other to \c *this.
    context& operator=(const context &other)
    {
        if(this != &other){
            if(m_context){
                clReleaseContext(m_context);
            }

            m_context = other.m_context;

            if(m_context){
                clRetainContext(m_context);
            }
        }

        return *this;
    }
void
setup_context(cl_context c) {
  cl_int err;
  cl_device_id *devs;
  size_t sz;

  if (ctx != NULL) {
    clReleaseContext(ctx);
    clReleaseCommandQueue(q);
  }
  ctx = c;
  clRetainContext(ctx);

  err = clGetContextInfo(ctx, CL_CONTEXT_DEVICES, 0, NULL, &sz);
  if (err != CL_SUCCESS) {
    fprintf(stderr, "clGetContextInfo = %d\n", err);
    goto fail;
  }

  devs = (cl_device_id *)malloc(sz);
  if (devs == NULL) goto fail;

  err = clGetContextInfo(ctx, CL_CONTEXT_DEVICES, sz, devs, NULL);
  if (err != CL_SUCCESS) goto fail_dev;

  dev = devs[0];
  free(devs);

  q = clCreateCommandQueue(ctx, dev, NULL, &err);
  if (err != CL_SUCCESS) {
    fprintf(stderr, "clCreateCommandQueue = %d", err);
    goto fail;
  }

  return;
 fail_dev:
  free(devs);
 fail:
  clReleaseContext(ctx);
  ctx = NULL;
}
Exemple #13
0
UfoNode *
ufo_gpu_node_new (gpointer context, gpointer device)
{
    UfoGpuNode *node;
    cl_int errcode;
    cl_command_queue_properties queue_properties;

    g_return_val_if_fail (context != NULL && device != NULL, NULL);

    queue_properties = CL_QUEUE_PROFILING_ENABLE;

    node = UFO_GPU_NODE (g_object_new (UFO_TYPE_GPU_NODE, NULL));
    node->priv->context = context;
    node->priv->device = device;
    node->priv->cmd_queue = clCreateCommandQueue (context, device, queue_properties, &errcode);

    UFO_RESOURCES_CHECK_CLERR (errcode);
    UFO_RESOURCES_CHECK_CLERR (clRetainContext (context));

    return UFO_NODE (node);
}
Exemple #14
0
			Context::Context( cl_context context ) : mID( context ) {
				clRetainContext( mID );
			}
Exemple #15
0
WEAK void halide_init_kernels(void *user_context, const char* src, int size) {
    int err;
    cl_device_id dev;
    // Initialize one shared context for all Halide compiled instances
    if (!(*cl_ctx)) {
        const cl_uint maxPlatforms = 4;
        cl_platform_id platforms[maxPlatforms];
        cl_uint platformCount = 0;

        err = clGetPlatformIDs( maxPlatforms, platforms, &platformCount );
        CHECK_ERR( err, "clGetPlatformIDs" );

        cl_platform_id platform = NULL;

        // Find the requested platform, or the first if none specified.
        const char * name = getenv("HL_OCL_PLATFORM");
        if (name != NULL) {
            for (cl_uint i = 0; i < platformCount; ++i) {
                const cl_uint maxPlatformName = 256;
                char platformName[maxPlatformName];
                err = clGetPlatformInfo( platforms[i], CL_PLATFORM_NAME, maxPlatformName, platformName, NULL );
                if (err != CL_SUCCESS) continue;

                if (strstr(platformName, name))
                {
                    platform = platforms[i];
                    break;
                }
            }
        } else if (platformCount > 0) {
            platform = platforms[0];
        }
        if (platform == NULL){
            halide_printf(user_context, "Failed to find OpenCL platform\n");
            return;
        }

        #ifdef DEBUG
        const cl_uint maxPlatformName = 256;
        char platformName[maxPlatformName];
        err = clGetPlatformInfo( platform, CL_PLATFORM_NAME, maxPlatformName, platformName, NULL );
        CHECK_ERR( err, "clGetPlatformInfo" );

        halide_printf(user_context, "Got platform '%s', about to create context (t=%lld)\n",
                      platformName, (long long)halide_current_time_ns(user_context));
        #endif

        cl_device_type device_type = 0;
        // Find the device types requested.
        const char * dev_type = getenv("HL_OCL_DEVICE");
        if (dev_type != NULL) {
            if (strstr("cpu", dev_type))
                device_type |= CL_DEVICE_TYPE_CPU;
            if (strstr("gpu", dev_type))
                device_type |= CL_DEVICE_TYPE_GPU;
        } 
        // If no devices are specified yet, just use all.
        if (device_type == 0)
            device_type = CL_DEVICE_TYPE_ALL;
        
        // Make sure we have a device
        const cl_uint maxDevices = 4;
        cl_device_id devices[maxDevices];
        cl_uint deviceCount = 0;
        err = clGetDeviceIDs( platform, device_type, maxDevices, devices, &deviceCount );
        CHECK_ERR( err, "clGetDeviceIDs" );
        if (deviceCount == 0) {
            halide_printf(user_context, "Failed to get device\n");
            return;
        }

        dev = devices[deviceCount-1];

        #ifdef DEBUG
        const cl_uint maxDeviceName = 256;
        char deviceName[maxDeviceName];
        err = clGetDeviceInfo( dev, CL_DEVICE_NAME, maxDeviceName, deviceName, NULL );
        CHECK_ERR( err, "clGetDeviceInfo" );

        halide_printf(user_context, "Got device '%s', about to create context (t=%lld)\n",
                      deviceName, (long long)halide_current_time_ns(user_context));
        #endif


        // Create context
        cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0 };
        *cl_ctx = clCreateContext(properties, 1, &dev, NULL, NULL, &err);
        CHECK_ERR( err, "clCreateContext" );
        // cuEventCreate(&__start, 0);
        // cuEventCreate(&__end, 0);

        halide_assert(user_context, !(*cl_q));
        *cl_q = clCreateCommandQueue(*cl_ctx, dev, 0, &err);
        CHECK_ERR( err, "clCreateCommandQueue" );
    } else {
        #ifdef DEBUG
        halide_printf(user_context, "Already had context %p\n", *cl_ctx);
        #endif

        // Maintain ref count of context.
        CHECK_CALL( clRetainContext(*cl_ctx), "clRetainContext" );
        CHECK_CALL( clRetainCommandQueue(*cl_q), "clRetainCommandQueue" );

        CHECK_CALL( clGetContextInfo(*cl_ctx, CL_CONTEXT_DEVICES, sizeof(dev), &dev, NULL), "clGetContextInfo" );
    }

    // Initialize a module for just this Halide module
    if ((!__mod) && (size > 1)) {
        // Create module

        cl_device_id devices[] = { dev };
        size_t lengths[] = { size };

        if (strstr(src, "/*OpenCL C*/")) {
            // Program is OpenCL C.

            #ifdef DEBUG
            halide_printf(user_context, "Compiling OpenCL C kernel: %s\n\n", src);
            #endif

            const char * sources[] = { src };
            __mod = clCreateProgramWithSource(*cl_ctx, 1, &sources[0], NULL, &err );
            CHECK_ERR( err, "clCreateProgramWithSource" );
        } else {
            // Program is SPIR binary.

            #ifdef DEBUG
            halide_printf(user_context, "Compiling SPIR kernel (%i bytes)\n", size);
            #endif

            const unsigned char * binaries[] = { (unsigned char *)src };
            __mod = clCreateProgramWithBinary(*cl_ctx, 1, devices, lengths, &binaries[0], NULL, &err );
            CHECK_ERR( err, "clCreateProgramWithBinary" );
        }

        err = clBuildProgram( __mod, 1, &dev, NULL, NULL, NULL );
        if (err != CL_SUCCESS) {
            size_t len;
            char buffer[2048];

            halide_printf(user_context, "Error: Failed to build program executable! err = %d\n", err);
            if (clGetProgramBuildInfo(__mod, dev, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len) == CL_SUCCESS)
                halide_printf(user_context, "Build Log:\n %s\n-----\n", buffer);
            else
                halide_printf(user_context, "clGetProgramBuildInfo failed to get build log!\n");
            halide_assert(user_context, err == CL_SUCCESS);
        }
    }
}
Exemple #16
0
 Context::Context(const Context& c) 
     : contextId(c.contextId), devices(c.devices) {
     if (contextId != 0) CHECK_FOR_CL_ERROR(clRetainContext(contextId));
 }
PIGLIT_CL_API_TEST_CONFIG_END


enum piglit_result
piglit_cl_test(const int argc,
               const char** argv,
               const struct piglit_cl_api_test_config* config,
               const struct piglit_cl_api_test_env* env)
{
	int ref_count = 0;
	const int max_ref_count = 10;
	cl_int errNo;
	cl_uint* ref_count_ptr;
	cl_context cl_ctx;

	cl_context_properties context_properties[] = {
		CL_CONTEXT_PLATFORM, (cl_context_properties)env->platform_id,
		0
	};

	/*** Normal usage ***/

	cl_ctx = clCreateContextFromType(context_properties,
	                                 CL_DEVICE_TYPE_ALL,
	                                 NULL,
	                                 NULL,
	                                 &errNo);
	if(errNo == CL_DEVICE_NOT_FOUND) {
		fprintf(stderr, "No available devices.\n");
		return PIGLIT_SKIP;
	}
	if(!piglit_cl_check_error(errNo, CL_SUCCESS)){
		fprintf(stderr,
		        "Failed (error code: %s): Create context.\n",
		        piglit_cl_get_error_name(errNo));
		return PIGLIT_FAIL;
	}

	ref_count_ptr =
		piglit_cl_get_context_info(cl_ctx, CL_CONTEXT_REFERENCE_COUNT);
	if(*ref_count_ptr != 1) {
		free(ref_count_ptr);
		fprintf(stderr,
		        "CL_CONTEXT_REFERENCE_COUNT should be 1 after creating context.\n");
		return PIGLIT_FAIL;
	}
	free(ref_count_ptr);
	
	/* increase by two and decrease by one on each itreation */
	for(ref_count = 1; ref_count < max_ref_count; ref_count++) {
		errNo = clRetainContext(cl_ctx);
		if(!piglit_cl_check_error(errNo, CL_SUCCESS)) {
			fprintf(stderr,
			        "clRetainContext: Failed (error code: %s): Retain context.\n",
			        piglit_cl_get_error_name(errNo));
			return PIGLIT_FAIL;
		}
		errNo = clReleaseContext(cl_ctx);
		if(!piglit_cl_check_error(errNo, CL_SUCCESS)){
			fprintf(stderr,
			        "clReleaseContext: Failed (error code: %s): Release context.\n",
			        piglit_cl_get_error_name(errNo));
			return PIGLIT_FAIL;
		}
		errNo = clRetainContext(cl_ctx);
		if(!piglit_cl_check_error(errNo, CL_SUCCESS)){
			fprintf(stderr,
			        "clRetainContext: Failed (error code: %s): Retain context.\n",
			        piglit_cl_get_error_name(errNo));
			return PIGLIT_FAIL;
		}

		/* check internal value of reference count */
		ref_count_ptr =
			piglit_cl_get_context_info(cl_ctx, CL_CONTEXT_REFERENCE_COUNT);
		if(*ref_count_ptr != (ref_count+1)) {
			free(ref_count_ptr);
			fprintf(stderr,
			        "CL_CONTEXT_REFERENCE_COUNT is not changing accordingly.\n");
			return PIGLIT_FAIL;
		}
		free(ref_count_ptr);
	}
	/* Decrease reference count to 0 */
	for(ref_count = max_ref_count; ref_count > 0; ref_count--) {
		errNo = clReleaseContext(cl_ctx);
		if(!piglit_cl_check_error(errNo, CL_SUCCESS)){
			fprintf(stderr,
			        "clReleaseContext: Failed (error code: %s): Release context.\n",
			        piglit_cl_get_error_name(errNo));
			return PIGLIT_FAIL;
		}

		/* check internal value of reference count */
		if(ref_count > 1) {
			ref_count_ptr =
				piglit_cl_get_context_info(cl_ctx,
				                           CL_CONTEXT_REFERENCE_COUNT);
			if(*ref_count_ptr != (ref_count-1)) {
				free(ref_count_ptr);
				fprintf(stderr,
				        "CL_CONTEXT_REFERENCE_COUNT is not changing accordingly.\n");
				return PIGLIT_FAIL;
			}
			free(ref_count_ptr);
		}
	}

	/*** Errors ***/

	/*
	 * CL_INVALID_CONTEXT if context is not a valid OpenCL context.
	 */
	errNo = clReleaseContext(cl_ctx);
	if(!piglit_cl_check_error(errNo, CL_INVALID_CONTEXT)) {
			fprintf(stderr,
			        "clReleaseContext: Failed (error code: %s): Trigger CL_INVALID_CONTEXT if context is not a valid context (already released).\n",
			        piglit_cl_get_error_name(errNo));
		return PIGLIT_FAIL;
	}
	errNo = clReleaseContext(NULL);
	if(!piglit_cl_check_error(errNo, CL_INVALID_CONTEXT)) {
			fprintf(stderr,
			        "clReleaseContext: Failed (error code: %s): Trigger CL_INVALID_CONTEXT if context is not a valid context (NULL).\n",
			        piglit_cl_get_error_name(errNo));
		return PIGLIT_FAIL;
	}

	return PIGLIT_PASS;
}
Exemple #18
0
 static void inc(cl_context & something)
 {
   cl_int err = clRetainContext(something);
   VIENNACL_ERR_CHECK(err);
 }
Exemple #19
0
extern
cl_program clCreateProgramWithSource (cl_context context,
                                      cl_uint count,
                                      const char **strings,
                                      const size_t *lengths,
                                      cl_int *errcode_ret)
{
  PRINT_DEBUG("\n====\tCreating program with source\t====\n");

  if(context == NULL || context == (cl_context)0)
    {
      setErrCode(errcode_ret, CL_INVALID_CONTEXT);
      return (cl_program)0;
    }

  
  if(lengths == NULL || strings == NULL || count <= 0)
    {
      setErrCode(errcode_ret, CL_INVALID_VALUE);
      return (cl_program)0;
    }

  FILE *outputFile;
  time_t seconds;
  seconds = time (NULL);
  char fileName[33];

  //convert integer to string
  sprintf(fileName,"%ld.c",seconds);

  PRINT_DEBUG("Creating file %s ...\n", fileName);
  
  if( (outputFile = fopen(fileName, "w")) == NULL)
    {
      fprintf(stderr, "Error opening file.\n");
      return (cl_program)0;
    }

  PRINT_DEBUG("File created successfully\n");
  PRINT_DEBUG("Writing to file ...\n");

  int i;
  size_t sumSourceSize = 0;
  for(i=0; i<count; i++)
    {
      fputs(strings[i], outputFile);
      sumSourceSize += lengths[i];
    }

  //close file so Lua can open it
  fclose(outputFile);

  PRINT_DEBUG("Finished writing to file.\n");

  cl_program program = malloc(sizeof(struct _cl_program));
  program->program_ref_count = 1;

  program->program_context = context;
  clRetainContext(context);

  program->program_num_devices = 0;
  program->program_devices = NULL;

  PRINT_DEBUG("Allocating memory for program_source\n");

  program->program_source = malloc(sumSourceSize);

  PRINT_DEBUG("Concatanating strings together...\n");
  //copy the first string and concat the rest
  strcpy(program->program_source, strings[0]);
  for(i=1; i<count; i++)
    {
      strcat(program->program_source, strings[i]);
    }

  lua_State *L = createLuaState();

  PRINT_DEBUG("Loading kernel file %s...\n", fileName);
  loadKernelFile(L, fileName);

  char *kernelName;
  int numArgs;

  loadNextKernel(L, &kernelName, &numArgs);

  if(numArgs < 0 || kernelName == NULL)
    {
      PRINT_DEBUG("ERROR:numArgs returned less than zero\n");
      setErrCode(errcode_ret, CL_INVALID_VALUE);
      return (cl_program)0;
    }

  
  // TODO: This next section is a bit messy.
  // It should be cleaned up.
  // Generating the linked list and then copying the data could
  //  be put into separate functions.

  //temporary linked list struct
  struct list_element {
    char *funcName;
    int numArgs;
    struct list_element * next;
  };

  struct list_element *head, *curr;

  head = NULL;

  int numKernels = 0;
  while(kernelName != NULL)
    {
      PRINT_DEBUG("Kernel name: %s  Num args: %d\n", kernelName, numArgs);

      numKernels++;

      curr = malloc(sizeof(struct list_element));
      curr->funcName = malloc(strlen(kernelName));
      strcpy(curr->funcName, kernelName);
      //free(kernelName);
      
      curr->numArgs = numArgs;
      curr->next = head;
      head = curr;
      
      loadNextKernel(L, &kernelName, &numArgs);
    }

  lua_close(L);
  //TODO: Delete the temporary file

  curr = head;

  PRINT_DEBUG("Transfering func names to program object\n");

  program->program_num_kernels = numKernels;
  program->program_kernel_names = malloc(numKernels * sizeof(char*));
  program->program_kernel_num_args = malloc(numKernels * sizeof(int));

  i=0;
  while(curr)
    {
      program->program_kernel_names[i] = malloc(strlen(curr->funcName));
      strcpy(program->program_kernel_names[i],curr->funcName);
      
      program->program_kernel_num_args[i] = curr->numArgs;

      //the structs should be freed
      curr = curr->next;
    }


  //TODO: This function probably has a bunch of memory leaks.
  PRINT_DEBUG("\n====\tReturn program  \t====\n");

  return program;

}
Exemple #20
0
WEAK void halide_init_kernels(const char* src, int size) {
    int err;
    cl_device_id dev;
    // Initialize one shared context for all Halide compiled instances
    if (!cl_ctx) {
        const cl_uint maxPlatforms = 4;
        cl_platform_id platforms[maxPlatforms];
        cl_uint platformCount = 0;

        err = clGetPlatformIDs( maxPlatforms, platforms, &platformCount );
        CHECK_ERR( err, "clGetPlatformIDs" );

        cl_platform_id platform = NULL;

        const char * name = get_opencl_platform();
        if (name != NULL) {
            for (cl_uint i = 0; i < platformCount; ++i) {
                const cl_uint maxPlatformName = 256;
                char platformName[maxPlatformName];
                err = clGetPlatformInfo( platforms[i], CL_PLATFORM_NAME, maxPlatformName, platformName, NULL );
                if (err != CL_SUCCESS) continue;

                if (strstr(platformName, name))
                {
                    platform = platforms[i];
                    break;
                }
            }
        } else if (platformCount > 0) {
            platform = platforms[0];
        }
        if (platform == NULL){
            halide_printf("Failed to find OpenCL platform\n");
            return;
        }

        #ifdef DEBUG
        const cl_uint maxPlatformName = 256;
        char platformName[maxPlatformName];
        err = clGetPlatformInfo( platform, CL_PLATFORM_NAME, maxPlatformName, platformName, NULL );
        CHECK_ERR( err, "clGetPlatformInfo" );

        halide_printf("Got platform '%s', about to create context (t=%lld)\n",
                      platformName, (long long)halide_current_time_ns());
        #endif

        // Make sure we have a device
        const cl_uint maxDevices = 4;
        cl_device_id devices[maxDevices];
        cl_uint deviceCount = 0;
        err = clGetDeviceIDs( platform, CL_DEVICE_TYPE_ALL, maxDevices, devices, &deviceCount );
        CHECK_ERR( err, "clGetDeviceIDs" );
        if (deviceCount == 0) {
            halide_printf("Failed to get device\n");
            return;
        }

        dev = devices[deviceCount-1];

        #ifdef DEBUG
        const cl_uint maxDeviceName = 256;
        char deviceName[maxDeviceName];
        err = clGetDeviceInfo( dev, CL_DEVICE_NAME, maxDeviceName, deviceName, NULL );
        CHECK_ERR( err, "clGetDeviceInfo" );

        halide_printf("Got device '%s', about to create context (t=%lld)\n",
                      deviceName, (long long)halide_current_time_ns());
        #endif


        // Create context
        cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0 };
        cl_ctx = clCreateContext(properties, 1, &dev, NULL, NULL, &err);
        CHECK_ERR( err, "clCreateContext" );
        // cuEventCreate(&__start, 0);
        // cuEventCreate(&__end, 0);

        halide_assert(!cl_q);
        cl_q = clCreateCommandQueue(cl_ctx, dev, 0, &err);
        CHECK_ERR( err, "clCreateCommandQueue" );
    } else {
        // Maintain ref count of context.
        clRetainContext(cl_ctx);
        clRetainCommandQueue(cl_q);
    }

    // Initialize a module for just this Halide module
    if ((!__mod) && (size > 1)) {
        #ifdef DEBUG
        halide_printf("Compiling kernel (%i bytes)\n", size);
        #endif

        // Create module

        cl_device_id devices[] = { dev };
        size_t lengths[] = { size };

        if (strstr(src, "/*OpenCL C*/")) {
            // Program is OpenCL C.
            const char * sources[] = { src };
            __mod = clCreateProgramWithSource(cl_ctx, 1, &sources[0], NULL, &err );
            CHECK_ERR( err, "clCreateProgramWithSource" );
        } else {
            // Program is SPIR binary.
            const unsigned char * binaries[] = { (unsigned char *)src };
            __mod = clCreateProgramWithBinary(cl_ctx, 1, devices, lengths, &binaries[0], NULL, &err );
            CHECK_ERR( err, "clCreateProgramWithBinary" );
        }

        err = clBuildProgram( __mod, 1, &dev, NULL, NULL, NULL );
        if (err != CL_SUCCESS) {
            size_t len;
            char buffer[2048];

            halide_printf("Error: Failed to build program executable! err = %d\n", err);
            if (clGetProgramBuildInfo(__mod, dev, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len) == CL_SUCCESS)
                halide_printf("%s\n", buffer);
            else
                halide_printf("clGetProgramBuildInfo failed to get build log!\n");
            halide_assert(err == CL_SUCCESS);
        }
    }
}
Exemple #21
0
			Context::Context( const Context& other ) : mID( other.mID ) {
				clRetainContext( mID );
			}