Пример #1
0
static GLuint make_shader(GLenum type, const char *filename)
{
    GLint length;
    GLchar *source = file_contents(filename, &length);
    GLuint shader;
    GLint shader_ok;

    if (!source)
        return 0;

    shader = glCreateShader(type);
    glShaderSource(shader, 1, (const GLchar**)&source, &length);
    free(source);
    glCompileShader(shader);

    glGetShaderiv(shader, GL_COMPILE_STATUS, &shader_ok);
    if (!shader_ok) {
        glGetShaderInfoLog(shader, sizeof(logbuf), NULL, logbuf);
        fprintf(stderr, "Failed to compile %s:\n", filename);
        fputs(logbuf, stderr);
        glDeleteShader(shader);
        return 0;
    }
    return shader;
}
Пример #2
0
void CL::loadProgram(const char* relative_path)
{
 // Program Setup
    int pl;
    size_t program_length;
    printf("load the program\n");
    
    //CL_SOURCE_DIR is set in the CMakeLists.txt
    std::string path(CL_SOURCE_DIR);
    path += "/" + std::string(relative_path);
    printf("path: %s\n", path.c_str());

    //file_contents is defined in util.cpp
    //it loads the contents of the file at the given path
    char* cSourceCL = file_contents(path.c_str(), &pl);
    //printf("file: %s\n", cSourceCL);
    program_length = (size_t)pl;

    // create the program
    program = clCreateProgramWithSource(context, 1,
                      (const char **) &cSourceCL, &program_length, &err);
    printf("clCreateProgramWithSource: %s\n", oclErrorString(err));

    buildExecutable();
   
}
Пример #3
0
JNIEXPORT jboolean JNICALL Java_com_example_LiveFeatureActivity_compileKernels(JNIEnv *env, jclass clazz)
{
    // Find OCL devices and compile kernels
    cl_int err = CL_SUCCESS;
    try {
        std::vector<cl::Platform> platforms;
        cl::Platform::get(&platforms);
        if (platforms.size() == 0) {
            return false;
        }
        cl_context_properties properties[] =
        { CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[0])(), 0};
        gContext = cl::Context(CL_DEVICE_TYPE_GPU, properties);
        std::vector<cl::Device> devices = gContext.getInfo<CL_CONTEXT_DEVICES>();
        gQueue = cl::CommandQueue(gContext, devices[0], 0, &err);
        int src_length = 0;
		const char* src  = file_contents("/data/data/com.example/app_execdir/kernels.cl",&src_length);
        cl::Program::Sources sources(1,std::make_pair(src, src_length) );
        cl::Program program(gContext, sources);
        program.build(devices,NULL,cb);
        while(program.getBuildInfo<CL_PROGRAM_BUILD_STATUS>(devices[0]) != CL_BUILD_SUCCESS);
        gNV21Kernel = cl::Kernel(program, "nv21torgba", &err);
        gLaplacianK = cl::Kernel(program, "laplacian", &err);
        gNegative = cl::Kernel(program, "negative", &err);
        return true;
    }
    catch (cl::Error e) {
        if( !throwJavaException(env,"decode",e.what(),e.err()) )
            LOGI("@decode: %s \n",e.what());
        return false;
    }
}
Пример #4
0
static char *
desktop_from_dir(const char *directory,
                    char **error_message)
{
    char *environ_contents = file_contents(directory, "environ", error_message);
    if (!environ_contents)
        return NULL;

    char *desktop = strstr(environ_contents, "DESKTOP_SESSION=");
    if (!desktop)
    {
        free(environ_contents);
        return NULL;
    }

    /* avoid prefixes - DESKTOP_SESSION= must either be
       the very first variable or preceeded by a newline */
    if (desktop != environ_contents && *(desktop - 1) != '\n')
    {
        free(environ_contents);
        return NULL;
    }

    desktop += strlen("DESKTOP_SESSION=");
    char *newline = strchrnul(desktop, '\n');
    *newline = '\0';

    char *result = sr_strdup(desktop);
    free(environ_contents);

    return result;
}
Пример #5
0
int main(int argc, char **argv){
	bt_zero("~~~Userspace test program start!~~~\n");
	print_string("TEST Command Prompt!\n");
	while(true){
		char input[128]={0};
		print_string("[TEST]>");
		get_string(input, 128);
		if(input[0]=='d') dir_listing();
		else if(input[0]=='b') ata_test();
		else if(input[0]=='l') dir_listing2(input);
		else if(input[0]=='f') file_contents();
		else if(input[0]=='c') file_contents2(input);
		else if(input[0]=='m') mount_test();
		else if(input[0]=='v') version();
		else if(input[0]=='r') run_program(input);
		else if(input[0]=='p') path(input);
		else if(input[0]=='t') thread_test();
        else if(input[0]=='x') crash_test();
		else if(input[0]=='q') break;
		else {
			if(strlen(input) && input[0]!='\n') print_string("Unrecognised command.\n");
		}
	}
	bt_zero("~~~Userspace test program done!~~~\n");
	bt_exit(0);
    return 0;
}
Пример #6
0
static GLuint make_shader(GLenum type, const std::string& filename)/*{{{*/
{
    /* Utility function to create a shader object from a file*/
    GLint length;
    GLchar *source = (GLchar*)file_contents(filename.c_str(), &length);
    GLuint shader;
    GLint shader_ok;
    if (!source)
        return 0;
    //
    shader = glCreateShader(type);
    glShaderSource(shader, 1, (const GLchar**)&source, &length);
    free(source);
    glCompileShader(shader);
    //
    glGetShaderiv(shader, GL_COMPILE_STATUS, &shader_ok);
    if (!shader_ok) {
        std::cerr<<"Failed to compile "<<filename<<":"<<std::endl;
        show_info_log(shader, glGetShaderiv, glGetShaderInfoLog);
        glDeleteShader(shader);
        return 0;
    } else {
		// std::cout << filename << " compiled" << std::endl;
	}
    return shader;
}/*}}}*/
Пример #7
0
struct sr_operating_system *
sr_abrt_operating_system_from_dir(const char *directory,
                                  char **error_message)
{
    bool success = false;
    struct sr_operating_system *os = sr_operating_system_new();

    char *osinfo_contents = file_contents(directory, "os_info", error_message);
    if (osinfo_contents)
    {
        success = sr_operating_system_parse_etc_os_release(osinfo_contents, os);
        free(osinfo_contents);
    }

    /* fall back to os_release if parsing os_info fails */
    if (!success)
    {
        char *release_contents = file_contents(directory, "os_release",
                                               error_message);
        if (release_contents)
        {
            success = sr_operating_system_parse_etc_system_release(release_contents,
                                                                   &os->name,
                                                                   &os->version);
            free(release_contents);
        }
    }

    if (!success)
    {
        sr_operating_system_free(os);
        *error_message = sr_strdup("Failed to parse operating system release string");
        return NULL;
    }

    os->architecture = file_contents(directory, "architecture", error_message);
    if (!os->architecture)
    {
        sr_operating_system_free(os);
        return NULL;
    }

    /* optional - failure is not fatal */
    os->desktop = desktop_from_dir(directory, error_message);

    return os;
}
Пример #8
0
struct sr_rpm_package *
sr_abrt_rpm_packages_from_dir(const char *directory,
                              char **error_message)
{

    char *epoch_str = file_contents(directory, "pkg_epoch", error_message);
    if (!epoch_str)
    {
        return NULL;
    }
    unsigned long epoch = strtoul(epoch_str, NULL, 10);
    if (epoch == ULONG_MAX)
    {
        *error_message = sr_asprintf("Epoch '%s' is not a number", epoch_str);
        return NULL;
    }
    free(epoch_str);

    struct sr_rpm_package *packages = sr_rpm_package_new();

    packages->epoch = (uint32_t)epoch;
    packages->name = file_contents(directory, "pkg_name", error_message);
    packages->version = file_contents(directory, "pkg_version", error_message);
    packages->release = file_contents(directory, "pkg_release", error_message);
    packages->architecture = file_contents(directory, "pkg_arch", error_message);
    packages->role = SR_ROLE_AFFECTED;

    if (!(packages->name && packages->version && packages->release &&
          packages->architecture))
    {
        sr_rpm_package_free(packages, false);
        return NULL;
    }

    /* Workaround abrt-action-save-kernel-data appending trailing \n for
     * koopses. */
    strip_newline(packages->name);
    strip_newline(packages->version);
    strip_newline(packages->release);
    strip_newline(packages->architecture);

    char *dso_list_contents = file_contents(directory, "dso_list",
                                            error_message);
    if (dso_list_contents)
    {
        struct sr_rpm_package *dso_packages =
            sr_abrt_parse_dso_list(dso_list_contents);

        if (dso_packages)
        {
            packages = sr_rpm_package_append(packages, dso_packages);
            packages = sr_rpm_package_sort(packages);
            packages = sr_rpm_package_uniq(packages);
        }

        free(dso_list_contents);
    }

    return packages;
}
Пример #9
0
static bool
create_core_stacktrace(const char *directory, const char *gdb_output,
                       bool hash_fingerprints, char **error_message)
{
    char *executable_contents = file_contents(directory, "executable",
                                              error_message);
    if (!executable_contents)
        return NULL;

    char *coredump_filename = sr_build_path(directory, "coredump", NULL);

    struct sr_core_stacktrace *core_stacktrace;

    if (gdb_output)
        core_stacktrace = sr_core_stacktrace_from_gdb(gdb_output,
                coredump_filename, executable_contents, error_message);
    else
        core_stacktrace = sr_parse_coredump(coredump_filename,
                executable_contents, error_message);

    free(executable_contents);
    free(coredump_filename);
    if (!core_stacktrace)
        return false;

    fulfill_missing_values(core_stacktrace);

#if 0
    sr_core_fingerprint_generate(core_stacktrace,
                                 error_message);

    if (hash_fingerprints)
        sr_core_fingerprint_hash(core_stacktrace);
#endif

    char *json = sr_core_stacktrace_to_json(core_stacktrace);

    // Add newline to the end of core stacktrace file to make text
    // editors happy.
    json = sr_realloc(json, strlen(json) + 2);
    strcat(json, "\n");

    char *core_backtrace_filename = sr_build_path(directory, "core_backtrace", NULL);
    bool success = sr_string_to_file(core_backtrace_filename,
                                    json,
                                    error_message);

    free(core_backtrace_filename);
    free(json);
    sr_core_stacktrace_free(core_stacktrace);
    return success;
}
Пример #10
0
 void Shader::set_source_from_file(const char * filename)
 {
     std::ifstream ifs;
     ifs.open(filename);
     if (!ifs.is_open())
     {
         throw Error(std::string("Error opening ") + filename);
     }
     ifs.seekg(0, ifs.end);
     int length = ifs.tellg();
     ifs.seekg(0, ifs.beg);
     std::vector<char> file_contents(length);
     ifs.read(&file_contents[0], length);
     set_source(&file_contents[0], length);
 }
