ocl.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  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_load_kernel_binary(struct cgpu_info * const cgpu, _clState * const clState, struct opencl_kernel_info * const kernelinfo, const char * const binaryfilename, bytes_t * const b)
  616. {
  617. cl_int status;
  618. FILE * const binaryfile = fopen(binaryfilename, "rb");
  619. if (!binaryfile)
  620. return false;
  621. struct stat binary_stat;
  622. if (unlikely(stat(binaryfilename, &binary_stat)))
  623. {
  624. applog(LOG_DEBUG, "Unable to stat binary, generating from source");
  625. fclose(binaryfile);
  626. return false;
  627. }
  628. if (!binary_stat.st_size)
  629. {
  630. fclose(binaryfile);
  631. return false;
  632. }
  633. const size_t binsz = binary_stat.st_size;
  634. bytes_resize(b, binsz);
  635. if (fread(bytes_buf(b), 1, binsz, binaryfile) != binsz)
  636. {
  637. applog(LOG_ERR, "Unable to fread binaries");
  638. fclose(binaryfile);
  639. return false;
  640. }
  641. fclose(binaryfile);
  642. kernelinfo->program = clCreateProgramWithBinary(clState->context, 1, &clState->devid, &binsz, (void*)&bytes_buf(b), &status, NULL);
  643. if (status != CL_SUCCESS)
  644. applogr(false, LOG_ERR, "Error %d: Loading Binary into cl_program (clCreateProgramWithBinary)", status);
  645. status = bfg_clBuildProgram(&kernelinfo->program, clState->devid, NULL);
  646. if (status != CL_SUCCESS)
  647. return false;
  648. applog(LOG_DEBUG, "Loaded binary image %s", binaryfilename);
  649. return true;
  650. }
  651. static
  652. bool opencl_should_patch_bfi_int(struct cgpu_info * const cgpu, _clState * const clState, struct opencl_kernel_info * const kernelinfo)
  653. {
  654. #ifdef USE_SHA256D
  655. struct opencl_device_data * const data = cgpu->device_data;
  656. const char * const name = cgpu->name;
  657. const char * const vbuff = clState->platform_ver_str;
  658. char *s;
  659. if (!clState->hasBitAlign)
  660. return false;
  661. if (!(strstr(name, "Cedar") ||
  662. strstr(name, "Redwood") ||
  663. strstr(name, "Juniper") ||
  664. strstr(name, "Cypress" ) ||
  665. strstr(name, "Hemlock" ) ||
  666. strstr(name, "Caicos" ) ||
  667. strstr(name, "Turks" ) ||
  668. strstr(name, "Barts" ) ||
  669. strstr(name, "Cayman" ) ||
  670. strstr(name, "Antilles" ) ||
  671. strstr(name, "Wrestler" ) ||
  672. strstr(name, "Zacate" ) ||
  673. strstr(name, "WinterPark" )))
  674. return false;
  675. // BFI_INT patching only works with AMD-APP up to 1084
  676. if (strstr(vbuff, "ATI-Stream"))
  677. {}
  678. else
  679. if ((s = strstr(vbuff, "AMD-APP")) && (s = strchr(s, '(')) && atoi(&s[1]) < 1085)
  680. {}
  681. else
  682. return false;
  683. switch (kernelinfo->interface)
  684. {
  685. case KL_DIABLO: case KL_DIAKGCN: case KL_PHATK: case KL_POCLBM:
  686. // Okay, these actually use BFI_INT hacking
  687. break;
  688. default:
  689. // Anything else has never needed it
  690. return false;
  691. break;
  692. }
  693. if (data->opt_opencl_binaries != OBU_LOADSAVE)
  694. applogr(false, LOG_WARNING, "BFI_INT patch requiring device found, but OpenCL binary usage disabled; cannot BFI_INT patch");
  695. applog(LOG_DEBUG, "BFI_INT patch requiring device found, will patch source with BFI_INT");
  696. return true;
  697. #else
  698. return false;
  699. #endif
  700. }
  701. static
  702. bool opencl_build_kernel(struct cgpu_info * const cgpu, _clState * const clState, struct opencl_kernel_info * const kernelinfo, const char *source, const size_t source_len, const bool patchbfi)
  703. {
  704. struct opencl_device_data * const data = cgpu->device_data;
  705. cl_int status;
  706. kernelinfo->program = clCreateProgramWithSource(clState->context, 1, &source, &source_len, &status);
  707. if (status != CL_SUCCESS)
  708. applogr(false, LOG_ERR, "Error %d: Loading Binary into cl_program (clCreateProgramWithSource)", status);
  709. /* create a cl program executable for all the devices specified */
  710. char *CompilerOptions = calloc(1, 256);
  711. #ifdef USE_SCRYPT
  712. if (kernelinfo->interface == KL_SCRYPT)
  713. sprintf(CompilerOptions, "-D LOOKUP_GAP=%d -D CONCURRENT_THREADS=%d -D WORKSIZE=%d",
  714. data->lookup_gap, (unsigned int)data->thread_concurrency, (int)kernelinfo->wsize);
  715. else
  716. #endif
  717. {
  718. sprintf(CompilerOptions, "-D WORKSIZE=%d -D VECTORS%d -D WORKVEC=%d",
  719. (int)kernelinfo->wsize, clState->vwidth, (int)kernelinfo->wsize * clState->vwidth);
  720. }
  721. applog(LOG_DEBUG, "Setting worksize to %"PRId64, (int64_t)kernelinfo->wsize);
  722. if (clState->vwidth > 1)
  723. applog(LOG_DEBUG, "Patched source to suit %d vectors", clState->vwidth);
  724. if (clState->hasBitAlign)
  725. {
  726. strcat(CompilerOptions, " -D BITALIGN");
  727. applog(LOG_DEBUG, "cl_amd_media_ops found, setting BITALIGN");
  728. }
  729. else
  730. applog(LOG_DEBUG, "cl_amd_media_ops not found, will not set BITALIGN");
  731. #ifdef USE_SHA256D
  732. if (patchbfi)
  733. strcat(CompilerOptions, " -D BFI_INT");
  734. #endif
  735. if (kernelinfo->goffset)
  736. strcat(CompilerOptions, " -D GOFFSET");
  737. applog(LOG_DEBUG, "CompilerOptions: %s", CompilerOptions);
  738. status = bfg_clBuildProgram(&kernelinfo->program, clState->devid, CompilerOptions);
  739. free(CompilerOptions);
  740. if (status != CL_SUCCESS)
  741. return false;
  742. return true;
  743. }
  744. static
  745. bool opencl_get_kernel_binary(struct cgpu_info * const cgpu, _clState * const clState, struct opencl_kernel_info * const kernelinfo, bytes_t * const b)
  746. {
  747. cl_int status;
  748. cl_uint slot, cpnd;
  749. status = clGetProgramInfo(kernelinfo->program, CL_PROGRAM_NUM_DEVICES, sizeof(cl_uint), &cpnd, NULL);
  750. if (unlikely(status != CL_SUCCESS))
  751. applogr(false, LOG_ERR, "Error %d: Getting program info CL_PROGRAM_NUM_DEVICES. (clGetProgramInfo)", status);
  752. size_t binary_sizes[cpnd];
  753. status = clGetProgramInfo(kernelinfo->program, CL_PROGRAM_BINARY_SIZES, sizeof(binary_sizes), binary_sizes, NULL);
  754. if (unlikely(status != CL_SUCCESS))
  755. applogr(false, LOG_ERR, "Error %d: Getting program info CL_PROGRAM_BINARY_SIZES. (clGetProgramInfo)", status);
  756. uint8_t **binaries = malloc(sizeof(*binaries) * cpnd);
  757. for (slot = 0; slot < cpnd; ++slot)
  758. binaries[slot] = malloc(binary_sizes[slot] + 1);
  759. /* The actual compiled binary ends up in a RANDOM slot! Grr, so we have
  760. * to iterate over all the binary slots and find where the real program
  761. * is. What the heck is this!? */
  762. for (slot = 0; slot < cpnd; slot++)
  763. if (binary_sizes[slot])
  764. break;
  765. /* copy over all of the generated binaries. */
  766. applog(LOG_DEBUG, "%s: Binary size found in binary slot %u: %"PRId64, cgpu->dev_repr, (unsigned)slot, (int64_t)binary_sizes[slot]);
  767. if (!binary_sizes[slot])
  768. applogr(false, LOG_ERR, "OpenCL compiler generated a zero sized binary, FAIL!");
  769. status = clGetProgramInfo(kernelinfo->program, CL_PROGRAM_BINARIES, sizeof(binaries), binaries, NULL);
  770. if (unlikely(status != CL_SUCCESS))
  771. applogr(false, LOG_ERR, "Error %d: Getting program info. CL_PROGRAM_BINARIES (clGetProgramInfo)", status);
  772. bytes_resize(b, binary_sizes[slot]);
  773. memcpy(bytes_buf(b), binaries[slot], bytes_len(b));
  774. for (slot = 0; slot < cpnd; ++slot)
  775. free(binaries[slot]);
  776. free(binaries);
  777. return true;
  778. }
  779. #ifdef USE_SHA256D
  780. /* Patch the kernel if the hardware supports BFI_INT but it needs to
  781. * be hacked in */
  782. static
  783. bool opencl_patch_kernel_binary(bytes_t * const b)
  784. {
  785. unsigned remaining = bytes_len(b);
  786. char *w = (void*)bytes_buf(b);
  787. unsigned int start, length;
  788. /* Find 2nd incidence of .text, and copy the program's
  789. * position and length at a fixed offset from that. Then go
  790. * back and find the 2nd incidence of \x7ELF (rewind by one
  791. * from ELF) and then patch the opcocdes */
  792. if (!advance(&w, &remaining, ".text"))
  793. return false;
  794. w++; remaining--;
  795. if (!advance(&w, &remaining, ".text")) {
  796. /* 32 bit builds only one ELF */
  797. w--; remaining++;
  798. }
  799. memcpy(&start, w + 285, 4);
  800. memcpy(&length, w + 289, 4);
  801. w = (void*)bytes_buf(b);
  802. remaining = bytes_len(b);
  803. if (!advance(&w, &remaining, "ELF"))
  804. return false;
  805. w++; remaining--;
  806. if (!advance(&w, &remaining, "ELF")) {
  807. /* 32 bit builds only one ELF */
  808. w--; remaining++;
  809. }
  810. w--; remaining++;
  811. w += start; remaining -= start;
  812. applog(LOG_DEBUG, "At %p (%u rem. bytes), to begin patching", w, remaining);
  813. patch_opcodes(w, length);
  814. return true;
  815. }
  816. static
  817. bool opencl_replace_binary_kernel(struct cgpu_info * const cgpu, _clState * const clState, struct opencl_kernel_info * const kernelinfo, bytes_t * const b)
  818. {
  819. cl_int status;
  820. status = clReleaseProgram(kernelinfo->program);
  821. if (status != CL_SUCCESS)
  822. applogr(false, LOG_ERR, "Error %d: Releasing program. (clReleaseProgram)", status);
  823. const size_t binsz = bytes_len(b);
  824. kernelinfo->program = clCreateProgramWithBinary(clState->context, 1, &clState->devid, &binsz, (void*)&bytes_buf(b), &status, NULL);
  825. if (status != CL_SUCCESS)
  826. applogr(false, LOG_ERR, "Error %d: Loading Binary into cl_program (clCreateProgramWithBinary)", status);
  827. status = bfg_clBuildProgram(&kernelinfo->program, clState->devid, NULL);
  828. if (status != CL_SUCCESS)
  829. return false;
  830. return true;
  831. }
  832. #endif
  833. static
  834. bool opencl_save_kernel_binary(const char * const binaryfilename, bytes_t * const b)
  835. {
  836. FILE *binaryfile;
  837. /* Save the binary to be loaded next time */
  838. binaryfile = fopen(binaryfilename, "wb");
  839. if (!binaryfile)
  840. return false;
  841. // FIXME: Failure here results in a bad file; better to write and move-replace (but unlink before replacing for Windows)
  842. if (unlikely(fwrite(bytes_buf(b), 1, bytes_len(b), binaryfile) != bytes_len(b)))
  843. {
  844. fclose(binaryfile);
  845. return false;
  846. }
  847. fclose(binaryfile);
  848. return true;
  849. }
  850. static
  851. bool opencl_test_goffset(_clState * const clState)
  852. {
  853. if (sizeof(size_t) < sizeof(uint32_t))
  854. return false;
  855. const char *source = "__kernel __attribute__((reqd_work_group_size(64, 1, 1))) void runtest(volatile __global uint *out) { *out = get_global_id(0); }";
  856. const size_t source_len = strlen(source);
  857. cl_int status;
  858. cl_program program = clCreateProgramWithSource(clState->context, 1, &source, &source_len, &status);
  859. if (status != CL_SUCCESS)
  860. applogr(false, LOG_ERR, "Error %d: Loading %s code into cl_program (clCreateProgramWithSource)", status, "goffset test");
  861. status = bfg_clBuildProgram(&program, clState->devid, "");
  862. if (status != CL_SUCCESS)
  863. {
  864. fail:
  865. clReleaseProgram(program);
  866. return false;
  867. }
  868. cl_kernel kernel = clCreateKernel(program, "runtest", &status);
  869. if (status != CL_SUCCESS)
  870. return_via_applog(fail, , LOG_ERR, "Error %d: Creating kernel from %s program (clCreateKernel)", status, "goffset test");
  871. static const uint32_t cleardata = 0;
  872. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0, sizeof(cleardata), &cleardata, 0, NULL, NULL);
  873. if (status != CL_SUCCESS)
  874. {
  875. applog(LOG_ERR, "Error %d: Clearing output buffer for %s kernel (clEnqueueWriteBuffer)", status, "goffset test");
  876. fail2:
  877. clReleaseKernel(kernel);
  878. goto fail;
  879. }
  880. status = clSetKernelArg(kernel, 0, sizeof(clState->outputBuffer), &clState->outputBuffer);
  881. if (status != CL_SUCCESS)
  882. return_via_applog(fail2, , LOG_ERR, "Error %d: Setting kernel argument for %s kernel (clSetKernelArg)", status, "goffset test");
  883. const size_t size_t_one = 1, test_goffset = 0xfabd0bf9;
  884. status = clEnqueueNDRangeKernel(clState->commandQueue, kernel, 1, &test_goffset, &size_t_one, &size_t_one, 0, NULL, NULL);
  885. if (status != CL_SUCCESS)
  886. return_via_applog(fail2, , LOG_DEBUG, "Error %d: Running %s kernel (clEnqueueNDRangeKernel)", status, "goffset test");
  887. uint32_t resultdata;
  888. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0, sizeof(resultdata), &resultdata, 0, NULL, NULL);
  889. if (status != CL_SUCCESS)
  890. return_via_applog(fail2, , LOG_DEBUG, "Error %d: Reading result from %s kernel (clEnqueueReadBuffer)", status, "goffset test");
  891. applog(LOG_DEBUG, "%s kernel returned 0x%08lx for goffset 0x%08lx", "goffset test", (unsigned long)resultdata, (unsigned long)test_goffset);
  892. return (resultdata == test_goffset);
  893. }
  894. 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)
  895. {
  896. const int gpu = cgpu->device_id;
  897. struct opencl_device_data * const data = cgpu->device_data;
  898. const char * const vbuff = clState->platform_ver_str;
  899. cl_int status;
  900. /* Create binary filename based on parameters passed to opencl
  901. * compiler to ensure we only load a binary that matches what would
  902. * have otherwise created. The filename is:
  903. * kernelname + name +/- g(offset) + v + vectors + w + work_size + l + sizeof(long) + p + platform version + .bin
  904. * For scrypt the filename is:
  905. * kernelname + name + g + lg + lookup_gap + tc + thread_concurrency + w + work_size + l + sizeof(long) + p + platform version + .bin
  906. */
  907. char binaryfilename[255];
  908. char filename[255];
  909. char numbuf[32];
  910. snprintf(filename, sizeof(filename), "%s.cl", kernel_file);
  911. snprintf(binaryfilename, sizeof(filename), "%s", kernel_file);
  912. int pl;
  913. char *source = opencl_kernel_source(filename, &pl, &kernelinfo->interface, NULL);
  914. if (!source)
  915. return false;
  916. {
  917. uint8_t hash[0x20];
  918. char hashhex[7];
  919. sha256((void*)source, pl, hash);
  920. bin2hex(hashhex, hash, 3);
  921. tailsprintf(binaryfilename, sizeof(binaryfilename), "-%s", hashhex);
  922. }
  923. switch (kernelinfo->interface)
  924. {
  925. case KL_NONE:
  926. applog(LOG_ERR, "%s: Failed to identify kernel interface for %s",
  927. cgpu->dev_repr, kernel_file);
  928. free(source);
  929. return false;
  930. #ifdef USE_SHA256D
  931. case KL_PHATK:
  932. if ((strstr(vbuff, "844.4") || strstr(vbuff, "851.4") ||
  933. strstr(vbuff, "831.4") || strstr(vbuff, "898.1") ||
  934. strstr(vbuff, "923.1") || strstr(vbuff, "938.2") ||
  935. strstr(vbuff, "1113.2"))) {
  936. applog(LOG_WARNING, "WARNING: You have selected the phatk kernel.");
  937. applog(LOG_WARNING, "You are running SDK 2.6+ which performs poorly with this kernel.");
  938. applog(LOG_WARNING, "Downgrade your SDK and delete any .bin files before starting again.");
  939. applog(LOG_WARNING, "Or allow BFGMiner to automatically choose a more suitable kernel.");
  940. }
  941. #endif
  942. default:
  943. ;
  944. }
  945. applog(LOG_DEBUG, "%s: Using kernel %s with interface %s",
  946. cgpu->dev_repr, kernel_file,
  947. opencl_get_kernel_interface_name(kernelinfo->interface));
  948. {
  949. int kernel_goffset_support = 0; // 0 = none; 1 = optional; 2 = required
  950. if (strstr(source, "def GOFFSET"))
  951. kernel_goffset_support = 1;
  952. else
  953. if (strstr(source, " base,"))
  954. kernel_goffset_support = 0;
  955. else
  956. kernel_goffset_support = 2;
  957. bool device_goffset_support = false;
  958. switch (data->use_goffset)
  959. {
  960. case BTS_TRUE:
  961. device_goffset_support = true;
  962. break;
  963. case BTS_FALSE:
  964. // if the kernel doesn't require goffset, allow the user to disable it
  965. if (kernel_goffset_support != 2)
  966. break;
  967. // fallthru
  968. case BTS_UNKNOWN:
  969. if (opencl_test_goffset(clState))
  970. device_goffset_support = true;
  971. break;
  972. }
  973. 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"));
  974. if (device_goffset_support)
  975. {
  976. if (kernel_goffset_support)
  977. kernelinfo->goffset = true;
  978. }
  979. else
  980. if (kernel_goffset_support == 2)
  981. {
  982. // FIXME: Determine this before min_nonce_diff returns positive
  983. applog(LOG_ERR, "%s: Need goffset support!", cgpu->dev_repr);
  984. return false;
  985. }
  986. }
  987. if (data->work_size && data->work_size <= clState->max_work_size)
  988. kernelinfo->wsize = data->work_size;
  989. else
  990. #ifdef USE_SCRYPT
  991. if (malgo->algo == POW_SCRYPT)
  992. kernelinfo->wsize = 256;
  993. else
  994. #endif
  995. if (strstr(name, "Tahiti"))
  996. kernelinfo->wsize = 64;
  997. else
  998. kernelinfo->wsize = (clState->max_work_size <= 256 ? clState->max_work_size : 256) / clState->vwidth;
  999. #ifdef USE_SCRYPT
  1000. if (kernelinfo->interface == KL_SCRYPT)
  1001. {
  1002. if (!data->thread_concurrency)
  1003. {
  1004. unsigned int sixtyfours;
  1005. sixtyfours = data->max_alloc / 131072 / 64 - 1;
  1006. data->thread_concurrency = sixtyfours * 64;
  1007. if (data->shaders && data->thread_concurrency > data->shaders) {
  1008. data->thread_concurrency -= data->thread_concurrency % data->shaders;
  1009. if (data->thread_concurrency > data->shaders * 5)
  1010. data->thread_concurrency = data->shaders * 5;
  1011. }
  1012. applog(LOG_DEBUG, "GPU %u: selecting thread concurrency of %lu", gpu, (unsigned long)data->thread_concurrency);
  1013. }
  1014. }
  1015. #endif
  1016. strcat(binaryfilename, name);
  1017. if (kernelinfo->goffset)
  1018. strcat(binaryfilename, "g");
  1019. #ifdef USE_SCRYPT
  1020. if (kernelinfo->interface == KL_SCRYPT)
  1021. {
  1022. sprintf(numbuf, "lg%utc%u", data->lookup_gap, (unsigned int)data->thread_concurrency);
  1023. strcat(binaryfilename, numbuf);
  1024. }
  1025. else
  1026. #endif
  1027. {
  1028. sprintf(numbuf, "v%d", clState->vwidth);
  1029. strcat(binaryfilename, numbuf);
  1030. }
  1031. sprintf(numbuf, "w%d", (int)kernelinfo->wsize);
  1032. strcat(binaryfilename, numbuf);
  1033. sprintf(numbuf, "l%d", (int)sizeof(long));
  1034. strcat(binaryfilename, numbuf);
  1035. strcat(binaryfilename, "p");
  1036. strcat(binaryfilename, vbuff);
  1037. sanestr(binaryfilename, binaryfilename);
  1038. applog(LOG_DEBUG, "OCL%2u: Configured OpenCL kernel name: %s", gpu, binaryfilename);
  1039. strcat(binaryfilename, ".bin");
  1040. bool patchbfi = opencl_should_patch_bfi_int(cgpu, clState, kernelinfo);
  1041. bytes_t binary_bytes = BYTES_INIT;
  1042. if (data->opt_opencl_binaries & OBU_LOAD)
  1043. {
  1044. if (!opencl_load_kernel_binary(cgpu, clState, kernelinfo, binaryfilename, &binary_bytes))
  1045. {
  1046. bytes_free(&binary_bytes);
  1047. applog(LOG_DEBUG, "No usable binary found, generating from source");
  1048. goto build;
  1049. }
  1050. }
  1051. else
  1052. {
  1053. build:
  1054. if (!opencl_build_kernel(cgpu, clState, kernelinfo, source, pl, patchbfi))
  1055. {
  1056. free(source);
  1057. return false;
  1058. }
  1059. if ((patchbfi || (data->opt_opencl_binaries & OBU_SAVE)) && !bytes_len(&binary_bytes))
  1060. {
  1061. if (!opencl_get_kernel_binary(cgpu, clState, kernelinfo, &binary_bytes))
  1062. {
  1063. bytes_free(&binary_bytes);
  1064. applog(LOG_DEBUG, "%s: Failed to get compiled kernel binary from OpenCL (cannot save it)", cgpu->dev_repr);
  1065. // NOTE: empty binary_bytes will fail BFI_INT patch on its own
  1066. }
  1067. }
  1068. #ifdef USE_SHA256D
  1069. if (patchbfi)
  1070. {
  1071. if (!(opencl_patch_kernel_binary(&binary_bytes)) && opencl_replace_binary_kernel(cgpu, clState, kernelinfo, &binary_bytes))
  1072. {
  1073. applog(LOG_DEBUG, "%s: BFI_INT patching failed, rebuilding without it", cgpu->dev_repr);
  1074. patchbfi = false;
  1075. bytes_free(&binary_bytes);
  1076. goto build;
  1077. }
  1078. }
  1079. #endif
  1080. }
  1081. free(source);
  1082. if ((data->opt_opencl_binaries & OBU_SAVE) && bytes_len(&binary_bytes))
  1083. {
  1084. if (!opencl_save_kernel_binary(binaryfilename, &binary_bytes))
  1085. applog(LOG_DEBUG, "Unable to save file %s", binaryfilename);
  1086. }
  1087. bytes_free(&binary_bytes);
  1088. applog(LOG_INFO, "Initialising kernel %s with%s bitalign, %"PRId64" vectors and worksize %"PRIu64,
  1089. filename, clState->hasBitAlign ? "" : "out", (int64_t)clState->vwidth, (uint64_t)kernelinfo->wsize);
  1090. /* get a kernel object handle for a kernel with the given name */
  1091. kernelinfo->kernel = clCreateKernel(kernelinfo->program, "search", &status);
  1092. if (status != CL_SUCCESS) {
  1093. applog(LOG_ERR, "Error %d: Creating Kernel from program. (clCreateKernel)", status);
  1094. return false;
  1095. }
  1096. free((void*)cgpu->kname);
  1097. cgpu->kname = strdup(kernel_file);
  1098. #ifdef MAX_CLBUFFER0_SZ
  1099. switch (kernelinfo->interface)
  1100. {
  1101. #ifdef USE_SCRYPT
  1102. case KL_SCRYPT:
  1103. if (!clState->padbufsize)
  1104. {
  1105. size_t ipt = (1024 / data->lookup_gap + (1024 % data->lookup_gap > 0));
  1106. size_t bufsize = 128 * ipt * data->thread_concurrency;
  1107. /* Use the max alloc value which has been rounded to a power of
  1108. * 2 greater >= required amount earlier */
  1109. if (bufsize > data->max_alloc) {
  1110. applog(LOG_WARNING, "Maximum buffer memory device %d supports says %lu", gpu, (unsigned long)data->max_alloc);
  1111. applog(LOG_WARNING, "Your scrypt settings come to %lu", (unsigned long)bufsize);
  1112. }
  1113. applog(LOG_DEBUG, "Creating scrypt buffer sized %lu", (unsigned long)bufsize);
  1114. clState->padbufsize = bufsize;
  1115. /* This buffer is weird and might work to some degree even if
  1116. * the create buffer call has apparently failed, so check if we
  1117. * get anything back before we call it a failure. */
  1118. clState->padbuffer8 = NULL;
  1119. clState->padbuffer8 = clCreateBuffer(clState->context, CL_MEM_READ_WRITE, bufsize, NULL, &status);
  1120. if (status != CL_SUCCESS && !clState->padbuffer8) {
  1121. applog(LOG_ERR, "Error %d: clCreateBuffer (padbuffer8), decrease TC or increase LG", status);
  1122. return false;
  1123. }
  1124. }
  1125. // NOTE: fallthru
  1126. #endif
  1127. #ifdef USE_OPENCL_FULLHEADER
  1128. case KL_FULLHEADER:
  1129. #endif
  1130. if (!clState->CLbuffer0)
  1131. {
  1132. clState->CLbuffer0 = clCreateBuffer(clState->context, CL_MEM_READ_ONLY, MAX_CLBUFFER0_SZ, NULL, &status);
  1133. if (status != CL_SUCCESS) {
  1134. applog(LOG_ERR, "Error %d: clCreateBuffer (CLbuffer0)", status);
  1135. return false;
  1136. }
  1137. }
  1138. break;
  1139. default:
  1140. break;
  1141. }
  1142. #endif
  1143. kernelinfo->loaded = true;
  1144. return true;
  1145. }