ocl.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2012-2014 Luke Dashjr
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the Free
  7. * Software Foundation; either version 3 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #include "config.h"
  11. #include <ctype.h>
  12. #include <limits.h>
  13. #include <signal.h>
  14. #include <stdbool.h>
  15. #include <stdint.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <stdio.h>
  19. #include <sys/types.h>
  20. #include <time.h>
  21. #include <sys/time.h>
  22. #include <pthread.h>
  23. #include <sys/stat.h>
  24. #include <unistd.h>
  25. #define OMIT_OPENCL_API
  26. #include "deviceapi.h"
  27. #include "driver-opencl.h"
  28. #include "findnonce.h"
  29. #include "logging.h"
  30. #include "miner.h"
  31. #include "ocl.h"
  32. #include "sha2.h"
  33. #include "util.h"
  34. /* Platform API */
  35. extern
  36. CL_API_ENTRY cl_int CL_API_CALL
  37. (*clGetPlatformIDs)(cl_uint /* num_entries */,
  38. cl_platform_id * /* platforms */,
  39. cl_uint * /* num_platforms */) CL_API_SUFFIX__VERSION_1_0;
  40. extern
  41. CL_API_ENTRY cl_int CL_API_CALL
  42. (*clGetPlatformInfo)(cl_platform_id /* platform */,
  43. cl_platform_info /* param_name */,
  44. size_t /* param_value_size */,
  45. void * /* param_value */,
  46. size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0;
  47. /* Device APIs */
  48. extern
  49. CL_API_ENTRY cl_int CL_API_CALL
  50. (*clGetDeviceIDs)(cl_platform_id /* platform */,
  51. cl_device_type /* device_type */,
  52. cl_uint /* num_entries */,
  53. cl_device_id * /* devices */,
  54. cl_uint * /* num_devices */) CL_API_SUFFIX__VERSION_1_0;
  55. extern
  56. CL_API_ENTRY cl_int CL_API_CALL
  57. (*clGetDeviceInfo)(cl_device_id /* device */,
  58. cl_device_info /* param_name */,
  59. size_t /* param_value_size */,
  60. void * /* param_value */,
  61. size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0;
  62. /* Context APIs */
  63. extern
  64. CL_API_ENTRY cl_context CL_API_CALL
  65. (*clCreateContextFromType)(const cl_context_properties * /* properties */,
  66. cl_device_type /* device_type */,
  67. void (CL_CALLBACK * /* pfn_notify*/ )(const char *, const void *, size_t, void *),
  68. void * /* user_data */,
  69. cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0;
  70. extern
  71. CL_API_ENTRY cl_int CL_API_CALL
  72. (*clReleaseContext)(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0;
  73. /* Command Queue APIs */
  74. extern
  75. CL_API_ENTRY cl_command_queue CL_API_CALL
  76. (*clCreateCommandQueue)(cl_context /* context */,
  77. cl_device_id /* device */,
  78. cl_command_queue_properties /* properties */,
  79. cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0;
  80. extern
  81. CL_API_ENTRY cl_int CL_API_CALL
  82. (*clReleaseCommandQueue)(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0;
  83. /* Memory Object APIs */
  84. extern
  85. CL_API_ENTRY cl_mem CL_API_CALL
  86. (*clCreateBuffer)(cl_context /* context */,
  87. cl_mem_flags /* flags */,
  88. size_t /* size */,
  89. void * /* host_ptr */,
  90. cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0;
  91. /* Program Object APIs */
  92. extern
  93. CL_API_ENTRY cl_program CL_API_CALL
  94. (*clCreateProgramWithSource)(cl_context /* context */,
  95. cl_uint /* count */,
  96. const char ** /* strings */,
  97. const size_t * /* lengths */,
  98. cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0;
  99. extern
  100. CL_API_ENTRY cl_program CL_API_CALL
  101. (*clCreateProgramWithBinary)(cl_context /* context */,
  102. cl_uint /* num_devices */,
  103. const cl_device_id * /* device_list */,
  104. const size_t * /* lengths */,
  105. const unsigned char ** /* binaries */,
  106. cl_int * /* binary_status */,
  107. cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0;
  108. extern
  109. CL_API_ENTRY cl_int CL_API_CALL
  110. (*clReleaseProgram)(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0;
  111. extern
  112. CL_API_ENTRY cl_int CL_API_CALL
  113. (*clBuildProgram)(cl_program /* program */,
  114. cl_uint /* num_devices */,
  115. const cl_device_id * /* device_list */,
  116. const char * /* options */,
  117. void (CL_CALLBACK * /* pfn_notify */)(cl_program /* program */, void * /* user_data */),
  118. void * /* user_data */) CL_API_SUFFIX__VERSION_1_0;
  119. extern
  120. CL_API_ENTRY cl_int CL_API_CALL
  121. (*clGetProgramInfo)(cl_program /* program */,
  122. cl_program_info /* param_name */,
  123. size_t /* param_value_size */,
  124. void * /* param_value */,
  125. size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0;
  126. extern
  127. CL_API_ENTRY cl_int CL_API_CALL
  128. (*clGetProgramBuildInfo)(cl_program /* program */,
  129. cl_device_id /* device */,
  130. cl_program_build_info /* param_name */,
  131. size_t /* param_value_size */,
  132. void * /* param_value */,
  133. size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0;
  134. /* Kernel Object APIs */
  135. extern
  136. CL_API_ENTRY cl_kernel CL_API_CALL
  137. (*clCreateKernel)(cl_program /* program */,
  138. const char * /* kernel_name */,
  139. cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0;
  140. extern
  141. CL_API_ENTRY cl_int CL_API_CALL
  142. (*clReleaseKernel)(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0;
  143. extern
  144. CL_API_ENTRY cl_int CL_API_CALL
  145. (*clSetKernelArg)(cl_kernel /* kernel */,
  146. cl_uint /* arg_index */,
  147. size_t /* arg_size */,
  148. const void * /* arg_value */) CL_API_SUFFIX__VERSION_1_0;
  149. /* Flush and Finish APIs */
  150. extern
  151. CL_API_ENTRY cl_int CL_API_CALL
  152. (*clFinish)(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0;
  153. /* Enqueued Commands APIs */
  154. extern
  155. CL_API_ENTRY cl_int CL_API_CALL
  156. (*clEnqueueReadBuffer)(cl_command_queue /* command_queue */,
  157. cl_mem /* buffer */,
  158. cl_bool /* blocking_read */,
  159. size_t /* offset */,
  160. size_t /* size */,
  161. void * /* ptr */,
  162. cl_uint /* num_events_in_wait_list */,
  163. const cl_event * /* event_wait_list */,
  164. cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0;
  165. extern
  166. CL_API_ENTRY cl_int CL_API_CALL
  167. (*clEnqueueWriteBuffer)(cl_command_queue /* command_queue */,
  168. cl_mem /* buffer */,
  169. cl_bool /* blocking_write */,
  170. size_t /* offset */,
  171. size_t /* size */,
  172. const void * /* ptr */,
  173. cl_uint /* num_events_in_wait_list */,
  174. const cl_event * /* event_wait_list */,
  175. cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0;
  176. extern
  177. CL_API_ENTRY cl_int CL_API_CALL
  178. (*clEnqueueNDRangeKernel)(cl_command_queue /* command_queue */,
  179. cl_kernel /* kernel */,
  180. cl_uint /* work_dim */,
  181. const size_t * /* global_work_offset */,
  182. const size_t * /* global_work_size */,
  183. const size_t * /* local_work_size */,
  184. cl_uint /* num_events_in_wait_list */,
  185. const cl_event * /* event_wait_list */,
  186. cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0;
  187. int opt_platform_id = -1;
  188. FILE *opencl_open_kernel(const char * const filename)
  189. {
  190. char *fullpath = alloca(PATH_MAX);
  191. FILE *f;
  192. /* Try in the optional kernel path or installed prefix first */
  193. f = open_bitstream("opencl", filename);
  194. if (!f) {
  195. /* Then try from the path BFGMiner was called */
  196. strcpy(fullpath, cgminer_path);
  197. strcat(fullpath, filename);
  198. f = fopen(fullpath, "rb");
  199. }
  200. /* Finally try opening it directly */
  201. if (!f)
  202. f = fopen(filename, "rb");
  203. return f;
  204. }
  205. char *file_contents(const char *filename, int *length)
  206. {
  207. void *buffer;
  208. FILE *f;
  209. f = opencl_open_kernel(filename);
  210. if (!f) {
  211. applog(LOG_ERR, "Unable to open %s for reading", filename);
  212. return NULL;
  213. }
  214. fseek(f, 0, SEEK_END);
  215. *length = ftell(f);
  216. fseek(f, 0, SEEK_SET);
  217. buffer = malloc(*length+1);
  218. *length = fread(buffer, 1, *length, f);
  219. fclose(f);
  220. ((char*)buffer)[*length] = '\0';
  221. return (char*)buffer;
  222. }
  223. static
  224. void extract_word(char * const buf, const size_t bufsz, const char ** const endptr, const char *s)
  225. {
  226. const char *q;
  227. for ( ; s[0] && isspace(s[0]); ++s)
  228. if (s[0] == '\n' || s[0] == '\r')
  229. break;
  230. for (q = s; q[0] && !isspace(q[0]); ++q)
  231. {} // Find end of string
  232. size_t len = q - s;
  233. if (len >= bufsz)
  234. len = bufsz - 1;
  235. memcpy(buf, s, len);
  236. buf[len] = '\0';
  237. if (endptr)
  238. *endptr = q;
  239. }
  240. char *opencl_kernel_source(const char * const filename, int * const out_sourcelen, enum cl_kernels * const out_kinterface, struct mining_algorithm ** const out_malgo)
  241. {
  242. char *source = file_contents(filename, out_sourcelen);
  243. if (!source)
  244. return NULL;
  245. char *s = strstr(source, "kernel-interface:");
  246. if (s)
  247. {
  248. const char *q;
  249. char buf[0x20];
  250. extract_word(buf, sizeof(buf), &q, &s[17]);
  251. *out_kinterface = select_kernel(buf);
  252. if (out_malgo && (q[0] == '\t' || q[0] == ' '))
  253. {
  254. extract_word(buf, sizeof(buf), &q, q);
  255. *out_malgo = mining_algorithm_by_alias(buf);
  256. }
  257. }
  258. else
  259. *out_kinterface = KL_NONE;
  260. return source;
  261. }
  262. extern int opt_g_threads;
  263. int clDevicesNum(void) {
  264. cl_int status;
  265. char pbuff[256];
  266. cl_uint numDevices;
  267. cl_uint numPlatforms;
  268. int most_devices = -1;
  269. cl_platform_id *platforms;
  270. cl_platform_id platform = NULL;
  271. unsigned int i, mdplatform = 0;
  272. bool mdmesa = false;
  273. status = clGetPlatformIDs(0, NULL, &numPlatforms);
  274. /* If this fails, assume no GPUs. */
  275. if (status != CL_SUCCESS) {
  276. applog(LOG_ERR, "Error %d: clGetPlatformsIDs failed (no OpenCL SDK installed?)", status);
  277. return -1;
  278. }
  279. if (numPlatforms == 0) {
  280. applog(LOG_ERR, "clGetPlatformsIDs returned no platforms (no OpenCL SDK installed?)");
  281. return -1;
  282. }
  283. platforms = (cl_platform_id *)alloca(numPlatforms*sizeof(cl_platform_id));
  284. status = clGetPlatformIDs(numPlatforms, platforms, NULL);
  285. if (status != CL_SUCCESS) {
  286. applog(LOG_ERR, "Error %d: Getting Platform Ids. (clGetPlatformsIDs)", status);
  287. return -1;
  288. }
  289. for (i = 0; i < numPlatforms; i++) {
  290. if (opt_platform_id >= 0 && (int)i != opt_platform_id)
  291. continue;
  292. status = clGetPlatformInfo( platforms[i], CL_PLATFORM_VENDOR, sizeof(pbuff), pbuff, NULL);
  293. if (status != CL_SUCCESS) {
  294. applog(LOG_ERR, "Error %d: Getting Platform Info. (clGetPlatformInfo)", status);
  295. return -1;
  296. }
  297. platform = platforms[i];
  298. applog(LOG_INFO, "CL Platform %d vendor: %s", i, pbuff);
  299. status = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(pbuff), pbuff, NULL);
  300. if (status == CL_SUCCESS)
  301. applog(LOG_INFO, "CL Platform %d name: %s", i, pbuff);
  302. status = clGetPlatformInfo(platform, CL_PLATFORM_VERSION, sizeof(pbuff), pbuff, NULL);
  303. if (status == CL_SUCCESS)
  304. applog(LOG_INFO, "CL Platform %d version: %s", i, pbuff);
  305. status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 0, NULL, &numDevices);
  306. if (status != CL_SUCCESS) {
  307. applog(LOG_INFO, "Error %d: Getting Device IDs (num)", status);
  308. continue;
  309. }
  310. applog(LOG_INFO, "Platform %d devices: %d", i, numDevices);
  311. if ((int)numDevices > most_devices) {
  312. most_devices = numDevices;
  313. mdplatform = i;
  314. mdmesa = strstr(pbuff, "MESA");
  315. }
  316. if (numDevices) {
  317. unsigned int j;
  318. cl_device_id *devices = (cl_device_id *)malloc(numDevices*sizeof(cl_device_id));
  319. clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, numDevices, devices, NULL);
  320. for (j = 0; j < numDevices; j++) {
  321. clGetDeviceInfo(devices[j], CL_DEVICE_NAME, sizeof(pbuff), pbuff, NULL);
  322. applog(LOG_INFO, "\t%i\t%s", j, pbuff);
  323. }
  324. free(devices);
  325. }
  326. }
  327. if (opt_platform_id < 0)
  328. opt_platform_id = mdplatform;
  329. if (mdmesa && opt_g_threads == -1)
  330. opt_g_threads = 1;
  331. return most_devices;
  332. }
  333. cl_int bfg_clBuildProgram(cl_program * const program, const cl_device_id devid, const char * const CompilerOptions)
  334. {
  335. cl_int status;
  336. status = clBuildProgram(*program, 1, &devid, CompilerOptions, NULL, NULL);
  337. if (status != CL_SUCCESS)
  338. {
  339. applog(LOG_ERR, "Error %d: Building Program (clBuildProgram)", status);
  340. size_t logSize;
  341. status = clGetProgramBuildInfo(*program, devid, CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize);
  342. char *log = malloc(logSize ?: 1);
  343. status = clGetProgramBuildInfo(*program, devid, CL_PROGRAM_BUILD_LOG, logSize, log, NULL);
  344. if (logSize > 0 && log[0])
  345. applog(LOG_ERR, "%s", log);
  346. free(log);
  347. }
  348. return status;
  349. }
  350. static int advance(char **area, unsigned *remaining, const char *marker)
  351. {
  352. char *find = memmem(*area, *remaining, marker, strlen(marker));
  353. if (!find) {
  354. applog(LOG_DEBUG, "Marker \"%s\" not found", marker);
  355. return 0;
  356. }
  357. *remaining -= find - *area;
  358. *area = find;
  359. return 1;
  360. }
  361. #define OP3_INST_BFE_UINT 4ULL
  362. #define OP3_INST_BFE_INT 5ULL
  363. #define OP3_INST_BFI_INT 6ULL
  364. #define OP3_INST_BIT_ALIGN_INT 12ULL
  365. #define OP3_INST_BYTE_ALIGN_INT 13ULL
  366. void patch_opcodes(char *w, unsigned remaining)
  367. {
  368. uint64_t *opcode = (uint64_t *)w;
  369. int patched = 0;
  370. int count_bfe_int = 0;
  371. int count_bfe_uint = 0;
  372. int count_byte_align = 0;
  373. while (42) {
  374. int clamp = (*opcode >> (32 + 31)) & 0x1;
  375. int dest_rel = (*opcode >> (32 + 28)) & 0x1;
  376. int alu_inst = (*opcode >> (32 + 13)) & 0x1f;
  377. int s2_neg = (*opcode >> (32 + 12)) & 0x1;
  378. int s2_rel = (*opcode >> (32 + 9)) & 0x1;
  379. int pred_sel = (*opcode >> 29) & 0x3;
  380. if (!clamp && !dest_rel && !s2_neg && !s2_rel && !pred_sel) {
  381. if (alu_inst == OP3_INST_BFE_INT) {
  382. count_bfe_int++;
  383. } else if (alu_inst == OP3_INST_BFE_UINT) {
  384. count_bfe_uint++;
  385. } else if (alu_inst == OP3_INST_BYTE_ALIGN_INT) {
  386. count_byte_align++;
  387. // patch this instruction to BFI_INT
  388. *opcode &= 0xfffc1fffffffffffULL;
  389. *opcode |= OP3_INST_BFI_INT << (32 + 13);
  390. patched++;
  391. }
  392. }
  393. if (remaining <= 8)
  394. break;
  395. opcode++;
  396. remaining -= 8;
  397. }
  398. applog(LOG_DEBUG, "Potential OP3 instructions identified: "
  399. "%i BFE_INT, %i BFE_UINT, %i BYTE_ALIGN",
  400. count_bfe_int, count_bfe_uint, count_byte_align);
  401. applog(LOG_DEBUG, "Patched a total of %i BFI_INT instructions", patched);
  402. }
  403. _clState *opencl_create_clState(unsigned int gpu, char *name, size_t nameSize)
  404. {
  405. _clState *clState = calloc(1, sizeof(_clState));
  406. struct cgpu_info *cgpu = &gpus[gpu];
  407. struct opencl_device_data * const data = cgpu->device_data;
  408. cl_platform_id platform = NULL;
  409. char pbuff[256], vbuff[255];
  410. char *s;
  411. cl_platform_id* platforms;
  412. cl_device_id *devices;
  413. cl_uint numPlatforms;
  414. cl_uint numDevices;
  415. cl_int status;
  416. status = clGetPlatformIDs(0, NULL, &numPlatforms);
  417. if (status != CL_SUCCESS) {
  418. applog(LOG_ERR, "Error %d: Getting Platforms. (clGetPlatformsIDs)", status);
  419. err:
  420. free(clState);
  421. return NULL;
  422. }
  423. platforms = (cl_platform_id *)alloca(numPlatforms*sizeof(cl_platform_id));
  424. status = clGetPlatformIDs(numPlatforms, platforms, NULL);
  425. if (status != CL_SUCCESS) {
  426. applog(LOG_ERR, "Error %d: Getting Platform Ids. (clGetPlatformsIDs)", status);
  427. goto err;
  428. }
  429. if (opt_platform_id >= (int)numPlatforms) {
  430. applog(LOG_ERR, "Specified platform that does not exist");
  431. goto err;
  432. }
  433. status = clGetPlatformInfo(platforms[opt_platform_id], CL_PLATFORM_VENDOR, sizeof(pbuff), pbuff, NULL);
  434. if (status != CL_SUCCESS) {
  435. applog(LOG_ERR, "Error %d: Getting Platform Info. (clGetPlatformInfo)", status);
  436. goto err;
  437. }
  438. platform = platforms[opt_platform_id];
  439. if (platform == NULL) {
  440. perror("NULL platform found!\n");
  441. goto err;
  442. }
  443. applog(LOG_INFO, "CL Platform vendor: %s", pbuff);
  444. status = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(pbuff), pbuff, NULL);
  445. if (status == CL_SUCCESS)
  446. applog(LOG_INFO, "CL Platform name: %s", pbuff);
  447. status = clGetPlatformInfo(platform, CL_PLATFORM_VERSION, sizeof(vbuff), vbuff, NULL);
  448. if (status == CL_SUCCESS)
  449. applog(LOG_INFO, "CL Platform version: %s", vbuff);
  450. clState->platform_ver_str = strdup(vbuff);
  451. status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 0, NULL, &numDevices);
  452. if (status != CL_SUCCESS) {
  453. applog(LOG_ERR, "Error %d: Getting Device IDs (num)", status);
  454. goto err;
  455. }
  456. if (numDevices <= 0)
  457. goto err;
  458. {
  459. devices = (cl_device_id *)malloc(numDevices*sizeof(cl_device_id));
  460. /* Now, get the device list data */
  461. status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, numDevices, devices, NULL);
  462. if (status != CL_SUCCESS) {
  463. applog(LOG_ERR, "Error %d: Getting Device IDs (list)", status);
  464. err2:
  465. free(devices);
  466. goto err;
  467. }
  468. applog(LOG_INFO, "List of devices:");
  469. unsigned int i;
  470. for (i = 0; i < numDevices; i++) {
  471. status = clGetDeviceInfo(devices[i], CL_DEVICE_NAME, sizeof(pbuff), pbuff, NULL);
  472. if (status != CL_SUCCESS) {
  473. applog(LOG_ERR, "Error %d: Getting Device Info", status);
  474. goto err2;
  475. }
  476. applog(LOG_INFO, "\t%i\t%s", i, pbuff);
  477. }
  478. if (gpu < numDevices) {
  479. status = clGetDeviceInfo(devices[gpu], CL_DEVICE_NAME, sizeof(pbuff), pbuff, NULL);
  480. if (status != CL_SUCCESS) {
  481. applog(LOG_ERR, "Error %d: Getting Device Info", status);
  482. goto err2;
  483. }
  484. applog(LOG_INFO, "Selected %i: %s", gpu, pbuff);
  485. strncpy(name, pbuff, nameSize);
  486. } else {
  487. applog(LOG_ERR, "Invalid GPU %i", gpu);
  488. goto err2;
  489. }
  490. }
  491. cl_context_properties cps[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0 };
  492. clState->context = clCreateContextFromType(cps, CL_DEVICE_TYPE_GPU, NULL, NULL, &status);
  493. if (status != CL_SUCCESS) {
  494. applog(LOG_ERR, "Error %d: Creating Context. (clCreateContextFromType)", status);
  495. goto err2;
  496. }
  497. /////////////////////////////////////////////////////////////////
  498. // Create an OpenCL command queue
  499. /////////////////////////////////////////////////////////////////
  500. clState->commandQueue = clCreateCommandQueue(clState->context, devices[gpu],
  501. CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, &status);
  502. if (status != CL_SUCCESS) /* Try again without OOE enable */
  503. clState->commandQueue = clCreateCommandQueue(clState->context, devices[gpu], 0 , &status);
  504. if (status != CL_SUCCESS) {
  505. applog(LOG_ERR, "Error %d: Creating Command Queue. (clCreateCommandQueue)", status);
  506. goto err2;
  507. }
  508. /* Check for BFI INT support. Hopefully people don't mix devices with
  509. * and without it! */
  510. char * extensions = malloc(1024);
  511. const char * camo = "cl_amd_media_ops";
  512. char *find;
  513. status = clGetDeviceInfo(devices[gpu], CL_DEVICE_EXTENSIONS, 1024, (void *)extensions, NULL);
  514. if (status != CL_SUCCESS) {
  515. applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_EXTENSIONS", status);
  516. free(extensions);
  517. goto err2;
  518. }
  519. find = strstr(extensions, camo);
  520. if (find)
  521. clState->hasBitAlign = true;
  522. free(extensions);
  523. status = clGetDeviceInfo(devices[gpu], CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT, sizeof(cl_uint), (void *)&clState->preferred_vwidth, NULL);
  524. if (status != CL_SUCCESS) {
  525. applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT", status);
  526. goto err2;
  527. }
  528. applog(LOG_DEBUG, "Preferred vector width reported %d", clState->preferred_vwidth);
  529. status = clGetDeviceInfo(devices[gpu], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), (void *)&clState->max_work_size, NULL);
  530. if (status != CL_SUCCESS) {
  531. applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_MAX_WORK_GROUP_SIZE", status);
  532. goto err2;
  533. }
  534. applog(LOG_DEBUG, "Max work group size reported %"PRId64, (int64_t)clState->max_work_size);
  535. status = clGetDeviceInfo(devices[gpu], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(clState->max_compute_units), (void *)&clState->max_compute_units, NULL);
  536. if (status != CL_SUCCESS) {
  537. applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_MAX_COMPUTE_UNITS", status);
  538. goto err2;
  539. }
  540. if (data->_init_intensity)
  541. {
  542. data->oclthreads = 1; // Needed to ensure we don't just try to re-save the string (which would free before strduping and segfault anyway)
  543. opencl_set_intensity_from_str(cgpu, data->_init_intensity);
  544. }
  545. else
  546. {
  547. data->oclthreads = 1;
  548. data->intensity = INT_MIN;
  549. }
  550. applog(LOG_DEBUG, "Max compute units reported %u", (unsigned)clState->max_compute_units);
  551. status = clGetDeviceInfo(devices[gpu], CL_DEVICE_MAX_MEM_ALLOC_SIZE , sizeof(cl_ulong), (void *)&data->max_alloc, NULL);
  552. if (status != CL_SUCCESS) {
  553. applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_MAX_MEM_ALLOC_SIZE", status);
  554. goto err2;
  555. }
  556. applog(LOG_DEBUG, "Max mem alloc size is %lu", (unsigned long)data->max_alloc);
  557. find = strstr(vbuff, "MESA");
  558. if (find)
  559. {
  560. long int major = strtol(&find[4], &s, 10), minor = 0;
  561. if (!major)
  562. {} // No version number at all
  563. else
  564. if (s[0] == '.')
  565. minor = strtol(&s[1], NULL, 10);
  566. if (major < 10 || (major == 10 && minor < 1))
  567. {
  568. if (data->opt_opencl_binaries == OBU_DEFAULT)
  569. {
  570. applog(LOG_DEBUG, "Mesa OpenCL platform detected (v%ld.%ld), disabling OpenCL kernel binaries and bitalign", major, minor);
  571. data->opt_opencl_binaries = OBU_NONE;
  572. }
  573. else
  574. applog(LOG_DEBUG, "Mesa OpenCL platform detected (v%ld.%ld), disabling bitalign", major, minor);
  575. clState->hasBitAlign = false;
  576. }
  577. else
  578. applog(LOG_DEBUG, "Mesa OpenCL platform detected (v%ld.%ld)", major, minor);
  579. clState->is_mesa = true;
  580. }
  581. if (data->opt_opencl_binaries == OBU_DEFAULT)
  582. {
  583. #ifdef __APPLE__
  584. // Apple OpenCL doesn't like using binaries this way
  585. data->opt_opencl_binaries = OBU_NONE;
  586. #else
  587. data->opt_opencl_binaries = OBU_LOADSAVE;
  588. #endif
  589. }
  590. clState->devid = devices[gpu];
  591. free(devices);
  592. /* For some reason 2 vectors is still better even if the card says
  593. * otherwise, and many cards lie about their max so use 256 as max
  594. * unless explicitly set on the command line. Tahiti prefers 1 */
  595. if (strstr(name, "Tahiti"))
  596. clState->preferred_vwidth = 1;
  597. else
  598. if (clState->preferred_vwidth > 2)
  599. clState->preferred_vwidth = 2;
  600. if (data->vwidth)
  601. clState->vwidth = data->vwidth;
  602. else {
  603. clState->vwidth = clState->preferred_vwidth;
  604. data->vwidth = clState->preferred_vwidth;
  605. }
  606. clState->outputBuffer = clCreateBuffer(clState->context, 0, OPENCL_MAX_BUFFERSIZE, NULL, &status);
  607. if (status != CL_SUCCESS) {
  608. applog(LOG_ERR, "Error %d: clCreateBuffer (outputBuffer)", status);
  609. // NOTE: devices is freed here, but still assigned
  610. goto err;
  611. }
  612. return clState;
  613. }
  614. static
  615. bool opencl_test_goffset(_clState * const clState)
  616. {
  617. if (sizeof(size_t) < sizeof(uint32_t))
  618. return false;
  619. const char *source = "__kernel __attribute__((reqd_work_group_size(64, 1, 1))) void runtest(volatile __global uint *out) { *out = get_global_id(0); }";
  620. const size_t source_len = strlen(source);
  621. cl_int status;
  622. cl_program program = clCreateProgramWithSource(clState->context, 1, &source, &source_len, &status);
  623. if (status != CL_SUCCESS)
  624. applogr(false, LOG_ERR, "Error %d: Loading %s code into cl_program (clCreateProgramWithSource)", status, "goffset test");
  625. status = bfg_clBuildProgram(&program, clState->devid, "");
  626. if (status != CL_SUCCESS)
  627. {
  628. fail:
  629. clReleaseProgram(program);
  630. return false;
  631. }
  632. cl_kernel kernel = clCreateKernel(program, "runtest", &status);
  633. if (status != CL_SUCCESS)
  634. return_via_applog(fail, , LOG_ERR, "Error %d: Creating kernel from %s program (clCreateKernel)", status, "goffset test");
  635. static const uint32_t cleardata = 0;
  636. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0, sizeof(cleardata), &cleardata, 0, NULL, NULL);
  637. if (status != CL_SUCCESS)
  638. {
  639. applog(LOG_ERR, "Error %d: Clearing output buffer for %s kernel (clEnqueueWriteBuffer)", status, "goffset test");
  640. fail2:
  641. clReleaseKernel(kernel);
  642. goto fail;
  643. }
  644. status = clSetKernelArg(kernel, 0, sizeof(clState->outputBuffer), &clState->outputBuffer);
  645. if (status != CL_SUCCESS)
  646. return_via_applog(fail2, , LOG_ERR, "Error %d: Setting kernel argument for %s kernel (clSetKernelArg)", status, "goffset test");
  647. const size_t size_t_one = 1, test_goffset = 0xfabd0bf9;
  648. status = clEnqueueNDRangeKernel(clState->commandQueue, kernel, 1, &test_goffset, &size_t_one, &size_t_one, 0, NULL, NULL);
  649. if (status != CL_SUCCESS)
  650. return_via_applog(fail2, , LOG_DEBUG, "Error %d: Running %s kernel (clEnqueueNDRangeKernel)", status, "goffset test");
  651. uint32_t resultdata;
  652. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0, sizeof(resultdata), &resultdata, 0, NULL, NULL);
  653. if (status != CL_SUCCESS)
  654. return_via_applog(fail2, , LOG_DEBUG, "Error %d: Reading result from %s kernel (clEnqueueReadBuffer)", status, "goffset test");
  655. applog(LOG_DEBUG, "%s kernel returned 0x%08lx for goffset 0x%08lx", "goffset test", (unsigned long)resultdata, (unsigned long)test_goffset);
  656. return (resultdata == test_goffset);
  657. }
  658. bool opencl_load_kernel(struct cgpu_info * const cgpu, _clState * const clState, const char * const name, struct opencl_kernel_info * const kernelinfo, const char * const kernel_file, __maybe_unused const struct mining_algorithm * const malgo)
  659. {
  660. const int gpu = cgpu->device_id;
  661. #ifdef USE_SHA256D
  662. bool patchbfi = false;
  663. #endif
  664. bool prog_built = false;
  665. struct opencl_device_data * const data = cgpu->device_data;
  666. const char * const vbuff = clState->platform_ver_str;
  667. char *s;
  668. cl_int status;
  669. /* Create binary filename based on parameters passed to opencl
  670. * compiler to ensure we only load a binary that matches what would
  671. * have otherwise created. The filename is:
  672. * kernelname + name +/- g(offset) + v + vectors + w + work_size + l + sizeof(long) + p + platform version + .bin
  673. * For scrypt the filename is:
  674. * kernelname + name + g + lg + lookup_gap + tc + thread_concurrency + w + work_size + l + sizeof(long) + p + platform version + .bin
  675. */
  676. char binaryfilename[255];
  677. char filename[255];
  678. char numbuf[32];
  679. snprintf(filename, sizeof(filename), "%s.cl", kernel_file);
  680. snprintf(binaryfilename, sizeof(filename), "%s", kernel_file);
  681. int pl;
  682. char *source = opencl_kernel_source(filename, &pl, &kernelinfo->interface, NULL);
  683. if (!source)
  684. return false;
  685. {
  686. uint8_t hash[0x20];
  687. char hashhex[7];
  688. sha256((void*)source, pl, hash);
  689. bin2hex(hashhex, hash, 3);
  690. tailsprintf(binaryfilename, sizeof(binaryfilename), "-%s", hashhex);
  691. }
  692. switch (kernelinfo->interface)
  693. {
  694. case KL_NONE:
  695. applog(LOG_ERR, "%s: Failed to identify kernel interface for %s",
  696. cgpu->dev_repr, kernel_file);
  697. free(source);
  698. return false;
  699. #ifdef USE_SHA256D
  700. case KL_PHATK:
  701. if ((strstr(vbuff, "844.4") || strstr(vbuff, "851.4") ||
  702. strstr(vbuff, "831.4") || strstr(vbuff, "898.1") ||
  703. strstr(vbuff, "923.1") || strstr(vbuff, "938.2") ||
  704. strstr(vbuff, "1113.2"))) {
  705. applog(LOG_WARNING, "WARNING: You have selected the phatk kernel.");
  706. applog(LOG_WARNING, "You are running SDK 2.6+ which performs poorly with this kernel.");
  707. applog(LOG_WARNING, "Downgrade your SDK and delete any .bin files before starting again.");
  708. applog(LOG_WARNING, "Or allow BFGMiner to automatically choose a more suitable kernel.");
  709. }
  710. #endif
  711. default:
  712. ;
  713. }
  714. applog(LOG_DEBUG, "%s: Using kernel %s with interface %s",
  715. cgpu->dev_repr, kernel_file,
  716. opencl_get_kernel_interface_name(kernelinfo->interface));
  717. {
  718. int kernel_goffset_support = 0; // 0 = none; 1 = optional; 2 = required
  719. if (strstr(source, "def GOFFSET"))
  720. kernel_goffset_support = 1;
  721. else
  722. if (strstr(source, " base,"))
  723. kernel_goffset_support = 2;
  724. else
  725. kernel_goffset_support = 0;
  726. bool device_goffset_support = false;
  727. switch (data->use_goffset)
  728. {
  729. case BTS_TRUE:
  730. device_goffset_support = true;
  731. break;
  732. case BTS_FALSE:
  733. // if the kernel doesn't require goffset, allow the user to disable it
  734. if (kernel_goffset_support != 2)
  735. break;
  736. // fallthru
  737. case BTS_UNKNOWN:
  738. if (opencl_test_goffset(clState))
  739. device_goffset_support = true;
  740. break;
  741. }
  742. applog(LOG_DEBUG, "%s: goffset support: device=%s kernel=%s", cgpu->dev_repr, device_goffset_support ? "yes" : "no", (kernel_goffset_support == 2) ? "required" : ((kernel_goffset_support == 1) ? "optional" : "none"));
  743. if (device_goffset_support)
  744. {
  745. if (kernel_goffset_support)
  746. kernelinfo->goffset = true;
  747. }
  748. else
  749. if (kernel_goffset_support == 2)
  750. {
  751. // FIXME: Determine this before min_nonce_diff returns positive
  752. applog(LOG_ERR, "%s: Need goffset support!", cgpu->dev_repr);
  753. return false;
  754. }
  755. }
  756. if (data->work_size && data->work_size <= clState->max_work_size)
  757. kernelinfo->wsize = data->work_size;
  758. else
  759. #ifdef USE_SCRYPT
  760. if (malgo->algo == POW_SCRYPT)
  761. kernelinfo->wsize = 256;
  762. else
  763. #endif
  764. if (strstr(name, "Tahiti"))
  765. kernelinfo->wsize = 64;
  766. else
  767. kernelinfo->wsize = (clState->max_work_size <= 256 ? clState->max_work_size : 256) / clState->vwidth;
  768. #ifdef USE_SCRYPT
  769. if (kernelinfo->interface == KL_SCRYPT)
  770. {
  771. if (!data->thread_concurrency)
  772. {
  773. unsigned int sixtyfours;
  774. sixtyfours = data->max_alloc / 131072 / 64 - 1;
  775. data->thread_concurrency = sixtyfours * 64;
  776. if (data->shaders && data->thread_concurrency > data->shaders) {
  777. data->thread_concurrency -= data->thread_concurrency % data->shaders;
  778. if (data->thread_concurrency > data->shaders * 5)
  779. data->thread_concurrency = data->shaders * 5;
  780. }
  781. applog(LOG_DEBUG, "GPU %u: selecting thread concurrency of %lu", gpu, (unsigned long)data->thread_concurrency);
  782. }
  783. }
  784. #endif
  785. FILE *binaryfile;
  786. size_t *binary_sizes;
  787. char **binaries;
  788. size_t sourceSize[] = {(size_t)pl};
  789. cl_uint slot, cpnd;
  790. slot = cpnd = 0;
  791. binary_sizes = calloc(sizeof(size_t) * MAX_GPUDEVICES * 4, 1);
  792. if (unlikely(!binary_sizes)) {
  793. applog(LOG_ERR, "Unable to calloc binary_sizes");
  794. return false;
  795. }
  796. binaries = calloc(sizeof(char *) * MAX_GPUDEVICES * 4, 1);
  797. if (unlikely(!binaries)) {
  798. applog(LOG_ERR, "Unable to calloc binaries");
  799. return false;
  800. }
  801. strcat(binaryfilename, name);
  802. if (kernelinfo->goffset)
  803. strcat(binaryfilename, "g");
  804. #ifdef USE_SCRYPT
  805. if (kernelinfo->interface == KL_SCRYPT)
  806. {
  807. sprintf(numbuf, "lg%utc%u", data->lookup_gap, (unsigned int)data->thread_concurrency);
  808. strcat(binaryfilename, numbuf);
  809. }
  810. else
  811. #endif
  812. {
  813. sprintf(numbuf, "v%d", clState->vwidth);
  814. strcat(binaryfilename, numbuf);
  815. }
  816. sprintf(numbuf, "w%d", (int)kernelinfo->wsize);
  817. strcat(binaryfilename, numbuf);
  818. sprintf(numbuf, "l%d", (int)sizeof(long));
  819. strcat(binaryfilename, numbuf);
  820. strcat(binaryfilename, "p");
  821. strcat(binaryfilename, vbuff);
  822. sanestr(binaryfilename, binaryfilename);
  823. applog(LOG_DEBUG, "OCL%2u: Configured OpenCL kernel name: %s", gpu, binaryfilename);
  824. strcat(binaryfilename, ".bin");
  825. if (!(data->opt_opencl_binaries & OBU_LOAD))
  826. goto build;
  827. binaryfile = fopen(binaryfilename, "rb");
  828. if (!binaryfile) {
  829. applog(LOG_DEBUG, "No binary found, generating from source");
  830. } else {
  831. struct stat binary_stat;
  832. if (unlikely(stat(binaryfilename, &binary_stat))) {
  833. applog(LOG_DEBUG, "Unable to stat binary, generating from source");
  834. fclose(binaryfile);
  835. goto build;
  836. }
  837. if (!binary_stat.st_size)
  838. goto build;
  839. binary_sizes[slot] = binary_stat.st_size;
  840. binaries[slot] = (char *)calloc(binary_sizes[slot], 1);
  841. if (unlikely(!binaries[slot])) {
  842. applog(LOG_ERR, "Unable to calloc binaries");
  843. fclose(binaryfile);
  844. return false;
  845. }
  846. if (fread(binaries[slot], 1, binary_sizes[slot], binaryfile) != binary_sizes[slot]) {
  847. applog(LOG_ERR, "Unable to fread binaries");
  848. fclose(binaryfile);
  849. free(binaries[slot]);
  850. goto build;
  851. }
  852. kernelinfo->program = clCreateProgramWithBinary(clState->context, 1, &clState->devid, &binary_sizes[slot], (const unsigned char **)binaries, &status, NULL);
  853. if (status != CL_SUCCESS) {
  854. applog(LOG_ERR, "Error %d: Loading Binary into cl_program (clCreateProgramWithBinary)", status);
  855. fclose(binaryfile);
  856. free(binaries[slot]);
  857. goto build;
  858. }
  859. fclose(binaryfile);
  860. applog(LOG_DEBUG, "Loaded binary image %s", binaryfilename);
  861. goto built;
  862. }
  863. /////////////////////////////////////////////////////////////////
  864. // Load CL file, build CL program object, create CL kernel object
  865. /////////////////////////////////////////////////////////////////
  866. build:
  867. kernelinfo->program = clCreateProgramWithSource(clState->context, 1, (const char **)&source, sourceSize, &status);
  868. if (status != CL_SUCCESS) {
  869. applog(LOG_ERR, "Error %d: Loading Binary into cl_program (clCreateProgramWithSource)", status);
  870. return false;
  871. }
  872. /* create a cl program executable for all the devices specified */
  873. char *CompilerOptions = calloc(1, 256);
  874. #ifdef USE_SCRYPT
  875. if (kernelinfo->interface == KL_SCRYPT)
  876. sprintf(CompilerOptions, "-D LOOKUP_GAP=%d -D CONCURRENT_THREADS=%d -D WORKSIZE=%d",
  877. data->lookup_gap, (unsigned int)data->thread_concurrency, (int)kernelinfo->wsize);
  878. else
  879. #endif
  880. {
  881. sprintf(CompilerOptions, "-D WORKSIZE=%d -D VECTORS%d -D WORKVEC=%d",
  882. (int)kernelinfo->wsize, clState->vwidth, (int)kernelinfo->wsize * clState->vwidth);
  883. }
  884. applog(LOG_DEBUG, "Setting worksize to %"PRId64, (int64_t)kernelinfo->wsize);
  885. if (clState->vwidth > 1)
  886. applog(LOG_DEBUG, "Patched source to suit %d vectors", clState->vwidth);
  887. if (clState->hasBitAlign) {
  888. strcat(CompilerOptions, " -D BITALIGN");
  889. applog(LOG_DEBUG, "cl_amd_media_ops found, setting BITALIGN");
  890. #ifdef USE_SHA256D
  891. if (strstr(name, "Cedar") ||
  892. strstr(name, "Redwood") ||
  893. strstr(name, "Juniper") ||
  894. strstr(name, "Cypress" ) ||
  895. strstr(name, "Hemlock" ) ||
  896. strstr(name, "Caicos" ) ||
  897. strstr(name, "Turks" ) ||
  898. strstr(name, "Barts" ) ||
  899. strstr(name, "Cayman" ) ||
  900. strstr(name, "Antilles" ) ||
  901. strstr(name, "Wrestler" ) ||
  902. strstr(name, "Zacate" ) ||
  903. strstr(name, "WinterPark" ))
  904. {
  905. // BFI_INT patching only works with AMD-APP up to 1084
  906. if (strstr(vbuff, "ATI-Stream"))
  907. patchbfi = true;
  908. else
  909. if ((s = strstr(vbuff, "AMD-APP")) && (s = strchr(s, '(')) && atoi(&s[1]) < 1085)
  910. patchbfi = true;
  911. }
  912. #endif
  913. } else
  914. applog(LOG_DEBUG, "cl_amd_media_ops not found, will not set BITALIGN");
  915. #ifdef USE_SHA256D
  916. switch (kernelinfo->interface)
  917. {
  918. case KL_DIABLO: case KL_DIAKGCN: case KL_PHATK: case KL_POCLBM:
  919. // Okay, these actually use BFI_INT hacking
  920. break;
  921. default:
  922. // Anything else has never needed it
  923. patchbfi = false;
  924. break;
  925. }
  926. if (patchbfi) {
  927. if (data->opt_opencl_binaries == OBU_LOADSAVE)
  928. {
  929. strcat(CompilerOptions, " -D BFI_INT");
  930. applog(LOG_DEBUG, "BFI_INT patch requiring device found, patched source with BFI_INT");
  931. }
  932. else
  933. {
  934. patchbfi = false;
  935. applog(LOG_WARNING, "BFI_INT patch requiring device found, but OpenCL binary usage disabled; cannot BFI_INT patch");
  936. }
  937. } else
  938. applog(LOG_DEBUG, "BFI_INT patch requiring device not found, will not BFI_INT patch");
  939. #endif
  940. if (kernelinfo->goffset)
  941. strcat(CompilerOptions, " -D GOFFSET");
  942. applog(LOG_DEBUG, "CompilerOptions: %s", CompilerOptions);
  943. status = bfg_clBuildProgram(&kernelinfo->program, clState->devid, CompilerOptions);
  944. free(CompilerOptions);
  945. if (status != CL_SUCCESS)
  946. return false;
  947. prog_built = true;
  948. if (!(data->opt_opencl_binaries & OBU_SAVE))
  949. goto built;
  950. status = clGetProgramInfo(kernelinfo->program, CL_PROGRAM_NUM_DEVICES, sizeof(cl_uint), &cpnd, NULL);
  951. if (unlikely(status != CL_SUCCESS)) {
  952. applog(LOG_ERR, "Error %d: Getting program info CL_PROGRAM_NUM_DEVICES. (clGetProgramInfo)", status);
  953. return false;
  954. }
  955. status = clGetProgramInfo(kernelinfo->program, CL_PROGRAM_BINARY_SIZES, sizeof(size_t)*cpnd, binary_sizes, NULL);
  956. if (unlikely(status != CL_SUCCESS)) {
  957. applog(LOG_ERR, "Error %d: Getting program info CL_PROGRAM_BINARY_SIZES. (clGetProgramInfo)", status);
  958. return false;
  959. }
  960. /* The actual compiled binary ends up in a RANDOM slot! Grr, so we have
  961. * to iterate over all the binary slots and find where the real program
  962. * is. What the heck is this!? */
  963. for (slot = 0; slot < cpnd; slot++)
  964. if (binary_sizes[slot])
  965. break;
  966. /* copy over all of the generated binaries. */
  967. applog(LOG_DEBUG, "Binary size for gpu %u found in binary slot %u: %"PRId64,
  968. gpu, (unsigned)slot, (int64_t)binary_sizes[slot]);
  969. if (!binary_sizes[slot]) {
  970. applog(LOG_ERR, "OpenCL compiler generated a zero sized binary, FAIL!");
  971. return false;
  972. }
  973. binaries[slot] = calloc(sizeof(char) * binary_sizes[slot], 1);
  974. status = clGetProgramInfo(kernelinfo->program, CL_PROGRAM_BINARIES, sizeof(char *) * cpnd, binaries, NULL );
  975. if (unlikely(status != CL_SUCCESS)) {
  976. applog(LOG_ERR, "Error %d: Getting program info. CL_PROGRAM_BINARIES (clGetProgramInfo)", status);
  977. return false;
  978. }
  979. #ifdef USE_SHA256D
  980. /* Patch the kernel if the hardware supports BFI_INT but it needs to
  981. * be hacked in */
  982. if (patchbfi) {
  983. unsigned remaining = binary_sizes[slot];
  984. char *w = binaries[slot];
  985. unsigned int start, length;
  986. /* Find 2nd incidence of .text, and copy the program's
  987. * position and length at a fixed offset from that. Then go
  988. * back and find the 2nd incidence of \x7ELF (rewind by one
  989. * from ELF) and then patch the opcocdes */
  990. if (!advance(&w, &remaining, ".text"))
  991. goto build;
  992. w++; remaining--;
  993. if (!advance(&w, &remaining, ".text")) {
  994. /* 32 bit builds only one ELF */
  995. w--; remaining++;
  996. }
  997. memcpy(&start, w + 285, 4);
  998. memcpy(&length, w + 289, 4);
  999. w = binaries[slot]; remaining = binary_sizes[slot];
  1000. if (!advance(&w, &remaining, "ELF"))
  1001. goto build;
  1002. w++; remaining--;
  1003. if (!advance(&w, &remaining, "ELF")) {
  1004. /* 32 bit builds only one ELF */
  1005. w--; remaining++;
  1006. }
  1007. w--; remaining++;
  1008. w += start; remaining -= start;
  1009. applog(LOG_DEBUG, "At %p (%u rem. bytes), to begin patching",
  1010. w, remaining);
  1011. patch_opcodes(w, length);
  1012. status = clReleaseProgram(kernelinfo->program);
  1013. if (status != CL_SUCCESS) {
  1014. applog(LOG_ERR, "Error %d: Releasing program. (clReleaseProgram)", status);
  1015. return false;
  1016. }
  1017. kernelinfo->program = clCreateProgramWithBinary(clState->context, 1, &clState->devid, &binary_sizes[slot], (const unsigned char **)&binaries[slot], &status, NULL);
  1018. if (status != CL_SUCCESS) {
  1019. applog(LOG_ERR, "Error %d: Loading Binary into cl_program (clCreateProgramWithBinary)", status);
  1020. return false;
  1021. }
  1022. /* Program needs to be rebuilt */
  1023. prog_built = false;
  1024. }
  1025. #endif
  1026. free(source);
  1027. /* Save the binary to be loaded next time */
  1028. binaryfile = fopen(binaryfilename, "wb");
  1029. if (!binaryfile) {
  1030. /* Not a fatal problem, just means we build it again next time */
  1031. applog(LOG_DEBUG, "Unable to create file %s", binaryfilename);
  1032. } else {
  1033. if (unlikely(fwrite(binaries[slot], 1, binary_sizes[slot], binaryfile) != binary_sizes[slot])) {
  1034. applog(LOG_ERR, "Unable to fwrite to binaryfile");
  1035. return false;
  1036. }
  1037. fclose(binaryfile);
  1038. }
  1039. built:
  1040. if (binaries[slot])
  1041. free(binaries[slot]);
  1042. free(binaries);
  1043. free(binary_sizes);
  1044. applog(LOG_INFO, "Initialising kernel %s with%s bitalign, %"PRId64" vectors and worksize %"PRIu64,
  1045. filename, clState->hasBitAlign ? "" : "out", (int64_t)clState->vwidth, (uint64_t)kernelinfo->wsize);
  1046. if (!prog_built) {
  1047. /* create a cl program executable for all the devices specified */
  1048. status = bfg_clBuildProgram(&kernelinfo->program, clState->devid, NULL);
  1049. if (status != CL_SUCCESS)
  1050. return false;
  1051. }
  1052. /* get a kernel object handle for a kernel with the given name */
  1053. kernelinfo->kernel = clCreateKernel(kernelinfo->program, "search", &status);
  1054. if (status != CL_SUCCESS) {
  1055. applog(LOG_ERR, "Error %d: Creating Kernel from program. (clCreateKernel)", status);
  1056. return false;
  1057. }
  1058. free((void*)cgpu->kname);
  1059. cgpu->kname = strdup(kernel_file);
  1060. #ifdef MAX_CLBUFFER0_SZ
  1061. switch (kernelinfo->interface)
  1062. {
  1063. #ifdef USE_SCRYPT
  1064. case KL_SCRYPT:
  1065. if (!clState->padbufsize)
  1066. {
  1067. size_t ipt = (1024 / data->lookup_gap + (1024 % data->lookup_gap > 0));
  1068. size_t bufsize = 128 * ipt * data->thread_concurrency;
  1069. /* Use the max alloc value which has been rounded to a power of
  1070. * 2 greater >= required amount earlier */
  1071. if (bufsize > data->max_alloc) {
  1072. applog(LOG_WARNING, "Maximum buffer memory device %d supports says %lu", gpu, (unsigned long)data->max_alloc);
  1073. applog(LOG_WARNING, "Your scrypt settings come to %lu", (unsigned long)bufsize);
  1074. }
  1075. applog(LOG_DEBUG, "Creating scrypt buffer sized %lu", (unsigned long)bufsize);
  1076. clState->padbufsize = bufsize;
  1077. /* This buffer is weird and might work to some degree even if
  1078. * the create buffer call has apparently failed, so check if we
  1079. * get anything back before we call it a failure. */
  1080. clState->padbuffer8 = NULL;
  1081. clState->padbuffer8 = clCreateBuffer(clState->context, CL_MEM_READ_WRITE, bufsize, NULL, &status);
  1082. if (status != CL_SUCCESS && !clState->padbuffer8) {
  1083. applog(LOG_ERR, "Error %d: clCreateBuffer (padbuffer8), decrease TC or increase LG", status);
  1084. return false;
  1085. }
  1086. }
  1087. // NOTE: fallthru
  1088. #endif
  1089. #ifdef USE_OPENCL_FULLHEADER
  1090. case KL_FULLHEADER:
  1091. #endif
  1092. if (!clState->CLbuffer0)
  1093. {
  1094. clState->CLbuffer0 = clCreateBuffer(clState->context, CL_MEM_READ_ONLY, MAX_CLBUFFER0_SZ, NULL, &status);
  1095. if (status != CL_SUCCESS) {
  1096. applog(LOG_ERR, "Error %d: clCreateBuffer (CLbuffer0)", status);
  1097. return false;
  1098. }
  1099. }
  1100. break;
  1101. default:
  1102. break;
  1103. }
  1104. #endif
  1105. kernelinfo->loaded = true;
  1106. return true;
  1107. }