Пример #11
0
int main(){
    std::string file_contents("adsf");
    x3_ast::declaration result;
    boost::spirit::x3::ascii::space_type space;

    auto it = file_contents.begin();
    auto end = file_contents.end();

    bool r = x3::phrase_parse(it, end, x3_grammar::parser, space, result);

    if(r && it == end){
        return true;
    } else {

        return false;
    }
}
Пример #12
0
  GLuint CreateShader(GLenum type, const char *filename)
{   GLint length;
    GLchar *source = (GLchar*) file_contents(filename, &length);
    GLuint shader;
    GLint shader_ok;
  
    if (!source){
      return 0;
    }
  
    shader = glCreateShader(type);
    glShaderSource(shader, 1, (const GLchar**)&source, &length);
    delete source;

    glCompileShader(shader);

	GLint status;
	glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
	if (status == GL_FALSE)
	{
		GLint infoLogLength;
		glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);

		GLchar *strInfoLog = new GLchar[infoLogLength + 1];
		glGetShaderInfoLog(shader, infoLogLength, NULL, strInfoLog);

		const char *strShaderType = NULL;
		switch(type)
		{
		case GL_VERTEX_SHADER: strShaderType = "vertex"; break;
		case GL_GEOMETRY_SHADER: strShaderType = "geometry"; break;
		case GL_FRAGMENT_SHADER: strShaderType = "fragment"; break;
		}

		printf("Compile failure in %s shader:\n%s\n", strShaderType, strInfoLog);
		delete[] strInfoLog;
	}

	return shader;
}
Пример #13
0
cl_program build_opencl_kernel(build_kernel_data *data, const char *filename)
{
  int pl;
  char *source = file_contents(data->source_filename, &pl);
  size_t sourceSize[] = {(size_t)pl};
  cl_int status;
  cl_program program = NULL;
  cl_program ret = NULL;

  if (!source)
    goto out;

  program = clCreateProgramWithSource(data->context, 1, (const char **)&source, sourceSize, &status);
  if (status != CL_SUCCESS) {
    applog(LOG_ERR, "Error %d: Loading Binary into cl_program (clCreateProgramWithSource)", status);
    goto out;
  }

  applog(LOG_DEBUG, "CompilerOptions: %s", data->compiler_options);
  status = clBuildProgram(program, 1, data->device, data->compiler_options, NULL, NULL);

  if (status != CL_SUCCESS) {
    size_t log_size;
    applog(LOG_ERR, "Error %d: Building Program (clBuildProgram)", status);
    status = clGetProgramBuildInfo(program, *data->device, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size);

    char *sz_log = (char *)malloc(log_size + 1);
    status = clGetProgramBuildInfo(program, *data->device, CL_PROGRAM_BUILD_LOG, log_size, sz_log, NULL);
    sz_log[log_size] = '\0';
    applogsiz(LOG_ERR, log_size, "%s", sz_log);
    free(sz_log);
    goto out;
  }

  ret = program;
out:
  if (source) free(source);
  return ret;
}
Пример #14
0
static GLuint createShader(GLenum eShaderType  , const char *filename)
{
  GLint length;
  GLuint shader;
  GLint status;
  GLchar *source = file_contents(filename, &length);
  
  if (!source)
    return 0;
  
  shader = glCreateShader(eShaderType);
  
  glShaderSource(shader, 1, (const GLchar**)&source, &length);
  glCompileShader(shader);
  
  glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
  if (status == GL_FALSE) {
    GLint infoLogLength;
    glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
    
    GLchar *strInfoLog = malloc(infoLogLength);
    glGetShaderInfoLog(shader, infoLogLength, NULL, strInfoLog);
    
    const char *strShaderType = NULL;
    switch(eShaderType) {
      case GL_VERTEX_SHADER: strShaderType = "vertex"; break;
#ifdef GL_GEOMETRY_SHADER
      case GL_GEOMETRY_SHADER: strShaderType = "geometry"; break;
#endif
      case GL_FRAGMENT_SHADER: strShaderType = "fragment"; break;
    }
    fprintf(stderr, "Compile failure in %s shader:\n%s\n", strShaderType, strInfoLog);
    free(strInfoLog);
  }
  
  return shader;
}
Пример #15
0
GLuint make_shader(GLenum type, const char *filename)
{
	GLint length;
	GLchar *source = (GLchar *)file_contents(filename, &length);
	GLuint shader;
	GLint shader_ok;

	if (!source)
		return 0;

	shader = glCreateShader(type);
	glShaderSource(shader, 1, (const GLchar**)&source, &length);
	free(source);
	glCompileShader(shader);

	glGetShaderiv(shader, GL_COMPILE_STATUS, &shader_ok);
	if (!shader_ok) {
		fprintf(stderr, "Failed to compile %s:\n", filename);
		show_info_log(shader, glGetShaderiv, glGetShaderInfoLog);
		glDeleteShader(shader);
		return 0;
	}
	return shader;
}
Пример #16
0
void http_cache::get (const std::string& url, int timeout_msec,
                      std::function<void(std::string)> callback) const
{
    auto file (cache_file(url));
    if (fs::exists(file))
    {
        callback(file_contents(url));
        return;
    }

    boost::thread bg ([=]{
        http::client::request rq (url);
        rq << header("Connection", "close");
        http::client temp_client;
        std::string data (http::body(temp_client.get(rq)));

        std::ofstream out (file.string(), std::ios::binary);
        out.write(&data[0], data.size());
        out.close();

        callback(std::move(data));
    });
    bg.detach();
}
Пример #17
0
struct sr_report *
sr_abrt_report_from_dir(const char *directory,
                        char **error_message)
{
    struct sr_report *report = sr_report_new();

    /* Report type. */
    char *type_contents = file_contents(directory, "type", error_message);
    if (!type_contents)
    {
        sr_report_free(report);
        return NULL;
    }

    report->report_type = sr_abrt_type_from_type(type_contents);
    free(type_contents);

    /* Operating system. */
    report->operating_system = sr_abrt_operating_system_from_dir(
        directory, error_message);

    if (!report->operating_system)
    {
        sr_report_free(report);
        return NULL;
    }

    /* Component name. */
    report->component_name = file_contents(directory, "component", error_message);

    /* RPM packages. */
    report->rpm_packages = sr_abrt_rpm_packages_from_dir(
        directory, error_message);

    if (!report->rpm_packages)
    {
        sr_report_free(report);
        return NULL;
    }

    /* Core stacktrace. */
    if (report->report_type == SR_REPORT_CORE)
    {
        char *core_backtrace_contents = file_contents(directory, "core_backtrace",
                                                      error_message);
        if (!core_backtrace_contents)
        {
            sr_report_free(report);
            return NULL;
        }

        report->stacktrace = (struct sr_stacktrace *)sr_core_stacktrace_from_json_text(
                core_backtrace_contents, error_message);

        free(core_backtrace_contents);
        if (!report->stacktrace)
        {
            sr_report_free(report);
            return NULL;
        }
    }

    /* Python stacktrace. */
    if (report->report_type == SR_REPORT_PYTHON)
    {
        char *backtrace_contents = file_contents(directory, "backtrace",
                                                 error_message);
        if (!backtrace_contents)
        {
            sr_report_free(report);
            return NULL;
        }

        /* Parse the Python stacktrace. */
        struct sr_location location;
        sr_location_init(&location);
        const char *contents_pointer = backtrace_contents;
        report->stacktrace = (struct sr_stacktrace *)sr_python_stacktrace_parse(
            &contents_pointer,
            &location);

        free(backtrace_contents);
        if (!report->stacktrace)
        {
            *error_message = sr_location_to_string(&location);
            sr_report_free(report);
            return NULL;
        }
    }

    /* Kerneloops stacktrace. */
    if (report->report_type == SR_REPORT_KERNELOOPS)
    {
        /* Determine kernel version */
        char *kernel_contents = file_contents(directory, "kernel",
                                              error_message);
        if (!kernel_contents)
        {
            sr_report_free(report);
            return NULL;
        }

        /* Load the Kerneloops stacktrace */
        char *backtrace_contents = file_contents(directory, "backtrace", error_message);
        if (!backtrace_contents)
        {
            sr_report_free(report);
            return NULL;
        }

        /* Parse the Kerneloops stacktrace. */
        struct sr_location location;
        sr_location_init(&location);
        const char *contents_pointer = backtrace_contents;
        struct sr_koops_stacktrace *stacktrace = sr_koops_stacktrace_parse(
            &contents_pointer,
            &location);

        stacktrace->version = kernel_contents;
        report->stacktrace = (struct sr_stacktrace *)stacktrace;

        free(backtrace_contents);
        if (!report->stacktrace)
        {
            *error_message = sr_location_to_string(&location);
            sr_report_free(report);
            return NULL;
        }
    }

    /* Java stacktrace. */
    if (report->report_type == SR_REPORT_JAVA)
    {
        char *backtrace_contents = file_contents(directory, "backtrace", error_message);
        if (!backtrace_contents)
        {
            sr_report_free(report);
            return NULL;
        }

        /* Parse the Java stacktrace. */
        struct sr_location location;
        sr_location_init(&location);
        const char *contents_pointer = backtrace_contents;
        report->stacktrace = (struct sr_stacktrace *)sr_java_stacktrace_parse(
            &contents_pointer,
            &location);

        free(backtrace_contents);
        if (!report->stacktrace)
        {
            *error_message = sr_location_to_string(&location);
            sr_report_free(report);
            return NULL;
        }
    }

    /* Ruby stacktrace. */
    if (report->report_type == SR_REPORT_RUBY)
    {
        char *backtrace_contents = file_contents(directory, "backtrace",
                                                 error_message);
        if (!backtrace_contents)
        {
            sr_report_free(report);
            return NULL;
        }

        /* Parse the Ruby stacktrace. */
        struct sr_location location;
        sr_location_init(&location);
        const char *contents_pointer = backtrace_contents;
        report->stacktrace = (struct sr_stacktrace *)sr_ruby_stacktrace_parse(
            &contents_pointer,
            &location);

        free(backtrace_contents);
        if (!report->stacktrace)
        {
            *error_message = sr_location_to_string(&location);
            sr_report_free(report);
            return NULL;
        }
    }

    return report;
}
Пример #18
0
    //----------------------------------------------------------------------
    GLuint Render::compileShaders(const char* vertex_file, const char* fragment_file, const char* geometry_file, GLenum* geom_param, GLint* geom_value, int geom_param_len)
    {

        //this may not be the cleanest implementation
        //#include "shaders.cpp"

        printf("vertex_file: %s\n", vertex_file);
        printf("fragment_file: %s\n", fragment_file);
        //printf("vertex shader:\n%s\n", vertex_shader_source);
        //printf("fragment shader:\n%s\n", fragment_shader_source);
        char *vertex_shader_source = NULL,*fragment_shader_source= NULL,*geometry_shader_source=NULL;
        int vert_size,frag_size,geom_size;
        if (vertex_file)
        {
            vertex_shader_source = file_contents(vertex_file,&vert_size);
            if (!vertex_shader_source)
            {
                printf("Vertex shader file not found or is empty! Cannot compile shader");
                return -1;
            }
        }
        else
        {
            printf("No vertex file specified! Cannot compile shader!");
            return -1;
        }

        if (fragment_file)
        {
            fragment_shader_source = file_contents(fragment_file,&frag_size);
            if (!fragment_shader_source)
            {
                printf("Fragment shader file not found or is empty! Cannot compile shader");
                free(vertex_shader_source);
                return -1;
            }
        }
        else
        {
            printf("No fragment file specified! Cannot compile shader!");
            free(vertex_shader_source);
            return -1;
        }

        if (geometry_file)
        {
            geometry_shader_source = file_contents(fragment_file,&frag_size);
            if (!geometry_shader_source)
            {
                printf("Geometry shader file not found or is empty! Cannot compile shader");
                free(vertex_shader_source);
                free(fragment_shader_source);
                return -1;
            }
        }

        GLint len;
        GLuint program = glCreateProgram();

        GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vertex_shader, 1, (const GLchar**)&vertex_shader_source, 0);
        glCompileShader(vertex_shader);
        glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &len);
        if (len > 0)
        {
            char log[1024];
            glGetShaderInfoLog(vertex_shader, 1024, 0, log);
            printf("Vertex Shader log:\n %s\n", log);
        }
        glAttachShader(program, vertex_shader);

        GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
        glShaderSource(fragment_shader, 1, (const GLchar**)&fragment_shader_source, 0);
        glCompileShader(fragment_shader);
        glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &len);
        if (len > 0)
        {
            char log[1024];
            glGetShaderInfoLog(fragment_shader, 1024, 0, log);
            printf("Fragment Shader log:\n %s\n", log);
        }
        glAttachShader(program, fragment_shader);


        GLuint geometry_shader=0;
        if (geometry_shader_source)
        {
            geometry_shader = glCreateShader(GL_GEOMETRY_SHADER_EXT);
            glShaderSource(geometry_shader, 1, (const GLchar**)&geometry_shader_source, 0);
            glCompileShader(geometry_shader);
            glGetShaderiv(geometry_shader, GL_INFO_LOG_LENGTH, &len);
            printf("geometry len %d\n", len);
            if (len > 0)
            {
                char log[1024];
                glGetShaderInfoLog(geometry_shader, 1024, 0, log);
                printf("Geometry Shader log:\n %s\n", log);
            }
            glAttachShader(program, geometry_shader);
            for (int i = 0;i < geom_param_len; i++)
            {
                glProgramParameteriEXT(program,geom_param[i],geom_value[i]);
            }
        }

        glLinkProgram(program);

        // check if program linked
        GLint success = 0;
        glGetProgramiv(program, GL_LINK_STATUS, &success);

        if (!success)
        {
            char temp[256];
            glGetProgramInfoLog(program, 256, 0, temp);
            printf("Failed to link program:\n%s\n", temp);
            glDeleteProgram(program);
            program = 0;
        }

        //cleanup
        glDeleteShader(vertex_shader);
        glDeleteShader(fragment_shader);
        if (geometry_shader)
        {
            glDeleteShader(geometry_shader);
        }
        free(vertex_shader_source);
        free(fragment_shader_source);
        free(geometry_shader_source);

        return program;
    }
Пример #19
0
void
setup_opencl(const char* cl_source_filename, const char* cl_source_main, cl_device_id* device_id,
             cl_kernel* kernel, cl_context* context, cl_command_queue* queue)
{
        cl_int err;					// error code returned from api calls

        cl_platform_id platform_id;			// compute device id
        cl_program program;				// compute program
        cl_device_id devices[MAX_RESOURCES];
        cl_platform_id platforms[MAX_RESOURCES];


        unsigned int best_platform = 0;
        unsigned int best_device = 0;
        print_devices(0);

        if(!get_best_device(&best_platform, &best_device)) {
                printf("No suitable device was found! Try using an OpenCL1.1 compatible device.\n");
                exit(1);
        }
        printf("Initiating platform-%d device-%d.\n", best_platform, best_device);



        // Platform
        err = clGetPlatformIDs(MAX_RESOURCES, platforms, NULL);
	ocl_error("Getting platform id", err);

        platform_id = platforms[best_platform];

        // Device
        err = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_ALL, sizeof(devices), devices, NULL); //NULL, ignore number returned devices.
	ocl_error("Getting device ids", err);

        *device_id = devices[best_device];

        // Context
        *context = clCreateContext(0, 1, device_id, NULL, NULL, &err);
	ocl_error("Creating context", err);

        // Command-queue
        *queue = clCreateCommandQueue(*context, *device_id, 0, &err);
	ocl_error("Creating command queue", err);


        // Read .cl source into memory
        int cl_source_len = 0;
        char* cl_source = file_contents(cl_source_filename, &cl_source_len);


        // Create thes compute program from the source buffer
        program = clCreateProgramWithSource(*context, 1, (const char **) &cl_source, NULL, &err);
	ocl_error("Failed to create compute program", err);


        // Build the program executable
        err = clBuildProgram(program, 0, NULL, NULL, NULL, NULL);
        if (err != CL_SUCCESS) {
                char* build_log;
                size_t log_size;
                // First call to know the proper size
                clGetProgramBuildInfo(program, *device_id, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size);
                build_log = malloc(sizeof(char)*(log_size+1));
                if(log_size > 0 && build_log != NULL) {
	                // Second call to get the log
	                clGetProgramBuildInfo(program, *device_id, CL_PROGRAM_BUILD_LOG, log_size, build_log, NULL);
	                build_log[log_size] = '\0';
	                printf("%s\n", build_log);
	                free(build_log);
                }

                exit(err);
        }


        // Create the compute kernel in the program we wish to run
        *kernel = clCreateKernel(program, cl_source_main, &err);
	ocl_error("Failed to create compute kernel", err);
}
Пример #20
0
_clState *initCl(unsigned int gpu, char *name, size_t nameSize)
{
    _clState *clState = calloc(1, sizeof(_clState));
    bool patchbfi = false, prog_built = false;
    struct cgpu_info *cgpu = &gpus[gpu];
    cl_platform_id platform = NULL;
    char pbuff[256], vbuff[255];
    cl_platform_id* platforms;
    cl_uint preferred_vwidth;
    cl_device_id *devices;
    cl_uint numPlatforms;
    cl_uint numDevices;
    cl_int status;

    status = clGetPlatformIDs(0, NULL, &numPlatforms);
    if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: Getting Platforms. (clGetPlatformsIDs)", status);
        return NULL;
    }

    platforms = (cl_platform_id *)alloca(numPlatforms*sizeof(cl_platform_id));
    status = clGetPlatformIDs(numPlatforms, platforms, NULL);
    if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: Getting Platform Ids. (clGetPlatformsIDs)", status);
        return NULL;
    }

    if (opt_platform_id >= (int)numPlatforms) {
        applog(LOG_ERR, "Specified platform that does not exist");
        return NULL;
    }

    status = clGetPlatformInfo(platforms[opt_platform_id], CL_PLATFORM_VENDOR, sizeof(pbuff), pbuff, NULL);
    if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: Getting Platform Info. (clGetPlatformInfo)", status);
        return NULL;
    }
    platform = platforms[opt_platform_id];

    if (platform == NULL) {
        perror("NULL platform found!\n");
        return NULL;
    }

    applog(LOG_INFO, "CL Platform vendor: %s", pbuff);
    status = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(pbuff), pbuff, NULL);
    if (status == CL_SUCCESS)
        applog(LOG_INFO, "CL Platform name: %s", pbuff);
    status = clGetPlatformInfo(platform, CL_PLATFORM_VERSION, sizeof(vbuff), vbuff, NULL);
    if (status == CL_SUCCESS)
        applog(LOG_INFO, "CL Platform version: %s", vbuff);

    status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 0, NULL, &numDevices);
    if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: Getting Device IDs (num)", status);
        return NULL;
    }

    if (numDevices > 0 ) {
        devices = (cl_device_id *)malloc(numDevices*sizeof(cl_device_id));

        /* Now, get the device list data */

        status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, numDevices, devices, NULL);
        if (status != CL_SUCCESS) {
            applog(LOG_ERR, "Error %d: Getting Device IDs (list)", status);
            return NULL;
        }

        applog(LOG_INFO, "List of devices:");

        unsigned int i;
        for (i = 0; i < numDevices; i++) {
            status = clGetDeviceInfo(devices[i], CL_DEVICE_NAME, sizeof(pbuff), pbuff, NULL);
            if (status != CL_SUCCESS) {
                applog(LOG_ERR, "Error %d: Getting Device Info", status);
                return NULL;
            }

            applog(LOG_INFO, "\t%i\t%s", i, pbuff);
        }

        if (gpu < numDevices) {
            status = clGetDeviceInfo(devices[gpu], CL_DEVICE_NAME, sizeof(pbuff), pbuff, NULL);
            if (status != CL_SUCCESS) {
                applog(LOG_ERR, "Error %d: Getting Device Info", status);
                return NULL;
            }

            applog(LOG_INFO, "Selected %i: %s", gpu, pbuff);
            strncpy(name, pbuff, nameSize);
        } else {
            applog(LOG_ERR, "Invalid GPU %i", gpu);
            return NULL;
        }

    } else return NULL;

    cl_context_properties cps[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0 };

    clState->context = clCreateContextFromType(cps, CL_DEVICE_TYPE_GPU, NULL, NULL, &status);
    if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: Creating Context. (clCreateContextFromType)", status);
        return NULL;
    }

    /////////////////////////////////////////////////////////////////
    // Create an OpenCL command queue
    /////////////////////////////////////////////////////////////////
    clState->commandQueue = clCreateCommandQueue(clState->context, devices[gpu],
                            CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, &status);
    if (status != CL_SUCCESS) /* Try again without OOE enable */
        clState->commandQueue = clCreateCommandQueue(clState->context, devices[gpu], 0 , &status);
    if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: Creating Command Queue. (clCreateCommandQueue)", status);
        return NULL;
    }

    /* Check for BFI INT support. Hopefully people don't mix devices with
     * and without it! */
    char * extensions = malloc(1024);
    const char * camo = "cl_amd_media_ops";
    char *find;

    status = clGetDeviceInfo(devices[gpu], CL_DEVICE_EXTENSIONS, 1024, (void *)extensions, NULL);
    if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_EXTENSIONS", status);
        return NULL;
    }
    find = strstr(extensions, camo);
    if (find)
        clState->hasBitAlign = true;

    /* Check for OpenCL >= 1.0 support, needed for global offset parameter usage. */
    char * devoclver = malloc(1024);
    const char * ocl10 = "OpenCL 1.0";
    const char * ocl11 = "OpenCL 1.1";

    status = clGetDeviceInfo(devices[gpu], CL_DEVICE_VERSION, 1024, (void *)devoclver, NULL);
    if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_VERSION", status);
        return NULL;
    }
    find = strstr(devoclver, ocl10);
    if (!find) {
        clState->hasOpenCL11plus = true;
        find = strstr(devoclver, ocl11);
        if (!find)
            clState->hasOpenCL12plus = true;
    }

    status = clGetDeviceInfo(devices[gpu], CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT, sizeof(cl_uint), (void *)&preferred_vwidth, NULL);
    if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT", status);
        return NULL;
    }
    applog(LOG_DEBUG, "Preferred vector width reported %d", preferred_vwidth);

    status = clGetDeviceInfo(devices[gpu], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), (void *)&clState->max_work_size, NULL);
    if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_MAX_WORK_GROUP_SIZE", status);
        return NULL;
    }
    applog(LOG_DEBUG, "Max work group size reported %d", (int)(clState->max_work_size));

    size_t compute_units = 0;
    status = clGetDeviceInfo(devices[gpu], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(size_t), (void *)&compute_units, NULL);
    if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_MAX_COMPUTE_UNITS", status);
        return NULL;
    }
    // AMD architechture got 64 compute shaders per compute unit.
    // Source: http://www.amd.com/us/Documents/GCN_Architecture_whitepaper.pdf
    clState->compute_shaders = compute_units * 64;
    applog(LOG_DEBUG, "Max shaders calculated %d", (int)(clState->compute_shaders));

    status = clGetDeviceInfo(devices[gpu], CL_DEVICE_MAX_MEM_ALLOC_SIZE , sizeof(cl_ulong), (void *)&cgpu->max_alloc, NULL);
    if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_MAX_MEM_ALLOC_SIZE", status);
        return NULL;
    }
    applog(LOG_DEBUG, "Max mem alloc size is %lu", (long unsigned int)(cgpu->max_alloc));

    /* Create binary filename based on parameters passed to opencl
     * compiler to ensure we only load a binary that matches what would
     * have otherwise created. The filename is:
     * name + kernelname +/- g(offset) + v + vectors + w + work_size + l + sizeof(long) + .bin
     * For scrypt the filename is:
     * name + kernelname + g + lg + lookup_gap + tc + thread_concurrency + w + work_size + l + sizeof(long) + .bin
     */
    char binaryfilename[255];
    char filename[255];
    char numbuf[16];

    if (cgpu->kernel == KL_NONE) {
        applog(LOG_INFO, "Selecting kernel ckolivas");
        clState->chosen_kernel = KL_CKOLIVAS;
        cgpu->kernel = clState->chosen_kernel;
    } else {
        clState->chosen_kernel = cgpu->kernel;
    }

    /* For some reason 2 vectors is still better even if the card says
     * otherwise, and many cards lie about their max so use 256 as max
     * unless explicitly set on the command line. Tahiti prefers 1 */
    if (strstr(name, "Tahiti"))
        preferred_vwidth = 1;
    else if (preferred_vwidth > 2)
        preferred_vwidth = 2;

    /* All available kernels only support vector 1 */
    cgpu->vwidth = 1;

    switch (clState->chosen_kernel) {
    case KL_ALEXKARNEW:
        applog(LOG_WARNING, "Kernel alexkarnew is experimental.");
        strcpy(filename, ALEXKARNEW_KERNNAME".cl");
        strcpy(binaryfilename, ALEXKARNEW_KERNNAME);
        break;
    case KL_ALEXKAROLD:
        applog(LOG_WARNING, "Kernel alexkarold is experimental.");
        strcpy(filename, ALEXKAROLD_KERNNAME".cl");
        strcpy(binaryfilename, ALEXKAROLD_KERNNAME);
        break;
    case KL_CKOLIVAS:
        strcpy(filename, CKOLIVAS_KERNNAME".cl");
        strcpy(binaryfilename, CKOLIVAS_KERNNAME);
        break;
    case KL_ZUIKKIS:
        applog(LOG_WARNING, "Kernel zuikkis is experimental.");
        strcpy(filename, ZUIKKIS_KERNNAME".cl");
        strcpy(binaryfilename, ZUIKKIS_KERNNAME);
        /* Kernel only supports lookup-gap 2 */
        cgpu->lookup_gap = 2;
        /* Kernel only supports worksize 256 */
        cgpu->work_size = 256;
        break;
    case KL_NONE: /* Shouldn't happen */
        break;
    }

    if (cgpu->vwidth)
        clState->vwidth = cgpu->vwidth;
    else {
        clState->vwidth = preferred_vwidth;
        cgpu->vwidth = preferred_vwidth;
    }

    clState->goffset = true;

    if (cgpu->work_size && cgpu->work_size <= clState->max_work_size)
        clState->wsize = cgpu->work_size;
    else
        clState->wsize = 256;

    if (!cgpu->opt_lg) {
        applog(LOG_DEBUG, "GPU %d: selecting lookup gap of 2", gpu);
        cgpu->lookup_gap = 2;
    } else
        cgpu->lookup_gap = cgpu->opt_lg;

    if (!cgpu->opt_tc) {
        unsigned int sixtyfours;

        sixtyfours =  cgpu->max_alloc / 131072 / 64 - 1;
        cgpu->thread_concurrency = sixtyfours * 64;
        if (cgpu->shaders && cgpu->thread_concurrency > cgpu->shaders) {
            cgpu->thread_concurrency -= cgpu->thread_concurrency % cgpu->shaders;
            if (cgpu->thread_concurrency > cgpu->shaders * 5)
                cgpu->thread_concurrency = cgpu->shaders * 5;
        }
        applog(LOG_DEBUG, "GPU %d: selecting thread concurrency of %d", gpu, (int)(cgpu->thread_concurrency));
    } else
        cgpu->thread_concurrency = cgpu->opt_tc;


    FILE *binaryfile;
    size_t *binary_sizes;
    char **binaries;
    int pl;
    char *source = file_contents(filename, &pl);
    size_t sourceSize[] = {(size_t)pl};
    cl_uint slot, cpnd;

    slot = cpnd = 0;

    if (!source)
        return NULL;

    binary_sizes = calloc(sizeof(size_t) * MAX_GPUDEVICES * 4, 1);
    if (unlikely(!binary_sizes)) {
        applog(LOG_ERR, "Unable to calloc binary_sizes");
        return NULL;
    }
    binaries = calloc(sizeof(char *) * MAX_GPUDEVICES * 4, 1);
    if (unlikely(!binaries)) {
        applog(LOG_ERR, "Unable to calloc binaries");
        return NULL;
    }

    strcat(binaryfilename, name);
    if (clState->goffset)
        strcat(binaryfilename, "g");

    sprintf(numbuf, "lg%utc%u", cgpu->lookup_gap, (unsigned int)cgpu->thread_concurrency);
    strcat(binaryfilename, numbuf);

    sprintf(numbuf, "w%d", (int)clState->wsize);
    strcat(binaryfilename, numbuf);
    sprintf(numbuf, "l%d", (int)sizeof(long));
    strcat(binaryfilename, numbuf);
    strcat(binaryfilename, ".bin");

    binaryfile = fopen(binaryfilename, "rb");
    if (!binaryfile) {
        applog(LOG_DEBUG, "No binary found, generating from source");
    } else {
        struct stat binary_stat;

        if (unlikely(stat(binaryfilename, &binary_stat))) {
            applog(LOG_DEBUG, "Unable to stat binary, generating from source");
            fclose(binaryfile);
            goto build;
        }
        if (!binary_stat.st_size)
            goto build;

        binary_sizes[slot] = binary_stat.st_size;
        binaries[slot] = (char *)calloc(binary_sizes[slot], 1);
        if (unlikely(!binaries[slot])) {
            applog(LOG_ERR, "Unable to calloc binaries");
            fclose(binaryfile);
            return NULL;
        }

        if (fread(binaries[slot], 1, binary_sizes[slot], binaryfile) != binary_sizes[slot]) {
            applog(LOG_ERR, "Unable to fread binaries");
            fclose(binaryfile);
            free(binaries[slot]);
            goto build;
        }

        clState->program = clCreateProgramWithBinary(clState->context, 1, &devices[gpu], &binary_sizes[slot], (const unsigned char **)binaries, &status, NULL);
        if (status != CL_SUCCESS) {
            applog(LOG_ERR, "Error %d: Loading Binary into cl_program (clCreateProgramWithBinary)", status);
            fclose(binaryfile);
            free(binaries[slot]);
            goto build;
        }

        fclose(binaryfile);
        applog(LOG_DEBUG, "Loaded binary image %s", binaryfilename);

        goto built;
    }

    /////////////////////////////////////////////////////////////////
    // Load CL file, build CL program object, create CL kernel object
    /////////////////////////////////////////////////////////////////

build:
    clState->program = clCreateProgramWithSource(clState->context, 1, (const char **)&source, sourceSize, &status);
    if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: Loading Binary into cl_program (clCreateProgramWithSource)", status);
        return NULL;
    }

    /* create a cl program executable for all the devices specified */
    char *CompilerOptions = calloc(1, 256);

    sprintf(CompilerOptions, "-D LOOKUP_GAP=%d -D CONCURRENT_THREADS=%d -D WORKSIZE=%d",
            cgpu->lookup_gap, (unsigned int)cgpu->thread_concurrency, (int)clState->wsize);

    applog(LOG_DEBUG, "Setting worksize to %d", (int)(clState->wsize));
    if (clState->vwidth > 1)
        applog(LOG_DEBUG, "Patched source to suit %d vectors", clState->vwidth);

    if (clState->hasBitAlign) {
        strcat(CompilerOptions, " -D BITALIGN");
        applog(LOG_DEBUG, "cl_amd_media_ops found, setting BITALIGN");
        if (!clState->hasOpenCL12plus &&
                (strstr(name, "Cedar") ||
                 strstr(name, "Redwood") ||
                 strstr(name, "Juniper") ||
                 strstr(name, "Cypress" ) ||
                 strstr(name, "Hemlock" ) ||
                 strstr(name, "Caicos" ) ||
                 strstr(name, "Turks" ) ||
                 strstr(name, "Barts" ) ||
                 strstr(name, "Cayman" ) ||
                 strstr(name, "Antilles" ) ||
                 strstr(name, "Wrestler" ) ||
                 strstr(name, "Zacate" ) ||
                 strstr(name, "WinterPark" )))
            patchbfi = true;
    } else
        applog(LOG_DEBUG, "cl_amd_media_ops not found, will not set BITALIGN");

    if (patchbfi) {
        strcat(CompilerOptions, " -D BFI_INT");
        applog(LOG_DEBUG, "BFI_INT patch requiring device found, patched source with BFI_INT");
    } else
        applog(LOG_DEBUG, "BFI_INT patch requiring device not found, will not BFI_INT patch");

    if (clState->goffset)
        strcat(CompilerOptions, " -D GOFFSET");

    if (!clState->hasOpenCL11plus)
        strcat(CompilerOptions, " -D OCL1");

    applog(LOG_DEBUG, "CompilerOptions: %s", CompilerOptions);
    status = clBuildProgram(clState->program, 1, &devices[gpu], CompilerOptions , NULL, NULL);
    free(CompilerOptions);

    if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: Building Program (clBuildProgram)", status);
        size_t logSize;
        status = clGetProgramBuildInfo(clState->program, devices[gpu], CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize);

        char *log = malloc(logSize);
        status = clGetProgramBuildInfo(clState->program, devices[gpu], CL_PROGRAM_BUILD_LOG, logSize, log, NULL);
        applog(LOG_ERR, "%s", log);
        return NULL;
    }

    prog_built = true;

#ifdef __APPLE__
    /* OSX OpenCL breaks reading off binaries with >1 GPU so always build
     * from source. */
    goto built;
#endif

    status = clGetProgramInfo(clState->program, CL_PROGRAM_NUM_DEVICES, sizeof(cl_uint), &cpnd, NULL);
    if (unlikely(status != CL_SUCCESS)) {
        applog(LOG_ERR, "Error %d: Getting program info CL_PROGRAM_NUM_DEVICES. (clGetProgramInfo)", status);
        return NULL;
    }

    status = clGetProgramInfo(clState->program, CL_PROGRAM_BINARY_SIZES, sizeof(size_t)*cpnd, binary_sizes, NULL);
    if (unlikely(status != CL_SUCCESS)) {
        applog(LOG_ERR, "Error %d: Getting program info CL_PROGRAM_BINARY_SIZES. (clGetProgramInfo)", status);
        return NULL;
    }

    /* The actual compiled binary ends up in a RANDOM slot! Grr, so we have
     * to iterate over all the binary slots and find where the real program
     * is. What the heck is this!? */
    for (slot = 0; slot < cpnd; slot++)
        if (binary_sizes[slot])
            break;

    /* copy over all of the generated binaries. */
    applog(LOG_DEBUG, "Binary size for gpu %d found in binary slot %d: %d", gpu, slot, (int)(binary_sizes[slot]));
    if (!binary_sizes[slot]) {
        applog(LOG_ERR, "OpenCL compiler generated a zero sized binary, FAIL!");
        return NULL;
    }
    binaries[slot] = calloc(sizeof(char) * binary_sizes[slot], 1);
    status = clGetProgramInfo(clState->program, CL_PROGRAM_BINARIES, sizeof(char *) * cpnd, binaries, NULL );
    if (unlikely(status != CL_SUCCESS)) {
        applog(LOG_ERR, "Error %d: Getting program info. CL_PROGRAM_BINARIES (clGetProgramInfo)", status);
        return NULL;
    }

    /* Patch the kernel if the hardware supports BFI_INT but it needs to
     * be hacked in */
    if (patchbfi) {
        unsigned remaining = binary_sizes[slot];
        char *w = binaries[slot];
        unsigned int start, length;

        /* Find 2nd incidence of .text, and copy the program's
        * position and length at a fixed offset from that. Then go
        * back and find the 2nd incidence of \x7ELF (rewind by one
        * from ELF) and then patch the opcocdes */
        if (!advance(&w, &remaining, ".text"))
            goto build;
        w++;
        remaining--;
        if (!advance(&w, &remaining, ".text")) {
            /* 32 bit builds only one ELF */
            w--;
            remaining++;
        }
        memcpy(&start, w + 285, 4);
        memcpy(&length, w + 289, 4);
        w = binaries[slot];
        remaining = binary_sizes[slot];
        if (!advance(&w, &remaining, "ELF"))
            goto build;
        w++;
        remaining--;
        if (!advance(&w, &remaining, "ELF")) {
            /* 32 bit builds only one ELF */
            w--;
            remaining++;
        }
        w--;
        remaining++;
        w += start;
        remaining -= start;
        applog(LOG_DEBUG, "At %p (%u rem. bytes), to begin patching",
               w, remaining);
        patch_opcodes(w, length);

        status = clReleaseProgram(clState->program);
        if (status != CL_SUCCESS) {
            applog(LOG_ERR, "Error %d: Releasing program. (clReleaseProgram)", status);
            return NULL;
        }

        clState->program = clCreateProgramWithBinary(clState->context, 1, &devices[gpu], &binary_sizes[slot], (const unsigned char **)&binaries[slot], &status, NULL);
        if (status != CL_SUCCESS) {
            applog(LOG_ERR, "Error %d: Loading Binary into cl_program (clCreateProgramWithBinary)", status);
            return NULL;
        }

        /* Program needs to be rebuilt */
        prog_built = false;
    }

    free(source);

    /* Save the binary to be loaded next time */
    binaryfile = fopen(binaryfilename, "wb");
    if (!binaryfile) {
        /* Not a fatal problem, just means we build it again next time */
        applog(LOG_DEBUG, "Unable to create file %s", binaryfilename);
    } else {
        if (unlikely(fwrite(binaries[slot], 1, binary_sizes[slot], binaryfile) != binary_sizes[slot])) {
            applog(LOG_ERR, "Unable to fwrite to binaryfile");
            return NULL;
        }
        fclose(binaryfile);
    }
built:
    if (binaries[slot])
        free(binaries[slot]);
    free(binaries);
    free(binary_sizes);

    applog(LOG_INFO, "Initialising kernel %s with%s bitalign, %d vectors and worksize %d",
           filename, clState->hasBitAlign ? "" : "out", clState->vwidth, (int)(clState->wsize));

    if (!prog_built) {
        /* create a cl program executable for all the devices specified */
        status = clBuildProgram(clState->program, 1, &devices[gpu], NULL, NULL, NULL);
        if (status != CL_SUCCESS) {
            applog(LOG_ERR, "Error %d: Building Program (clBuildProgram)", status);
            size_t logSize;
            status = clGetProgramBuildInfo(clState->program, devices[gpu], CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize);

            char *log = malloc(logSize);
            status = clGetProgramBuildInfo(clState->program, devices[gpu], CL_PROGRAM_BUILD_LOG, logSize, log, NULL);
            applog(LOG_ERR, "%s", log);
            return NULL;
        }
    }

    /* get a kernel object handle for a kernel with the given name */
    clState->kernel = clCreateKernel(clState->program, "search", &status);
    if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: Creating Kernel from program. (clCreateKernel)", status);
        return NULL;
    }

    size_t ipt = (1024 / cgpu->lookup_gap + (1024 % cgpu->lookup_gap > 0));
    size_t bufsize = 128 * ipt * cgpu->thread_concurrency;

    /* Use the max alloc value which has been rounded to a power of
     * 2 greater >= required amount earlier */
    if (bufsize > cgpu->max_alloc) {
        applog(LOG_WARNING, "Maximum buffer memory device %d supports says %lu",
               gpu, (long unsigned int)(cgpu->max_alloc));
        applog(LOG_WARNING, "Your scrypt settings come to %d", (int)bufsize);
    }
    applog(LOG_DEBUG, "Creating scrypt buffer sized %d", (int)bufsize);
    clState->padbufsize = bufsize;

    /* This buffer is weird and might work to some degree even if
     * the create buffer call has apparently failed, so check if we
     * get anything back before we call it a failure. */
    clState->padbuffer8 = NULL;
    clState->padbuffer8 = clCreateBuffer(clState->context, CL_MEM_READ_WRITE, bufsize, NULL, &status);
    if (status != CL_SUCCESS && !clState->padbuffer8) {
        applog(LOG_ERR, "Error %d: clCreateBuffer (padbuffer8), decrease TC or increase LG", status);
        return NULL;
    }

    clState->CLbuffer0 = clCreateBuffer(clState->context, CL_MEM_READ_ONLY, 128, NULL, &status);
    if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: clCreateBuffer (CLbuffer0)", status);
        return NULL;
    }
    clState->outputBuffer = clCreateBuffer(clState->context, CL_MEM_WRITE_ONLY, BUFFERSIZE, NULL, &status);

    if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: clCreateBuffer (outputBuffer)", status);
        return NULL;
    }

    return clState;
}
Пример #21
0
_clState *initCl(unsigned int gpu, char *name, size_t nameSize)
{
	_clState *clState = calloc(1, sizeof(_clState));
	bool patchbfi = false, prog_built = false;
	cl_platform_id platform = NULL;
	cl_platform_id* platforms;
	cl_device_id *devices;
	cl_uint numPlatforms;
	cl_uint numDevices;
	char pbuff[256];
	cl_int status;

	status = clGetPlatformIDs(0, NULL, &numPlatforms);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error: Getting Platforms. (clGetPlatformsIDs)");
		return NULL;
	}

	platforms = (cl_platform_id *)alloca(numPlatforms*sizeof(cl_platform_id));
	status = clGetPlatformIDs(numPlatforms, platforms, NULL);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error: Getting Platform Ids. (clGetPlatformsIDs)");
		return NULL;
	}

	if (opt_platform_id >= numPlatforms) {
		applog(LOG_ERR, "Specified platform that does not exist");
		return NULL;
	}

	status = clGetPlatformInfo(platforms[opt_platform_id], CL_PLATFORM_VENDOR, sizeof(pbuff), pbuff, NULL);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error: Getting Platform Info. (clGetPlatformInfo)");
		return NULL;
	}
	platform = platforms[opt_platform_id];

	if (platform == NULL) {
		perror("NULL platform found!\n");
		return NULL;
	}

	applog(LOG_INFO, "CL Platform vendor: %s", pbuff);
	status = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(pbuff), pbuff, NULL);
	if (status == CL_SUCCESS)
		applog(LOG_INFO, "CL Platform name: %s", pbuff);
	status = clGetPlatformInfo(platform, CL_PLATFORM_VERSION, sizeof(pbuff), pbuff, NULL);
	if (status == CL_SUCCESS)
		applog(LOG_INFO, "CL Platform version: %s", pbuff);

	status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 0, NULL, &numDevices);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error: Getting Device IDs (num)");
		return NULL;
	}

	if (numDevices > 0 ) {
		devices = (cl_device_id *)malloc(numDevices*sizeof(cl_device_id));

		/* Now, get the device list data */

		status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, numDevices, devices, NULL);
		if (status != CL_SUCCESS) {
			applog(LOG_ERR, "Error: Getting Device IDs (list)");
			return NULL;
		}

		applog(LOG_INFO, "List of devices:");

		unsigned int i;
		for (i = 0; i < numDevices; i++) {
			status = clGetDeviceInfo(devices[i], CL_DEVICE_NAME, sizeof(pbuff), pbuff, NULL);
			if (status != CL_SUCCESS) {
				applog(LOG_ERR, "Error: Getting Device Info");
				return NULL;
			}

			applog(LOG_INFO, "\t%i\t%s", i, pbuff);
		}

		if (gpu < numDevices) {
			status = clGetDeviceInfo(devices[gpu], CL_DEVICE_NAME, sizeof(pbuff), pbuff, NULL);
			if (status != CL_SUCCESS) {
				applog(LOG_ERR, "Error: Getting Device Info");
				return NULL;
			}

			applog(LOG_INFO, "Selected %i: %s", gpu, pbuff);
			strncpy(name, pbuff, nameSize);
		} else {
			applog(LOG_ERR, "Invalid GPU %i", gpu);
			return NULL;
		}

	} else return NULL;

	cl_context_properties cps[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0 };

	clState->context = clCreateContextFromType(cps, CL_DEVICE_TYPE_GPU, NULL, NULL, &status);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error: Creating Context. (clCreateContextFromType)");
		return NULL;
	}

	/* Check for BFI INT support. Hopefully people don't mix devices with
	 * and without it! */
	char * extensions = malloc(1024);
	const char * camo = "cl_amd_media_ops";
	char *find;

	status = clGetDeviceInfo(devices[gpu], CL_DEVICE_EXTENSIONS, 1024, (void *)extensions, NULL);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error: Failed to clGetDeviceInfo when trying to get CL_DEVICE_EXTENSIONS");
		return NULL;
	}
	find = strstr(extensions, camo);
	if (find)
		clState->hasBitAlign = true;

	status = clGetDeviceInfo(devices[gpu], CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT, sizeof(cl_uint), (void *)&clState->preferred_vwidth, NULL);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error: Failed to clGetDeviceInfo when trying to get CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT");
		return NULL;
	}
	if (opt_debug)
		applog(LOG_DEBUG, "Preferred vector width reported %d", clState->preferred_vwidth);

	status = clGetDeviceInfo(devices[gpu], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), (void *)&clState->max_work_size, NULL);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error: Failed to clGetDeviceInfo when trying to get CL_DEVICE_MAX_WORK_GROUP_SIZE");
		return NULL;
	}
	if (opt_debug)
		applog(LOG_DEBUG, "Max work group size reported %d", clState->max_work_size);

	/* For some reason 2 vectors is still better even if the card says
	 * otherwise, and many cards lie about their max so use 256 as max
	 * unless explicitly set on the command line. 79x0 cards perform
	 * better without vectors */
	if (clState->preferred_vwidth > 1) {
		if (strstr(name, "Tahiti"))
			clState->preferred_vwidth = 1;
		else
			clState->preferred_vwidth = 2;
	}

	if (opt_vectors)
		clState->preferred_vwidth = opt_vectors;
	if (opt_worksize && opt_worksize <= clState->max_work_size)
		clState->work_size = opt_worksize;
	else
		clState->work_size = (clState->max_work_size <= 256 ? clState->max_work_size : 256) /
				clState->preferred_vwidth;

	/* Create binary filename based on parameters passed to opencl
	 * compiler to ensure we only load a binary that matches what would
	 * have otherwise created. The filename is:
	 * name + kernelname +/i bitalign + v + vectors + w + work_size + sizeof(long) + .bin
	 */
	char binaryfilename[255];
	char numbuf[10];
	char filename[16];

	if (chosen_kernel == KL_NONE) {
		if (!clState->hasBitAlign || strstr(name, "Tahiti"))
			chosen_kernel = KL_POCLBM;
		else
			chosen_kernel = KL_PHATK;
	}

	switch (chosen_kernel) {
		case KL_POCLBM:
			strcpy(filename, "poclbm120203.cl");
			strcpy(binaryfilename, "poclbm120203");
			break;
		case KL_NONE: /* Shouldn't happen */
		case KL_PHATK:
			strcpy(filename, "phatk120203.cl");
			strcpy(binaryfilename, "phatk120203");
			break;
	}

	FILE *binaryfile;
	size_t *binary_sizes;
	char **binaries;
	int pl;
	char *source = file_contents(filename, &pl);
	size_t sourceSize[] = {(size_t)pl};

	if (!source)
		return NULL;

	binary_sizes = (size_t *)malloc(sizeof(size_t)*numDevices);
	if (unlikely(!binary_sizes)) {
		applog(LOG_ERR, "Unable to malloc binary_sizes");
		return NULL;
	}
	binaries = (char **)malloc(sizeof(char *)*numDevices);
	if (unlikely(!binaries)) {
		applog(LOG_ERR, "Unable to malloc binaries");
		return NULL;
	}

	strcat(binaryfilename, name);
	if (clState->hasBitAlign)
		strcat(binaryfilename, "bitalign");

	strcat(binaryfilename, "v");
	sprintf(numbuf, "%d", clState->preferred_vwidth);
	strcat(binaryfilename, numbuf);
	strcat(binaryfilename, "w");
	sprintf(numbuf, "%d", (int)clState->work_size);
	strcat(binaryfilename, numbuf);
	strcat(binaryfilename, "long");
	sprintf(numbuf, "%d", (int)sizeof(long));
	strcat(binaryfilename, numbuf);
	strcat(binaryfilename, ".bin");

	binaryfile = fopen(binaryfilename, "rb");
	if (!binaryfile) {
		if (opt_debug)
			applog(LOG_DEBUG, "No binary found, generating from source");
	} else {
		struct stat binary_stat;

		if (unlikely(stat(binaryfilename, &binary_stat))) {
			if (opt_debug)
				applog(LOG_DEBUG, "Unable to stat binary, generating from source");
			fclose(binaryfile);
			goto build;
		}
		if (!binary_stat.st_size)
			goto build;

		binary_sizes[gpu] = binary_stat.st_size;
		binaries[gpu] = (char *)malloc(binary_sizes[gpu]);
		if (unlikely(!binaries[gpu])) {
			applog(LOG_ERR, "Unable to malloc binaries");
			fclose(binaryfile);
			return NULL;
		}

		if (fread(binaries[gpu], 1, binary_sizes[gpu], binaryfile) != binary_sizes[gpu]) {
			applog(LOG_ERR, "Unable to fread binaries[gpu]");
			fclose(binaryfile);
			free(binaries[gpu]);
			goto build;
		}

		clState->program = clCreateProgramWithBinary(clState->context, 1, &devices[gpu], &binary_sizes[gpu], (const unsigned char **)&binaries[gpu], &status, NULL);
		if (status != CL_SUCCESS) {
			applog(LOG_ERR, "Error: Loading Binary into cl_program (clCreateProgramWithBinary)");
			fclose(binaryfile);
			free(binaries[gpu]);
			goto build;
		}
		fclose(binaryfile);
		if (opt_debug)
			applog(LOG_DEBUG, "Loaded binary image %s", binaryfilename);

		/* We don't need to patch this already loaded image, but need to
		 * set the flag for status later */
		if (clState->hasBitAlign)
			patchbfi = true;

		free(binaries[gpu]);
		goto built;
	}

	/////////////////////////////////////////////////////////////////
	// Load CL file, build CL program object, create CL kernel object
	/////////////////////////////////////////////////////////////////

build:
	clState->program = clCreateProgramWithSource(clState->context, 1, (const char **)&source, sourceSize, &status);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error: Loading Binary into cl_program (clCreateProgramWithSource)");
		return NULL;
	}

	clRetainProgram(clState->program);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error: Retaining Program (clRetainProgram)");
		return NULL;
	}

	/* create a cl program executable for all the devices specified */
	char *CompilerOptions = calloc(1, 256);

	sprintf(CompilerOptions, "-D WORKSIZE=%d -D VECTORS%d",
		(int)clState->work_size, clState->preferred_vwidth);
	if (opt_debug)
		applog(LOG_DEBUG, "Setting worksize to %d", clState->work_size);
	if (clState->preferred_vwidth > 1 && opt_debug)
		applog(LOG_DEBUG, "Patched source to suit %d vectors", clState->preferred_vwidth);

	if (clState->hasBitAlign) {
		strcat(CompilerOptions, " -D BITALIGN");
		if (opt_debug)
			applog(LOG_DEBUG, "cl_amd_media_ops found, setting BITALIGN");
		if (strstr(name, "Cedar") ||
		    strstr(name, "Redwood") ||
		    strstr(name, "Juniper") ||
		    strstr(name, "Cypress" ) ||
		    strstr(name, "Hemlock" ) ||
		    strstr(name, "Caicos" ) ||
		    strstr(name, "Turks" ) ||
		    strstr(name, "Barts" ) ||
		    strstr(name, "Cayman" ) ||
		    strstr(name, "Antilles" ) ||
		    strstr(name, "Wrestler" ) ||
		    strstr(name, "Zacate" ) ||
		    strstr(name, "WinterPark" ) ||
		    strstr(name, "BeaverCreek" ))
			patchbfi = true;
	} else if (opt_debug)
		applog(LOG_DEBUG, "cl_amd_media_ops not found, will not set BITALIGN");

	if (patchbfi) {
		strcat(CompilerOptions, " -D BFI_INT");
		if (opt_debug)
			applog(LOG_DEBUG, "BFI_INT patch requiring device found, patched source with BFI_INT");
	} else if (opt_debug)
		applog(LOG_DEBUG, "BFI_INT patch requiring device not found, will not BFI_INT patch");

	if (opt_debug)
		applog(LOG_DEBUG, "CompilerOptions: %s", CompilerOptions);
	status = clBuildProgram(clState->program, 1, &devices[gpu], CompilerOptions , NULL, NULL);
	free(CompilerOptions);

	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error: Building Program (clBuildProgram)");
		size_t logSize;
		status = clGetProgramBuildInfo(clState->program, devices[gpu], CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize);

		char *log = malloc(logSize);
		status = clGetProgramBuildInfo(clState->program, devices[gpu], CL_PROGRAM_BUILD_LOG, logSize, log, NULL);
		applog(LOG_INFO, "%s", log);
		return NULL;
	}

	prog_built = true;

	status = clGetProgramInfo( clState->program, CL_PROGRAM_BINARY_SIZES, sizeof(size_t)*numDevices, binary_sizes, NULL );
	if (unlikely(status != CL_SUCCESS)) {
		applog(LOG_ERR, "Error: Getting program info CL_PROGRAM_BINARY_SIZES. (clGetPlatformInfo)");
		return NULL;
	}

	/* copy over all of the generated binaries. */
	if (opt_debug)
		applog(LOG_DEBUG, "binary size %d : %d", gpu, binary_sizes[gpu]);
	if (!binary_sizes[gpu]) {
		applog(LOG_ERR, "OpenCL compiler generated a zero sized binary, may need to reboot!");
		return NULL;
	}
	binaries[gpu] = (char *)malloc( sizeof(char)*binary_sizes[gpu]);
	status = clGetProgramInfo( clState->program, CL_PROGRAM_BINARIES, sizeof(char *)*numDevices, binaries, NULL );
	if (unlikely(status != CL_SUCCESS)) {
		applog(LOG_ERR, "Error: Getting program info. (clGetPlatformInfo)");
		return NULL;
	}

	/* Patch the kernel if the hardware supports BFI_INT but it needs to
	 * be hacked in */
	if (patchbfi) {
		unsigned remaining = binary_sizes[gpu];
		char *w = binaries[gpu];
		unsigned int start, length;

		/* Find 2nd incidence of .text, and copy the program's
		* position and length at a fixed offset from that. Then go
		* back and find the 2nd incidence of \x7ELF (rewind by one
		* from ELF) and then patch the opcocdes */
		if (!advance(&w, &remaining, ".text"))
			{patchbfi = 0; goto build;}
		w++; remaining--;
		if (!advance(&w, &remaining, ".text")) {
			/* 32 bit builds only one ELF */
			w--; remaining++;
		}
		memcpy(&start, w + 285, 4);
		memcpy(&length, w + 289, 4);
		w = binaries[gpu]; remaining = binary_sizes[gpu];
		if (!advance(&w, &remaining, "ELF"))
			{patchbfi = 0; goto build;}
		w++; remaining--;
		if (!advance(&w, &remaining, "ELF")) {
			/* 32 bit builds only one ELF */
			w--; remaining++;
		}
		w--; remaining++;
		w += start; remaining -= start;
		if (opt_debug)
			applog(LOG_DEBUG, "At %p (%u rem. bytes), to begin patching",
				w, remaining);
		patch_opcodes(w, length);

		status = clReleaseProgram(clState->program);
		if (status != CL_SUCCESS) {
			applog(LOG_ERR, "Error: Releasing program. (clReleaseProgram)");
			return NULL;
		}

		clState->program = clCreateProgramWithBinary(clState->context, 1, &devices[gpu], &binary_sizes[gpu], (const unsigned char **)&binaries[gpu], &status, NULL);
		if (status != CL_SUCCESS) {
			applog(LOG_ERR, "Error: Loading Binary into cl_program (clCreateProgramWithBinary)");
			return NULL;
		}

		clRetainProgram(clState->program);
		if (status != CL_SUCCESS) {
			applog(LOG_ERR, "Error: Retaining Program (clRetainProgram)");
			return NULL;
		}

		/* Program needs to be rebuilt */
		prog_built = false;
	}

	free(source);

	/* Save the binary to be loaded next time */
	binaryfile = fopen(binaryfilename, "wb");
	if (!binaryfile) {
		/* Not a fatal problem, just means we build it again next time */
		if (opt_debug)
			applog(LOG_DEBUG, "Unable to create file %s", binaryfilename);
	} else {
		if (unlikely(fwrite(binaries[gpu], 1, binary_sizes[gpu], binaryfile) != binary_sizes[gpu])) {
			applog(LOG_ERR, "Unable to fwrite to binaryfile");
			return NULL;
		}
		fclose(binaryfile);
	}
	if (binaries[gpu])
		free(binaries[gpu]);
built:
	free(binaries);
	free(binary_sizes);

	applog(LOG_INFO, "Initialising kernel %s with%s BFI_INT, %d vectors and worksize %d",
	       filename, patchbfi ? "" : "out", clState->preferred_vwidth, clState->work_size);

	if (!prog_built) {
		/* create a cl program executable for all the devices specified */
		status = clBuildProgram(clState->program, 1, &devices[gpu], NULL, NULL, NULL);
		if (status != CL_SUCCESS) {
			applog(LOG_ERR, "Error: Building Program (clBuildProgram)");
			size_t logSize;
			status = clGetProgramBuildInfo(clState->program, devices[gpu], CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize);

			char *log = malloc(logSize);
			status = clGetProgramBuildInfo(clState->program, devices[gpu], CL_PROGRAM_BUILD_LOG, logSize, log, NULL);
			applog(LOG_INFO, "%s", log);
			return NULL;
		}

		clRetainProgram(clState->program);
		if (status != CL_SUCCESS) {
			applog(LOG_ERR, "Error: Retaining Program (clRetainProgram)");
			return NULL;
		}
	}

	/* get a kernel object handle for a kernel with the given name */
	clState->kernel = clCreateKernel(clState->program, "search", &status);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error: Creating Kernel from program. (clCreateKernel)");
		return NULL;
	}

	/////////////////////////////////////////////////////////////////
	// Create an OpenCL command queue
	/////////////////////////////////////////////////////////////////
	clState->commandQueue = clCreateCommandQueue(clState->context, devices[gpu],
						     CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, &status);
	if (status != CL_SUCCESS) /* Try again without OOE enable */
		clState->commandQueue = clCreateCommandQueue(clState->context, devices[gpu], 0 , &status);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Creating Command Queue. (clCreateCommandQueue)");
		return NULL;
	}

	clState->outputBuffer = clCreateBuffer(clState->context, CL_MEM_READ_WRITE, BUFFERSIZE, NULL, &status);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error: clCreateBuffer (outputBuffer)");
		return NULL;
	}

	return clState;
}
Пример #22
0
_clState *initCl(unsigned int gpu, char *name, size_t nameSize)
{
	_clState *clState = calloc(1, sizeof(_clState));
	bool patchbfi = false, prog_built = false;
	struct cgpu_info *cgpu = &gpus[gpu];
	cl_platform_id platform = NULL;
	char pbuff[256], vbuff[255];
	cl_platform_id* platforms;
	cl_uint preferred_vwidth;
	cl_device_id *devices;
	cl_uint numPlatforms;
	cl_uint numDevices;
	cl_int status;

	status = clGetPlatformIDs(0, NULL, &numPlatforms);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error %d: Getting Platforms. (clGetPlatformsIDs)", status);
		return NULL;
	}

	platforms = (cl_platform_id *)alloca(numPlatforms*sizeof(cl_platform_id));
	status = clGetPlatformIDs(numPlatforms, platforms, NULL);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error %d: Getting Platform Ids. (clGetPlatformsIDs)", status);
		return NULL;
	}

	if (opt_platform_id >= (int)numPlatforms) {
		applog(LOG_ERR, "Specified platform that does not exist");
		return NULL;
	}

	status = clGetPlatformInfo(platforms[opt_platform_id], CL_PLATFORM_VENDOR, sizeof(pbuff), pbuff, NULL);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error %d: Getting Platform Info. (clGetPlatformInfo)", status);
		return NULL;
	}
	platform = platforms[opt_platform_id];

	if (platform == NULL) {
		perror("NULL platform found!\n");
		return NULL;
	}

	applog(LOG_INFO, "CL Platform vendor: %s", pbuff);
	status = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(pbuff), pbuff, NULL);
	if (status == CL_SUCCESS)
		applog(LOG_INFO, "CL Platform name: %s", pbuff);
	status = clGetPlatformInfo(platform, CL_PLATFORM_VERSION, sizeof(vbuff), vbuff, NULL);
	if (status == CL_SUCCESS)
		applog(LOG_INFO, "CL Platform version: %s", vbuff);

	status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 0, NULL, &numDevices);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error %d: Getting Device IDs (num)", status);
		return NULL;
	}

	if (numDevices > 0 ) {
		devices = (cl_device_id *)malloc(numDevices*sizeof(cl_device_id));

		/* Now, get the device list data */

		status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, numDevices, devices, NULL);
		if (status != CL_SUCCESS) {
			applog(LOG_ERR, "Error %d: Getting Device IDs (list)", status);
			return NULL;
		}

		applog(LOG_INFO, "List of devices:");

		unsigned int i;
		for (i = 0; i < numDevices; i++) {
			status = clGetDeviceInfo(devices[i], CL_DEVICE_NAME, sizeof(pbuff), pbuff, NULL);
			if (status != CL_SUCCESS) {
				applog(LOG_ERR, "Error %d: Getting Device Info", status);
				return NULL;
			}

			applog(LOG_INFO, "\t%i\t%s", i, pbuff);
		}

		if (gpu < numDevices) {
			status = clGetDeviceInfo(devices[gpu], CL_DEVICE_NAME, sizeof(pbuff), pbuff, NULL);
			if (status != CL_SUCCESS) {
				applog(LOG_ERR, "Error %d: Getting Device Info", status);
				return NULL;
			}

			applog(LOG_INFO, "Selected %i: %s", gpu, pbuff);
			strncpy(name, pbuff, nameSize);
		} else {
			applog(LOG_ERR, "Invalid GPU %i", gpu);
			return NULL;
		}

	} else return NULL;

	cl_context_properties cps[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0 };

	clState->context = clCreateContextFromType(cps, CL_DEVICE_TYPE_GPU, NULL, NULL, &status);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error %d: Creating Context. (clCreateContextFromType)", status);
		return NULL;
	}

	/////////////////////////////////////////////////////////////////
	// Create an OpenCL command queue
	/////////////////////////////////////////////////////////////////
	clState->commandQueue = clCreateCommandQueue(clState->context, devices[gpu],
						     CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, &status);
	if (status != CL_SUCCESS) /* Try again without OOE enable */
		clState->commandQueue = clCreateCommandQueue(clState->context, devices[gpu], 0 , &status);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error %d: Creating Command Queue. (clCreateCommandQueue)", status);
		return NULL;
	}

	/* Check for BFI INT support. Hopefully people don't mix devices with
	 * and without it! */
	char * extensions = malloc(1024);
	const char * camo = "cl_amd_media_ops";
	char *find;

	status = clGetDeviceInfo(devices[gpu], CL_DEVICE_EXTENSIONS, 1024, (void *)extensions, NULL);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_EXTENSIONS", status);
		return NULL;
	}
	find = strstr(extensions, camo);
	if (find)
		clState->hasBitAlign = true;
		
	/* Check for OpenCL >= 1.0 support, needed for global offset parameter usage. */
	char * devoclver = malloc(1024);
	const char * ocl10 = "OpenCL 1.0";
	const char * ocl11 = "OpenCL 1.1";

	status = clGetDeviceInfo(devices[gpu], CL_DEVICE_VERSION, 1024, (void *)devoclver, NULL);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_VERSION", status);
		return NULL;
	}
	find = strstr(devoclver, ocl10);
	if (!find) {
		clState->hasOpenCL11plus = true;
		find = strstr(devoclver, ocl11);
		if (!find)
			clState->hasOpenCL12plus = true;
	}

	status = clGetDeviceInfo(devices[gpu], CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT, sizeof(cl_uint), (void *)&preferred_vwidth, NULL);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT", status);
		return NULL;
	}
	applog(LOG_DEBUG, "Preferred vector width reported %d", preferred_vwidth);

	status = clGetDeviceInfo(devices[gpu], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), (void *)&clState->max_work_size, NULL);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_MAX_WORK_GROUP_SIZE", status);
		return NULL;
	}
	applog(LOG_DEBUG, "Max work group size reported %d", (int)(clState->max_work_size));

	size_t compute_units = 0;
	status = clGetDeviceInfo(devices[gpu], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(size_t), (void *)&compute_units, NULL);
	if (status != CL_SUCCESS) {
	applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_MAX_COMPUTE_UNITS", status);
	return NULL;
	}
	// AMD architechture got 64 compute shaders per compute unit.
	// Source: http://www.amd.com/us/Documents/GCN_Architecture_whitepaper.pdf
	clState->compute_shaders = compute_units * 64;
	applog(LOG_DEBUG, "Max shaders calculated %d", (int)(clState->compute_shaders));

	status = clGetDeviceInfo(devices[gpu], CL_DEVICE_MAX_MEM_ALLOC_SIZE , sizeof(cl_ulong), (void *)&cgpu->max_alloc, NULL);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_MAX_MEM_ALLOC_SIZE", status);
		return NULL;
	}
	applog(LOG_DEBUG, "Max mem alloc size is %lu", (long unsigned int)(cgpu->max_alloc));

	/* Create binary filename based on parameters passed to opencl
	 * compiler to ensure we only load a binary that matches what would
	 * have otherwise created. The filename is:
	 * name + kernelname +/- g(offset) + v + vectors + w + work_size + l + sizeof(long) + .bin
	 * For scrypt the filename is:
	 * name + kernelname + g + lg + lookup_gap + tc + thread_concurrency + w + work_size + l + sizeof(long) + .bin
	 */
	char binaryfilename[255];
	char filename[255];
	char numbuf[16];

	if (cgpu->kernel == KL_NONE) {
		if (opt_scrypt) {
			if (opt_scrypt_chacha) {
				applog(LOG_INFO, "Selecting scrypt-chacha kernel");
				clState->chosen_kernel = KL_SCRYPT_CHACHA;
			} else if (opt_n_scrypt) {
				applog(LOG_INFO, "Selecting N-scrypt kernel");
				clState->chosen_kernel = KL_N_SCRYPT;
			} else {
				applog(LOG_INFO, "Selecting standard scrypt kernel");
				clState->chosen_kernel = KL_SCRYPT;
			}

		} else if (!strstr(name, "Tahiti") &&
			/* Detect all 2.6 SDKs not with Tahiti and use diablo kernel */
			(strstr(vbuff, "844.4") ||  // Linux 64 bit ATI 2.6 SDK
			 strstr(vbuff, "851.4") ||  // Windows 64 bit ""
			 strstr(vbuff, "831.4") ||
			 strstr(vbuff, "898.1") ||  // 12.2 driver SDK 
			 strstr(vbuff, "923.1") ||  // 12.4
			 strstr(vbuff, "938.2") ||  // SDK 2.7
			 strstr(vbuff, "1113.2"))) {// SDK 2.8
				applog(LOG_INFO, "Selecting diablo kernel");
				clState->chosen_kernel = KL_DIABLO;
		/* Detect all 7970s, older ATI and NVIDIA and use poclbm */
		} else if (strstr(name, "Tahiti") || !clState->hasBitAlign) {
			applog(LOG_INFO, "Selecting poclbm kernel");
			clState->chosen_kernel = KL_POCLBM;
		/* Use phatk for the rest R5xxx R6xxx */
		} else {
			applog(LOG_INFO, "Selecting phatk kernel");
			clState->chosen_kernel = KL_PHATK;
		}
		cgpu->kernel = clState->chosen_kernel;
	} else {
		clState->chosen_kernel = cgpu->kernel;
		if (clState->chosen_kernel == KL_PHATK &&
		    (strstr(vbuff, "844.4") || strstr(vbuff, "851.4") ||
		     strstr(vbuff, "831.4") || strstr(vbuff, "898.1") ||
		     strstr(vbuff, "923.1") || strstr(vbuff, "938.2") ||
		     strstr(vbuff, "1113.2"))) {
			applog(LOG_WARNING, "WARNING: You have selected the phatk kernel.");
			applog(LOG_WARNING, "You are running SDK 2.6+ which performs poorly with this kernel.");
			applog(LOG_WARNING, "Downgrade your SDK and delete any .bin files before starting again.");
			applog(LOG_WARNING, "Or allow cgminer to automatically choose a more suitable kernel.");
		}
	}

	/* For some reason 2 vectors is still better even if the card says
	 * otherwise, and many cards lie about their max so use 256 as max
	 * unless explicitly set on the command line. Tahiti prefers 1 */
	if (strstr(name, "Tahiti"))
		preferred_vwidth = 1;
	else if (preferred_vwidth > 2)
		preferred_vwidth = 2;

	switch (clState->chosen_kernel) {
		case KL_POCLBM:
			strcpy(filename, POCLBM_KERNNAME".cl");
			strcpy(binaryfilename, POCLBM_KERNNAME);
			break;
		case KL_PHATK:
			strcpy(filename, PHATK_KERNNAME".cl");
			strcpy(binaryfilename, PHATK_KERNNAME);
			break;
		case KL_DIAKGCN:
			strcpy(filename, DIAKGCN_KERNNAME".cl");
			strcpy(binaryfilename, DIAKGCN_KERNNAME);
			break;
		case KL_SCRYPT:
			strcpy(filename, SCRYPT_KERNNAME".cl");
			strcpy(binaryfilename, SCRYPT_KERNNAME);
			/* Scrypt only supports vector 1 */
			cgpu->vwidth = 1;
			break;
		case KL_N_SCRYPT:
			strcpy(filename, N_SCRYPT_KERNNAME".cl");
			strcpy(binaryfilename, N_SCRYPT_KERNNAME);
			/* Scrypt only supports vector 1 */
			cgpu->vwidth = 1;
			break;
		case KL_SCRYPT_CHACHA:
			strcpy(filename, SCRYPT_CHACHA_KERNNAME".cl");
			strcpy(binaryfilename, SCRYPT_CHACHA_KERNNAME);
			/* Scrypt only supports vector 1 */
			cgpu->vwidth = 1;
			break;
		case KL_NONE: /* Shouldn't happen */
		case KL_DIABLO:
			strcpy(filename, DIABLO_KERNNAME".cl");
			strcpy(binaryfilename, DIABLO_KERNNAME);
			break;
	}

	if (cgpu->vwidth)
		clState->vwidth = cgpu->vwidth;
	else {
		clState->vwidth = preferred_vwidth;
		cgpu->vwidth = preferred_vwidth;
	}

	if (((clState->chosen_kernel == KL_POCLBM || clState->chosen_kernel == KL_DIABLO || clState->chosen_kernel == KL_DIAKGCN) &&
		clState->vwidth == 1 && clState->hasOpenCL11plus) || opt_scrypt)
			clState->goffset = true;

	if (cgpu->work_size && cgpu->work_size <= clState->max_work_size)
		clState->wsize = cgpu->work_size;
	else if (opt_scrypt)
		clState->wsize = 256;
	else if (strstr(name, "Tahiti"))
		clState->wsize = 64;
	else
		clState->wsize = (clState->max_work_size <= 256 ? clState->max_work_size : 256) / clState->vwidth;
	cgpu->work_size = clState->wsize;

#ifdef USE_SCRYPT
	if (opt_scrypt) {
		if (!cgpu->opt_lg) {
			applog(LOG_NOTICE, "GPU %d: selecting lookup gap of 4", gpu);
			cgpu->lookup_gap = 4;
		} else
			cgpu->lookup_gap = cgpu->opt_lg;

		unsigned int bsize = opt_n_scrypt ? 2048 : 1024;
		size_t ipt = (bsize / cgpu->lookup_gap + (bsize % cgpu->lookup_gap > 0));

		// if we do not have TC and we do not have BS, then calculate some conservative numbers
		if ((!cgpu->opt_tc) && (!cgpu->buffer_size)) {
			unsigned int base_alloc;

			// default to 88% of the available memory and find the closest MB value divisible by 8
			base_alloc = (int)(cgpu->max_alloc * 88 / 100 / 1024 / 1024 / 8) * 8 * 1024 * 1024 / cgpu->threads;
			// base_alloc is now the number of bytes to allocate.  
			// 2 threads of 336 MB did not fit into dedicated VRAM while 1 thread of 772MB did.  334 MB each did
			// to be safe, reduce by 2MB per thread beyond the first

			base_alloc -= (cgpu->threads - 1) * 2 * 1024 * 1024;

			cgpu->thread_concurrency = base_alloc / 128 / ipt;
			cgpu->buffer_size = base_alloc / 1024 / 1024;
			applog(LOG_DEBUG,"88%% Max Allocation: %u",base_alloc);
			applog(LOG_NOTICE, "GPU %d: selecting buffer_size of %zu", gpu, cgpu->buffer_size);
		} else
			cgpu->thread_concurrency = cgpu->opt_tc;

		if (cgpu->buffer_size) {
			// use the buffer-size to overwrite the thread-concurrency
			cgpu->thread_concurrency = (int)((cgpu->buffer_size * 1024 * 1024) / ipt / 128);
			applog(LOG_DEBUG, "GPU %d: setting thread_concurrency to %d based on buffer size %d and lookup gap %d", gpu, (int)(cgpu->thread_concurrency),(int)(cgpu->buffer_size),(int)(cgpu->lookup_gap));
		}
	}
#endif

	FILE *binaryfile;
	size_t *binary_sizes;
	char **binaries;
	int pl;
	char *source = file_contents(filename, &pl);
	size_t sourceSize[] = {(size_t)pl};
	cl_uint slot, cpnd;

	slot = cpnd = 0;

	if (!source)
		return NULL;

	binary_sizes = calloc(sizeof(size_t) * MAX_GPUDEVICES * 4, 1);
	if (unlikely(!binary_sizes)) {
		applog(LOG_ERR, "Unable to calloc binary_sizes");
		return NULL;
	}
	binaries = calloc(sizeof(char *) * MAX_GPUDEVICES * 4, 1);
	if (unlikely(!binaries)) {
		applog(LOG_ERR, "Unable to calloc binaries");
		return NULL;
	}

	strcat(binaryfilename, name);
	if (clState->goffset)
		strcat(binaryfilename, "g");
	if (opt_scrypt) {
#ifdef USE_SCRYPT
		sprintf(numbuf, "lg%utc%u", cgpu->lookup_gap, (unsigned int)cgpu->thread_concurrency);
		strcat(binaryfilename, numbuf);
#endif
	} else {
		sprintf(numbuf, "v%d", clState->vwidth);
		strcat(binaryfilename, numbuf);
	}
	sprintf(numbuf, "w%d", (int)clState->wsize);
	strcat(binaryfilename, numbuf);
	sprintf(numbuf, "l%d", (int)sizeof(long));
	strcat(binaryfilename, numbuf);
	strcat(binaryfilename, ".bin");

	binaryfile = fopen(binaryfilename, "rb");
	if (!binaryfile) {
		applog(LOG_DEBUG, "No binary found, generating from source");
	} else {
		struct stat binary_stat;

		if (unlikely(stat(binaryfilename, &binary_stat))) {
			applog(LOG_DEBUG, "Unable to stat binary, generating from source");
			fclose(binaryfile);
			goto build;
		}
		if (!binary_stat.st_size)
			goto build;

		binary_sizes[slot] = binary_stat.st_size;
		binaries[slot] = (char *)calloc(binary_sizes[slot], 1);
		if (unlikely(!binaries[slot])) {
			applog(LOG_ERR, "Unable to calloc binaries");
			fclose(binaryfile);
			return NULL;
		}

		if (fread(binaries[slot], 1, binary_sizes[slot], binaryfile) != binary_sizes[slot]) {
			applog(LOG_ERR, "Unable to fread binaries");
			fclose(binaryfile);
			free(binaries[slot]);
			goto build;
		}

		clState->program = clCreateProgramWithBinary(clState->context, 1, &devices[gpu], &binary_sizes[slot], (const unsigned char **)binaries, &status, NULL);
		if (status != CL_SUCCESS) {
			applog(LOG_ERR, "Error %d: Loading Binary into cl_program (clCreateProgramWithBinary)", status);
			fclose(binaryfile);
			free(binaries[slot]);
			goto build;
		}

		fclose(binaryfile);
		applog(LOG_DEBUG, "Loaded binary image %s", binaryfilename);

		goto built;
	}

	/////////////////////////////////////////////////////////////////
	// Load CL file, build CL program object, create CL kernel object
	/////////////////////////////////////////////////////////////////

build:
	clState->program = clCreateProgramWithSource(clState->context, 1, (const char **)&source, sourceSize, &status);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error %d: Loading Binary into cl_program (clCreateProgramWithSource)", status);
		return NULL;
	}

	/* create a cl program executable for all the devices specified */
	char *CompilerOptions = calloc(1, 256);

#ifdef USE_SCRYPT
	if (opt_scrypt)
	{
		sprintf(CompilerOptions, "-D LOOKUP_GAP=%d -D CONCURRENT_THREADS=%d -D WORKSIZE=%d",
			cgpu->lookup_gap, (unsigned int)cgpu->thread_concurrency, (int)clState->wsize);
	}
	else
#endif
	{
		sprintf(CompilerOptions, "-D WORKSIZE=%d -D VECTORS%d -D WORKVEC=%d",
			(int)clState->wsize, clState->vwidth, (int)clState->wsize * clState->vwidth);
	}
	applog(LOG_DEBUG, "Setting worksize to %d", (int)(clState->wsize));
	if (clState->vwidth > 1)
		applog(LOG_DEBUG, "Patched source to suit %d vectors", clState->vwidth);

	if (clState->hasBitAlign) {
		strcat(CompilerOptions, " -D BITALIGN");
		applog(LOG_DEBUG, "cl_amd_media_ops found, setting BITALIGN");
		if (!clState->hasOpenCL12plus &&
		    (strstr(name, "Cedar") ||
		     strstr(name, "Redwood") ||
		     strstr(name, "Juniper") ||
		     strstr(name, "Cypress" ) ||
		     strstr(name, "Hemlock" ) ||
		     strstr(name, "Caicos" ) ||
		     strstr(name, "Turks" ) ||
		     strstr(name, "Barts" ) ||
		     strstr(name, "Cayman" ) ||
		     strstr(name, "Antilles" ) ||
		     strstr(name, "Wrestler" ) ||
		     strstr(name, "Zacate" ) ||
		     strstr(name, "WinterPark" )))
			patchbfi = true;
	} else
		applog(LOG_DEBUG, "cl_amd_media_ops not found, will not set BITALIGN");

	if (patchbfi) {
		strcat(CompilerOptions, " -D BFI_INT");
		applog(LOG_DEBUG, "BFI_INT patch requiring device found, patched source with BFI_INT");
	} else
		applog(LOG_DEBUG, "BFI_INT patch requiring device not found, will not BFI_INT patch");

	if (clState->goffset)
		strcat(CompilerOptions, " -D GOFFSET");

	if (!clState->hasOpenCL11plus)
		strcat(CompilerOptions, " -D OCL1");

	applog(LOG_DEBUG, "CompilerOptions: %s", CompilerOptions);
	status = clBuildProgram(clState->program, 1, &devices[gpu], CompilerOptions , NULL, NULL);
	free(CompilerOptions);

	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error %d: Building Program (clBuildProgram)", status);
		size_t logSize;
		status = clGetProgramBuildInfo(clState->program, devices[gpu], CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize);

		char *log = malloc(logSize);
		status = clGetProgramBuildInfo(clState->program, devices[gpu], CL_PROGRAM_BUILD_LOG, logSize, log, NULL);
		applog(LOG_ERR, "%s", log);
		return NULL;
	} else {
		applog(LOG_DEBUG, "Success: Building Program (clBuildProgram)");
	}

	prog_built = true;

#ifdef __APPLE__
	/* OSX OpenCL breaks reading off binaries with >1 GPU so always build
	 * from source. */
	goto built;
#endif

	status = clGetProgramInfo(clState->program, CL_PROGRAM_NUM_DEVICES, sizeof(cl_uint), &cpnd, NULL);
	if (unlikely(status != CL_SUCCESS)) {
		applog(LOG_ERR, "Error %d: Getting program info CL_PROGRAM_NUM_DEVICES. (clGetProgramInfo)", status);
		return NULL;
	}

	status = clGetProgramInfo(clState->program, CL_PROGRAM_BINARY_SIZES, sizeof(size_t)*cpnd, binary_sizes, NULL);
	if (unlikely(status != CL_SUCCESS)) {
		applog(LOG_ERR, "Error %d: Getting program info CL_PROGRAM_BINARY_SIZES. (clGetProgramInfo)", status);
		return NULL;
	}

	/* The actual compiled binary ends up in a RANDOM slot! Grr, so we have
	 * to iterate over all the binary slots and find where the real program
	 * is. What the heck is this!? */
	for (slot = 0; slot < cpnd; slot++)
		if (binary_sizes[slot])
			break;

	/* copy over all of the generated binaries. */
	applog(LOG_DEBUG, "Binary size for gpu %d found in binary slot %d: %d", gpu, slot, (int)(binary_sizes[slot]));
	if (!binary_sizes[slot]) {
		applog(LOG_ERR, "OpenCL compiler generated a zero sized binary, FAIL!");
		return NULL;
	}
	binaries[slot] = calloc(sizeof(char) * binary_sizes[slot], 1);
	status = clGetProgramInfo(clState->program, CL_PROGRAM_BINARIES, sizeof(char *) * cpnd, binaries, NULL );
	if (unlikely(status != CL_SUCCESS)) {
		applog(LOG_ERR, "Error %d: Getting program info. CL_PROGRAM_BINARIES (clGetProgramInfo)", status);
		return NULL;
	}

	/* Patch the kernel if the hardware supports BFI_INT but it needs to
	 * be hacked in */
	if (patchbfi) {
		unsigned remaining = binary_sizes[slot];
		char *w = binaries[slot];
		unsigned int start, length;

		/* Find 2nd incidence of .text, and copy the program's
		* position and length at a fixed offset from that. Then go
		* back and find the 2nd incidence of \x7ELF (rewind by one
		* from ELF) and then patch the opcocdes */
		if (!advance(&w, &remaining, ".text"))
			goto build;
		w++; remaining--;
		if (!advance(&w, &remaining, ".text")) {
			/* 32 bit builds only one ELF */
			w--; remaining++;
		}
		memcpy(&start, w + 285, 4);
		memcpy(&length, w + 289, 4);
		w = binaries[slot]; remaining = binary_sizes[slot];
		if (!advance(&w, &remaining, "ELF"))
			goto build;
		w++; remaining--;
		if (!advance(&w, &remaining, "ELF")) {
			/* 32 bit builds only one ELF */
			w--; remaining++;
		}
		w--; remaining++;
		w += start; remaining -= start;
		applog(LOG_DEBUG, "At %p (%u rem. bytes), to begin patching", w, remaining);
		patch_opcodes(w, length);

		status = clReleaseProgram(clState->program);
		if (status != CL_SUCCESS) {
			applog(LOG_ERR, "Error %d: Releasing program. (clReleaseProgram)", status);
			return NULL;
		}

		clState->program = clCreateProgramWithBinary(clState->context, 1, &devices[gpu], &binary_sizes[slot], (const unsigned char **)&binaries[slot], &status, NULL);
		if (status != CL_SUCCESS) {
			applog(LOG_ERR, "Error %d: Loading Binary into cl_program (clCreateProgramWithBinary)", status);
			return NULL;
		}

		/* Program needs to be rebuilt */
		prog_built = false;
	}

	free(source);

	/* Save the binary to be loaded next time */
	binaryfile = fopen(binaryfilename, "wb");
	if (!binaryfile) {
		/* Not a fatal problem, just means we build it again next time */
		applog(LOG_DEBUG, "Unable to create file %s", binaryfilename);
	} else {
		if (unlikely(fwrite(binaries[slot], 1, binary_sizes[slot], binaryfile) != binary_sizes[slot])) {
			applog(LOG_ERR, "Unable to fwrite to binaryfile");
			return NULL;
		}
		fclose(binaryfile);
	}
built:
	if (binaries[slot])
		free(binaries[slot]);
	free(binaries);
	free(binary_sizes);

	applog(LOG_INFO, "Initialising kernel %s with%s bitalign, %d vectors and worksize %d",
	       filename, clState->hasBitAlign ? "" : "out", clState->vwidth, (int)(clState->wsize));

	if (!prog_built) {
		/* create a cl program executable for all the devices specified */
		status = clBuildProgram(clState->program, 1, &devices[gpu], NULL, NULL, NULL);
		if (status != CL_SUCCESS) {
			applog(LOG_ERR, "Error %d: Building Program (clBuildProgram)", status);
			size_t logSize;
			status = clGetProgramBuildInfo(clState->program, devices[gpu], CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize);

			char *log = malloc(logSize);
			status = clGetProgramBuildInfo(clState->program, devices[gpu], CL_PROGRAM_BUILD_LOG, logSize, log, NULL);
			applog(LOG_ERR, "%s", log);
			return NULL;
		}
	}

	/* get a kernel object handle for a kernel with the given name */
	clState->kernel = clCreateKernel(clState->program, "search", &status);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error %d: Creating Kernel from program. (clCreateKernel)", status);
		return NULL;
	}

#ifdef USE_SCRYPT
	if (opt_scrypt) {

		unsigned int bsize = opt_n_scrypt ? 2048 : 1024;
		size_t ipt = (bsize / cgpu->lookup_gap + (bsize % cgpu->lookup_gap > 0));
		size_t bufsize = 128 * ipt * cgpu->thread_concurrency;

		if (!cgpu->buffer_size) {
			applog(LOG_NOTICE, "GPU %d: bufsize for thread @ %dMB based on TC of %zu", gpu, (int)(bufsize/1048576),cgpu->thread_concurrency);
		} else {
			applog(LOG_NOTICE, "GPU %d: bufsize for thread @ %dMB based on buffer-size", gpu, (int)(cgpu->buffer_size));
			bufsize = (size_t)(cgpu->buffer_size)*(1048576);
		}

		/* Use the max alloc value which has been rounded to a power of
		 * 2 greater >= required amount earlier */
		if (bufsize > cgpu->max_alloc) {
			applog(LOG_WARNING, "Maximum buffer memory device %d supports says %lu",
						gpu, (long unsigned int)(cgpu->max_alloc));
			applog(LOG_WARNING, "Your scrypt settings come to %d", (int)bufsize);
		}
		applog(LOG_INFO, "Creating scrypt buffer sized %d", (int)bufsize);
		clState->padbufsize = bufsize;

		/* This buffer is weird and might work to some degree even if
		 * the create buffer call has apparently failed, so check if we
		 * get anything back before we call it a failure. */
		clState->padbuffer8 = NULL;
		clState->padbuffer8 = clCreateBuffer(clState->context, CL_MEM_READ_WRITE, bufsize, NULL, &status);
		if (status != CL_SUCCESS && !clState->padbuffer8) {
			applog(LOG_ERR, "Error %d: clCreateBuffer (padbuffer8), decrease TC or increase LG", status);
			return NULL;
		}

		clState->CLbuffer0 = clCreateBuffer(clState->context, CL_MEM_READ_ONLY, 128, NULL, &status);
		if (status != CL_SUCCESS) {
			applog(LOG_ERR, "Error %d: clCreateBuffer (CLbuffer0)", status);
			return NULL;
		}
		clState->outputBuffer = clCreateBuffer(clState->context, CL_MEM_WRITE_ONLY, SCRYPT_BUFFERSIZE, NULL, &status);
	} else
#endif
	clState->outputBuffer = clCreateBuffer(clState->context, CL_MEM_WRITE_ONLY, BUFFERSIZE, NULL, &status);
	if (status != CL_SUCCESS) {
		applog(LOG_ERR, "Error %d: clCreateBuffer (outputBuffer)", status);
		return NULL;
	}

	return clState;
}
shader_manager::resource
shader_manager::load (const std::string& location)
{
    return std::make_shared<std::string>(file_contents(resource_file(res_shader, location)));
}
Пример #24
0
{
    prepare_logdir();
    std::string filename = "logs/simple_log.txt";

    auto logger = spdlog::create<spdlog::sinks::simple_file_sink_mt>("logger", filename, true);
    logger->set_pattern("%v");
#if !defined(SPDLOG_FMT_PRINTF)
    logger->info("Test message {} {}", 1);
    logger->info("Test message {}", 2);
#else
    logger->info("Test message %d %d", 1);
    logger->info("Test message %d", 2);
#endif
    logger->flush();

    REQUIRE(file_contents(filename) == std::string("Test message 2\n"));
    REQUIRE(count_lines(filename) == 1);
}

struct custom_ex
{
};
TEST_CASE("custom_error_handler", "[errors]]")
{
    prepare_logdir();
    std::string filename = "logs/simple_log.txt";
    auto logger = spdlog::create<spdlog::sinks::simple_file_sink_mt>("logger", filename, true);
    logger->flush_on(spdlog::level::info);
    logger->set_error_handler([=](const std::string &msg) { throw custom_ex(); });
    logger->info("Good message #1");
#if !defined(SPDLOG_FMT_PRINTF)