main.c 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916
  1. /*
  2. * Copyright 2011 Con Kolivas
  3. * Copyright 2010 Jeff Garzik
  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 2 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #include "config.h"
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <stdbool.h>
  15. #include <stdint.h>
  16. #include <unistd.h>
  17. #include <sys/time.h>
  18. #include <time.h>
  19. #include <math.h>
  20. #include <stdarg.h>
  21. #include <assert.h>
  22. #ifndef WIN32
  23. #include <sys/resource.h>
  24. #endif
  25. #include <ccan/opt/opt.h>
  26. #include <jansson.h>
  27. #include <curl/curl.h>
  28. #include "compat.h"
  29. #include "miner.h"
  30. #include "findnonce.h"
  31. #include "ocl.h"
  32. #define PROGRAM_NAME "cgminer"
  33. #define DEF_RPC_URL "http://127.0.0.1:8332/"
  34. #define DEF_RPC_USERNAME "rpcuser"
  35. #define DEF_RPC_PASSWORD "rpcpass"
  36. #define DEF_RPC_USERPASS DEF_RPC_USERNAME ":" DEF_RPC_PASSWORD
  37. #ifdef __linux /* Linux specific policy and affinity management */
  38. #include <sched.h>
  39. static inline void drop_policy(void)
  40. {
  41. struct sched_param param;
  42. #ifdef SCHED_BATCH
  43. #ifdef SCHED_IDLE
  44. if (unlikely(sched_setscheduler(0, SCHED_IDLE, &param) == -1))
  45. #endif
  46. sched_setscheduler(0, SCHED_BATCH, &param);
  47. #endif
  48. }
  49. static inline void affine_to_cpu(int id, int cpu)
  50. {
  51. cpu_set_t set;
  52. CPU_ZERO(&set);
  53. CPU_SET(cpu, &set);
  54. sched_setaffinity(0, sizeof(&set), &set);
  55. applog(LOG_INFO, "Binding cpu mining thread %d to cpu %d", id, cpu);
  56. }
  57. #else
  58. static inline void drop_policy(void)
  59. {
  60. }
  61. static inline void affine_to_cpu(int id, int cpu)
  62. {
  63. }
  64. #endif
  65. enum workio_commands {
  66. WC_GET_WORK,
  67. WC_SUBMIT_WORK,
  68. WC_DIE,
  69. };
  70. struct workio_cmd {
  71. enum workio_commands cmd;
  72. struct thr_info *thr;
  73. union {
  74. struct work *work;
  75. } u;
  76. };
  77. enum sha256_algos {
  78. ALGO_C, /* plain C */
  79. ALGO_4WAY, /* parallel SSE2 */
  80. ALGO_VIA, /* VIA padlock */
  81. ALGO_CRYPTOPP, /* Crypto++ (C) */
  82. ALGO_CRYPTOPP_ASM32, /* Crypto++ 32-bit assembly */
  83. ALGO_SSE2_64, /* SSE2 for x86_64 */
  84. };
  85. static const char *algo_names[] = {
  86. [ALGO_C] = "c",
  87. #ifdef WANT_SSE2_4WAY
  88. [ALGO_4WAY] = "4way",
  89. #endif
  90. #ifdef WANT_VIA_PADLOCK
  91. [ALGO_VIA] = "via",
  92. #endif
  93. [ALGO_CRYPTOPP] = "cryptopp",
  94. #ifdef WANT_CRYPTOPP_ASM32
  95. [ALGO_CRYPTOPP_ASM32] = "cryptopp_asm32",
  96. #endif
  97. #ifdef WANT_X8664_SSE2
  98. [ALGO_SSE2_64] = "sse2_64",
  99. #endif
  100. };
  101. bool opt_debug = false;
  102. bool opt_protocol = false;
  103. bool want_longpoll = true;
  104. bool have_longpoll = false;
  105. bool use_syslog = false;
  106. static bool opt_quiet = false;
  107. static int opt_retries = -1;
  108. static int opt_fail_pause = 5;
  109. static int opt_log_interval = 5;
  110. bool opt_log_output = false;
  111. static int opt_queue = 1;
  112. int opt_vectors;
  113. int opt_worksize;
  114. int opt_scantime = 60;
  115. static const bool opt_time = true;
  116. #ifdef WANT_X8664_SSE2
  117. static enum sha256_algos opt_algo = ALGO_SSE2_64;
  118. #else
  119. static enum sha256_algos opt_algo = ALGO_C;
  120. #endif
  121. static int nDevs;
  122. static int opt_g_threads = 2;
  123. static int opt_device;
  124. static int total_devices;
  125. static bool gpu_devices[16];
  126. static int gpu_threads;
  127. static bool forced_n_threads;
  128. static int opt_n_threads;
  129. static int num_processors;
  130. static int scan_intensity = 4;
  131. static char *rpc_url;
  132. static char *rpc_userpass;
  133. static char *rpc_user, *rpc_pass;
  134. struct thr_info *thr_info;
  135. static int work_thr_id;
  136. int longpoll_thr_id;
  137. static int stage_thr_id;
  138. struct work_restart *work_restart = NULL;
  139. pthread_mutex_t time_lock;
  140. static pthread_mutex_t hash_lock;
  141. static pthread_mutex_t qd_lock;
  142. static pthread_mutex_t stgd_lock;
  143. static double total_mhashes_done;
  144. static struct timeval total_tv_start, total_tv_end;
  145. static int accepted, rejected;
  146. int hw_errors;
  147. static int total_queued, total_staged, lp_staged;
  148. static bool localgen = false;
  149. static unsigned int getwork_requested;
  150. static char current_block[37];
  151. static char longpoll_block[37];
  152. static char blank[37];
  153. static void applog_and_exit(const char *fmt, ...)
  154. {
  155. va_list ap;
  156. va_start(ap, fmt);
  157. vapplog(LOG_ERR, fmt, ap);
  158. va_end(ap);
  159. exit(1);
  160. }
  161. /* FIXME: Use asprintf for better errors. */
  162. static char *set_algo(const char *arg, enum sha256_algos *algo)
  163. {
  164. enum sha256_algos i;
  165. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  166. if (algo_names[i] && !strcmp(arg, algo_names[i])) {
  167. *algo = i;
  168. return NULL;
  169. }
  170. }
  171. return "Unknown algorithm";
  172. }
  173. static void show_algo(char buf[OPT_SHOW_LEN], const enum sha256_algos *algo)
  174. {
  175. strncpy(buf, algo_names[*algo], OPT_SHOW_LEN);
  176. }
  177. static char *set_int_range(const char *arg, int *i, int min, int max)
  178. {
  179. char *err = opt_set_intval(arg, i);
  180. if (err)
  181. return err;
  182. if (*i < min || *i > max)
  183. return "Value out of range";
  184. return NULL;
  185. }
  186. static char *set_int_0_to_9999(const char *arg, int *i)
  187. {
  188. return set_int_range(arg, i, 0, 9999);
  189. }
  190. static char *set_int_0_to_14(const char *arg, int *i)
  191. {
  192. return set_int_range(arg, i, 0, 14);
  193. }
  194. static char *force_nthreads_int(const char *arg, int *i)
  195. {
  196. forced_n_threads = true;
  197. return set_int_range(arg, i, 0, 9999);
  198. }
  199. static char *set_int_0_to_10(const char *arg, int *i)
  200. {
  201. return set_int_range(arg, i, 0, 10);
  202. }
  203. static char *set_int_1_to_10(const char *arg, int *i)
  204. {
  205. return set_int_range(arg, i, 1, 10);
  206. }
  207. static char *set_devices(const char *arg, int *i)
  208. {
  209. char *err = opt_set_intval(arg, i);
  210. if (err)
  211. return err;
  212. if (*i < 0 || *i > 15)
  213. return "Invalid GPU device number";
  214. total_devices++;
  215. gpu_devices[*i] = true;
  216. return NULL;
  217. }
  218. static char *set_url(const char *arg, char **p)
  219. {
  220. opt_set_charp(arg, p);
  221. if (strncmp(arg, "http://", 7) &&
  222. strncmp(arg, "https://", 8))
  223. return "URL must start with http:// or https://";
  224. return NULL;
  225. }
  226. static char *set_vector(const char *arg, int *i)
  227. {
  228. char *err = opt_set_intval(arg, i);
  229. if (err)
  230. return err;
  231. if (*i != 1 && *i != 2 && *i != 4)
  232. return "Valid vectors are 1, 2 or 4";
  233. return NULL;
  234. }
  235. static char *enable_debug(bool *flag)
  236. {
  237. *flag = true;
  238. /* Turn out verbose output, too. */
  239. opt_log_output = true;
  240. return NULL;
  241. }
  242. /* These options are available from config file or commandline */
  243. static struct opt_table opt_config_table[] = {
  244. OPT_WITH_ARG("--algo|-a",
  245. set_algo, show_algo, &opt_algo,
  246. "Specify sha256 implementation:\n"
  247. "\tc\t\tLinux kernel sha256, implemented in C"
  248. #ifdef WANT_SSE2_4WAY
  249. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  250. #endif
  251. #ifdef WANT_VIA_PADLOCK
  252. "\n\tvia\t\tVIA padlock implementation"
  253. #endif
  254. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  255. #ifdef WANT_CRYPTOPP_ASM32
  256. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  257. #endif
  258. #ifdef WANT_X8664_SSE2
  259. "\n\tsse2_64\t\tSSE2 implementation for x86_64 machines"
  260. #endif
  261. ),
  262. OPT_WITH_ARG("--cpu-threads|-t",
  263. force_nthreads_int, opt_show_intval, &opt_n_threads,
  264. "Number of miner CPU threads"),
  265. OPT_WITHOUT_ARG("--debug|-D",
  266. enable_debug, &opt_debug,
  267. "Enable debug output"),
  268. #ifdef HAVE_OPENCL
  269. OPT_WITH_ARG("--device|-d",
  270. set_devices, NULL, &opt_device,
  271. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  272. OPT_WITH_ARG("--gpu-threads|-g",
  273. set_int_0_to_10, opt_show_intval, &opt_g_threads,
  274. "Number of threads per GPU (0 - 10)"),
  275. OPT_WITH_ARG("--intensity|-I",
  276. set_int_0_to_14, opt_show_intval, &scan_intensity,
  277. "Intensity of GPU scanning (0 - 14)"),
  278. #endif
  279. OPT_WITH_ARG("--log|-l",
  280. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  281. "Interval in seconds between log output"),
  282. OPT_WITHOUT_ARG("--no-longpoll",
  283. opt_set_invbool, &want_longpoll,
  284. "Disable X-Long-Polling support"),
  285. OPT_WITH_ARG("--pass|-p",
  286. opt_set_charp, NULL, &rpc_pass,
  287. "Password for bitcoin JSON-RPC server"),
  288. OPT_WITHOUT_ARG("--protocol-dump|-P",
  289. opt_set_bool, &opt_protocol,
  290. "Verbose dump of protocol-level activities"),
  291. OPT_WITH_ARG("--queue|-Q",
  292. set_int_1_to_10, opt_show_intval, &opt_queue,
  293. "Number of extra work items to queue (1 - 10)"),
  294. OPT_WITHOUT_ARG("--quiet|-q",
  295. opt_set_bool, &opt_quiet,
  296. "Disable per-thread hashmeter output"),
  297. OPT_WITH_ARG("--retries|-r",
  298. opt_set_intval, opt_show_intval, &opt_retries,
  299. "Number of times to retry before giving up, if JSON-RPC call fails (-1 means never)"),
  300. OPT_WITH_ARG("--retry-pause|-R",
  301. set_int_0_to_9999, opt_show_intval, &opt_fail_pause,
  302. "Number of seconds to pause, between retries"),
  303. OPT_WITH_ARG("--scan-time|-s",
  304. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  305. "Upper bound on time spent scanning current work, in seconds"),
  306. #ifdef HAVE_SYSLOG_H
  307. OPT_WITHOUT_ARG("--syslog",
  308. opt_set_bool, &use_syslog,
  309. "Use system log for output messages (default: standard error)"),
  310. #endif
  311. OPT_WITH_ARG("--url|-o",
  312. set_url, opt_show_charp, &rpc_url,
  313. "URL for bitcoin JSON-RPC server"),
  314. OPT_WITH_ARG("--user|-u",
  315. opt_set_charp, NULL, &rpc_user,
  316. "Username for bitcoin JSON-RPC server"),
  317. #ifdef HAVE_OPENCL
  318. OPT_WITH_ARG("--vectors|-v",
  319. set_vector, NULL, &opt_vectors,
  320. "Override detected optimal vector width (1, 2 or 4)"),
  321. #endif
  322. OPT_WITHOUT_ARG("--verbose",
  323. opt_set_bool, &opt_log_output,
  324. "Log verbose output to stderr as well as status output"),
  325. #ifdef HAVE_OPENCL
  326. OPT_WITH_ARG("--worksize|-w",
  327. set_int_0_to_9999, opt_show_intval, &opt_worksize,
  328. "Override detected optimal worksize"),
  329. #endif
  330. OPT_WITH_ARG("--userpass|-O",
  331. opt_set_charp, NULL, &rpc_userpass,
  332. "Username:Password pair for bitcoin JSON-RPC server"),
  333. OPT_ENDTABLE
  334. };
  335. static char *parse_config(json_t *config)
  336. {
  337. static char err_buf[200];
  338. json_t *val;
  339. struct opt_table *opt;
  340. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  341. char *p, *name;
  342. /* We don't handle subtables. */
  343. assert(!(opt->type & OPT_SUBTABLE));
  344. /* Pull apart the option name(s). */
  345. name = strdup(opt->names);
  346. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  347. char *err;
  348. /* Ignore short options. */
  349. if (p[1] != '-')
  350. continue;
  351. val = json_object_get(config, p+2);
  352. if (!val)
  353. continue;
  354. if ((opt->type & OPT_HASARG) && json_is_string(val)) {
  355. err = opt->cb_arg(json_string_value(val),
  356. opt->u.arg);
  357. } else if ((opt->type&OPT_NOARG) && json_is_true(val)) {
  358. err = opt->cb(opt->u.arg);
  359. } else {
  360. err = "Invalid value";
  361. }
  362. if (err) {
  363. sprintf(err_buf, "Parsing JSON option %s: %s",
  364. p, err);
  365. return err_buf;
  366. }
  367. }
  368. free(name);
  369. }
  370. return NULL;
  371. }
  372. static char *load_config(const char *arg, void *unused)
  373. {
  374. json_error_t err;
  375. json_t *config;
  376. config = json_load_file(arg, &err);
  377. if (!json_is_object(config))
  378. return "JSON decode of file failed";
  379. /* Parse the config now, so we can override it. That can keep pointers
  380. * so don't free config object. */
  381. return parse_config(config);
  382. }
  383. static char *print_ndevs_and_exit(int *ndevs)
  384. {
  385. printf("%i", *ndevs);
  386. exit(*ndevs);
  387. }
  388. /* These options are available from commandline only */
  389. static struct opt_table opt_cmdline_table[] = {
  390. OPT_WITH_ARG("--config|-c",
  391. load_config, NULL, NULL,
  392. "Load a JSON-format configuration file\n"
  393. "See example-cfg.json for an example configuration."),
  394. OPT_WITHOUT_ARG("--help|-h",
  395. opt_usage_and_exit,
  396. #ifdef HAVE_OPENCL
  397. "\nBuilt with CPU and GPU mining support.\n\n",
  398. #else
  399. "\nBuilt with CPU mining support only.\n\n",
  400. #endif
  401. "Print this message"),
  402. OPT_WITHOUT_ARG("--ndevs|-n",
  403. print_ndevs_and_exit, &nDevs,
  404. "Display number of detected GPUs and exit"),
  405. OPT_ENDTABLE
  406. };
  407. static bool jobj_binary(const json_t *obj, const char *key,
  408. void *buf, size_t buflen)
  409. {
  410. const char *hexstr;
  411. json_t *tmp;
  412. tmp = json_object_get(obj, key);
  413. if (unlikely(!tmp)) {
  414. applog(LOG_ERR, "JSON key '%s' not found", key);
  415. return false;
  416. }
  417. hexstr = json_string_value(tmp);
  418. if (unlikely(!hexstr)) {
  419. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  420. return false;
  421. }
  422. if (!hex2bin(buf, hexstr, buflen))
  423. return false;
  424. return true;
  425. }
  426. static bool work_decode(const json_t *val, struct work *work)
  427. {
  428. if (unlikely(!jobj_binary(val, "midstate",
  429. work->midstate, sizeof(work->midstate)))) {
  430. applog(LOG_ERR, "JSON inval midstate");
  431. goto err_out;
  432. }
  433. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
  434. applog(LOG_ERR, "JSON inval data");
  435. goto err_out;
  436. }
  437. if (unlikely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1)))) {
  438. applog(LOG_ERR, "JSON inval hash1");
  439. goto err_out;
  440. }
  441. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
  442. applog(LOG_ERR, "JSON inval target");
  443. goto err_out;
  444. }
  445. memset(work->hash, 0, sizeof(work->hash));
  446. return true;
  447. err_out:
  448. return false;
  449. }
  450. static double total_secs;
  451. static char statusline[256];
  452. static inline void print_status(void)
  453. {
  454. printf("%s\r", statusline);
  455. fflush(stdout);
  456. }
  457. static bool submit_fail = false;
  458. static bool submit_upstream_work(const struct work *work)
  459. {
  460. char *hexstr = NULL;
  461. json_t *val, *res;
  462. char s[345];
  463. bool rc = false;
  464. struct cgpu_info *cgpu = thr_info[work->thr_id].cgpu;
  465. CURL *curl = curl_easy_init();
  466. double utility, efficiency;
  467. if (unlikely(!curl)) {
  468. applog(LOG_ERR, "CURL initialisation failed");
  469. return rc;
  470. }
  471. /* build hex string */
  472. hexstr = bin2hex(work->data, sizeof(work->data));
  473. if (unlikely(!hexstr)) {
  474. applog(LOG_ERR, "submit_upstream_work OOM");
  475. goto out_nofree;
  476. }
  477. /* build JSON-RPC request */
  478. sprintf(s,
  479. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  480. hexstr);
  481. if (opt_debug)
  482. applog(LOG_DEBUG, "DBG: sending RPC call: %s", s);
  483. /* issue JSON-RPC request */
  484. val = json_rpc_call(curl, rpc_url, rpc_userpass, s, false, false);
  485. if (unlikely(!val)) {
  486. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  487. if (!submit_fail) {
  488. submit_fail = true;
  489. applog(LOG_WARNING, "Upstream communication failure, caching submissions");
  490. }
  491. goto out;
  492. } else if (submit_fail) {
  493. submit_fail = false;
  494. applog(LOG_WARNING, "Upstream communication resumed, submitting work");
  495. }
  496. res = json_object_get(val, "result");
  497. /* Theoretically threads could race when modifying accepted and
  498. * rejected values but the chance of two submits completing at the
  499. * same time is zero so there is no point adding extra locking */
  500. if (json_is_true(res)) {
  501. cgpu->accepted++;
  502. accepted++;
  503. if (opt_debug)
  504. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  505. if (!opt_quiet)
  506. printf("[Accepted] ");
  507. } else {
  508. cgpu->rejected++;
  509. rejected++;
  510. if (opt_debug)
  511. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  512. if (!opt_quiet)
  513. printf("[Rejected] ");
  514. }
  515. utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  516. efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  517. if (!opt_quiet) {
  518. printf("[%sPU %d] [%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m] \n",
  519. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->total_mhashes / total_secs,
  520. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  521. efficiency, utility);
  522. print_status();
  523. }
  524. applog(LOG_INFO, "%sPU %d Requested:%d Accepted:%d Rejected:%d HW errors:%d Efficiency:%.0f%% Utility:%.2f/m",
  525. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors, efficiency, utility
  526. );
  527. json_decref(val);
  528. rc = true;
  529. out:
  530. free(hexstr);
  531. out_nofree:
  532. curl_easy_cleanup(curl);
  533. return rc;
  534. }
  535. static const char *rpc_req =
  536. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  537. static bool get_upstream_work(struct work *work)
  538. {
  539. json_t *val;
  540. bool rc = false;
  541. CURL *curl = curl_easy_init();
  542. if (unlikely(!curl)) {
  543. applog(LOG_ERR, "CURL initialisation failed");
  544. return rc;
  545. }
  546. val = json_rpc_call(curl, rpc_url, rpc_userpass, rpc_req,
  547. want_longpoll, false);
  548. if (unlikely(!val)) {
  549. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  550. goto out;
  551. }
  552. rc = work_decode(json_object_get(val, "result"), work);
  553. json_decref(val);
  554. out:
  555. curl_easy_cleanup(curl);
  556. return rc;
  557. }
  558. static void workio_cmd_free(struct workio_cmd *wc)
  559. {
  560. if (!wc)
  561. return;
  562. switch (wc->cmd) {
  563. case WC_SUBMIT_WORK:
  564. free(wc->u.work);
  565. break;
  566. default: /* do nothing */
  567. break;
  568. }
  569. memset(wc, 0, sizeof(*wc)); /* poison */
  570. free(wc);
  571. }
  572. static void kill_work(void)
  573. {
  574. struct workio_cmd *wc;
  575. applog(LOG_INFO, "Received kill message");
  576. wc = calloc(1, sizeof(*wc));
  577. if (unlikely(!wc)) {
  578. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  579. /* We're just trying to die anyway, so forget graceful */
  580. exit (1);
  581. }
  582. wc->cmd = WC_DIE;
  583. wc->thr = 0;
  584. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  585. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  586. exit (1);
  587. }
  588. }
  589. static void *get_work_thread(void *userdata)
  590. {
  591. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  592. struct work *ret_work;
  593. int failures = 0;
  594. pthread_detach(pthread_self());
  595. ret_work = calloc(1, sizeof(*ret_work));
  596. if (unlikely(!ret_work)) {
  597. applog(LOG_ERR, "Failed to calloc ret_work in workio_get_work");
  598. kill_work();
  599. goto out;
  600. }
  601. /* obtain new work from bitcoin via JSON-RPC */
  602. while (!get_upstream_work(ret_work)) {
  603. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  604. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  605. free(ret_work);
  606. kill_work();
  607. goto out;
  608. }
  609. /* pause, then restart work-request loop */
  610. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  611. opt_fail_pause);
  612. sleep(opt_fail_pause);
  613. }
  614. /* send work to requesting thread */
  615. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  616. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  617. kill_work();
  618. free(ret_work);
  619. }
  620. out:
  621. workio_cmd_free(wc);
  622. return NULL;
  623. }
  624. static bool workio_get_work(struct workio_cmd *wc)
  625. {
  626. pthread_t get_thread;
  627. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  628. applog(LOG_ERR, "Failed to create get_work_thread");
  629. return false;
  630. }
  631. return true;
  632. }
  633. static void *submit_work_thread(void *userdata)
  634. {
  635. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  636. int failures = 0;
  637. char *hexstr;
  638. pthread_detach(pthread_self());
  639. hexstr = bin2hex(wc->u.work->data, 36);
  640. if (unlikely(!hexstr)) {
  641. applog(LOG_ERR, "submit_work_thread OOM");
  642. goto out;
  643. }
  644. if (unlikely(strncmp(hexstr, current_block, 36))) {
  645. applog(LOG_WARNING, "Stale work detected, discarding");
  646. goto out_free;
  647. }
  648. /* submit solution to bitcoin via JSON-RPC */
  649. while (!submit_upstream_work(wc->u.work)) {
  650. if (unlikely(strncmp(hexstr, current_block, 36))) {
  651. applog(LOG_WARNING, "Stale work detected, discarding");
  652. goto out_free;
  653. }
  654. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  655. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  656. kill_work();
  657. goto out_free;
  658. }
  659. /* pause, then restart work-request loop */
  660. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  661. opt_fail_pause);
  662. sleep(opt_fail_pause);
  663. }
  664. out_free:
  665. free(hexstr);
  666. out:
  667. workio_cmd_free(wc);
  668. return NULL;
  669. }
  670. static bool workio_submit_work(struct workio_cmd *wc)
  671. {
  672. pthread_t submit_thread;
  673. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  674. applog(LOG_ERR, "Failed to create submit_work_thread");
  675. return false;
  676. }
  677. return true;
  678. }
  679. static void inc_staged(int inc, bool lp)
  680. {
  681. pthread_mutex_lock(&stgd_lock);
  682. if (lp) {
  683. lp_staged += inc;
  684. total_staged += inc;
  685. } else if (lp_staged)
  686. lp_staged--;
  687. else
  688. total_staged += inc;
  689. pthread_mutex_unlock(&stgd_lock);
  690. }
  691. static void dec_staged(int inc)
  692. {
  693. pthread_mutex_lock(&stgd_lock);
  694. if (lp_staged)
  695. lp_staged -= inc;
  696. total_staged -= inc;
  697. pthread_mutex_unlock(&stgd_lock);
  698. }
  699. static int requests_staged(void)
  700. {
  701. int ret;
  702. pthread_mutex_lock(&stgd_lock);
  703. ret = total_staged;
  704. pthread_mutex_unlock(&stgd_lock);
  705. return ret;
  706. }
  707. static void *stage_thread(void *userdata)
  708. {
  709. struct thr_info *mythr = userdata;
  710. bool ok = true;
  711. unsigned int i;
  712. for (i = 0; i < 36; i++) {
  713. strcat(current_block, "0");
  714. strcat(blank, "0");
  715. }
  716. while (ok) {
  717. struct work *work = NULL;
  718. char *hexstr;
  719. work = tq_pop(mythr->q, NULL);
  720. if (unlikely(!work)) {
  721. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  722. ok = false;
  723. break;
  724. }
  725. hexstr = bin2hex(work->data, 36);
  726. if (unlikely(!hexstr)) {
  727. applog(LOG_ERR, "stage_thread OOM");
  728. break;
  729. }
  730. /* current_block is blanked out on successful longpoll */
  731. if (likely(strncmp(current_block, blank, 36))) {
  732. if (unlikely(strncmp(hexstr, current_block, 36))) {
  733. if (want_longpoll)
  734. applog(LOG_WARNING, "New block detected, possible missed longpoll, flushing work queue");
  735. else
  736. applog(LOG_WARNING, "New block detected, flushing work queue");
  737. /* As we can't flush the work from here, signal
  738. * the wakeup thread to restart all the
  739. * threads */
  740. work_restart[stage_thr_id].restart = 1;
  741. }
  742. } else
  743. memcpy(longpoll_block, hexstr, 36);
  744. memcpy(current_block, hexstr, 36);
  745. free(hexstr);
  746. if (unlikely(!tq_push(thr_info[0].q, work))) {
  747. applog(LOG_ERR, "Failed to tq_push work in stage_thread");
  748. ok = false;
  749. break;
  750. }
  751. inc_staged(1, false);
  752. }
  753. tq_freeze(mythr->q);
  754. return NULL;
  755. }
  756. static void *workio_thread(void *userdata)
  757. {
  758. struct thr_info *mythr = userdata;
  759. bool ok = true;
  760. while (ok) {
  761. struct workio_cmd *wc;
  762. /* wait for workio_cmd sent to us, on our queue */
  763. wc = tq_pop(mythr->q, NULL);
  764. if (unlikely(!wc)) {
  765. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  766. ok = false;
  767. break;
  768. }
  769. /* process workio_cmd */
  770. switch (wc->cmd) {
  771. case WC_GET_WORK:
  772. ok = workio_get_work(wc);
  773. break;
  774. case WC_SUBMIT_WORK:
  775. ok = workio_submit_work(wc);
  776. break;
  777. case WC_DIE:
  778. default:
  779. ok = false;
  780. break;
  781. }
  782. }
  783. tq_freeze(mythr->q);
  784. return NULL;
  785. }
  786. static void hashmeter(int thr_id, struct timeval *diff,
  787. unsigned long hashes_done)
  788. {
  789. struct timeval temp_tv_end, total_diff;
  790. double khashes, secs;
  791. double local_secs;
  792. double utility, efficiency = 0.0;
  793. static double local_mhashes_done = 0;
  794. static double rolling_local = 0;
  795. double local_mhashes = (double)hashes_done / 1000000.0;
  796. /* Don't bother calculating anything if we're not displaying it */
  797. if (opt_quiet || !opt_log_interval)
  798. return;
  799. khashes = hashes_done / 1000.0;
  800. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  801. if (thr_id >= 0) {
  802. /* So we can call hashmeter from a non worker thread */
  803. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  804. if (opt_debug)
  805. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  806. thr_id, hashes_done, hashes_done / secs);
  807. cgpu->local_mhashes += local_mhashes;
  808. cgpu->total_mhashes += local_mhashes;
  809. }
  810. /* Totals are updated by all threads so can race without locking */
  811. pthread_mutex_lock(&hash_lock);
  812. gettimeofday(&temp_tv_end, NULL);
  813. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  814. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  815. total_mhashes_done += local_mhashes;
  816. local_mhashes_done += local_mhashes;
  817. if (total_diff.tv_sec < opt_log_interval)
  818. /* Only update the total every opt_log_interval seconds */
  819. goto out_unlock;
  820. gettimeofday(&total_tv_end, NULL);
  821. /* Use a rolling average by faking an exponential decay over 5 * log */
  822. rolling_local = ((rolling_local * 0.9) + local_mhashes_done) / 1.9;
  823. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  824. total_secs = (double)total_diff.tv_sec +
  825. ((double)total_diff.tv_usec / 1000000.0);
  826. utility = accepted / ( total_secs ? total_secs : 1 ) * 60;
  827. efficiency = getwork_requested ? accepted * 100.0 / getwork_requested : 0.0;
  828. sprintf(statusline, "[(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m] ",
  829. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  830. getwork_requested, accepted, rejected, hw_errors, efficiency, utility);
  831. print_status();
  832. applog(LOG_INFO, "[Rate (%ds):%.1f (avg):%.2f Mhash/s] [Requested:%d Accepted:%d Rejected:%d HW errors:%d Efficiency:%.0f%% Utility:%.2f/m]",
  833. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  834. getwork_requested, accepted, rejected, hw_errors, efficiency, utility);
  835. local_mhashes_done = 0;
  836. out_unlock:
  837. pthread_mutex_unlock(&hash_lock);
  838. }
  839. /* This is overkill, but at least we'll know accurately how much work is
  840. * queued to prevent ever being left without work */
  841. static void inc_queued(void)
  842. {
  843. pthread_mutex_lock(&qd_lock);
  844. total_queued++;
  845. pthread_mutex_unlock(&qd_lock);
  846. }
  847. static void dec_queued(void)
  848. {
  849. pthread_mutex_lock(&qd_lock);
  850. total_queued--;
  851. pthread_mutex_unlock(&qd_lock);
  852. dec_staged(1);
  853. }
  854. static int requests_queued(void)
  855. {
  856. int ret;
  857. pthread_mutex_lock(&qd_lock);
  858. ret = total_queued;
  859. pthread_mutex_unlock(&qd_lock);
  860. return ret;
  861. }
  862. /* All work is queued flagged as being for thread 0 and then the mining thread
  863. * flags it as its own */
  864. static bool queue_request(void)
  865. {
  866. struct thr_info *thr = &thr_info[0];
  867. struct workio_cmd *wc;
  868. /* fill out work request message */
  869. wc = calloc(1, sizeof(*wc));
  870. if (unlikely(!wc)) {
  871. applog(LOG_ERR, "Failed to tq_pop in queue_request");
  872. return false;
  873. }
  874. wc->cmd = WC_GET_WORK;
  875. wc->thr = thr;
  876. /* send work request to workio thread */
  877. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  878. applog(LOG_ERR, "Failed to tq_push in queue_request");
  879. workio_cmd_free(wc);
  880. return false;
  881. }
  882. inc_queued();
  883. return true;
  884. }
  885. static bool discard_request(void)
  886. {
  887. struct thr_info *thr = &thr_info[0];
  888. struct work *work_heap;
  889. /* Just in case we fell in a hole and missed a queue filling */
  890. if (unlikely(!requests_queued())) {
  891. applog(LOG_WARNING, "Tried to discard_request with nil queued");
  892. return true;
  893. }
  894. work_heap = tq_pop(thr->q, NULL);
  895. if (unlikely(!work_heap)) {
  896. applog(LOG_ERR, "Failed to tq_pop in discard_request");
  897. return false;
  898. }
  899. free(work_heap);
  900. dec_queued();
  901. return true;
  902. }
  903. static void flush_requests(bool longpoll)
  904. {
  905. int i, extra;
  906. extra = requests_queued();
  907. /* When flushing from longpoll, we don't know the new work yet. When
  908. * not flushing from longpoll, the first work item is valid so do not
  909. * discard it */
  910. if (longpoll)
  911. memcpy(current_block, blank, 36);
  912. else
  913. extra--;
  914. /* Temporarily increase the staged count so that get_work thinks there
  915. * is work available instead of making threads reuse existing work */
  916. inc_staged(extra, true);
  917. for (i = 0; i < extra; i++) {
  918. /* Queue a whole batch of new requests */
  919. if (unlikely(!queue_request())) {
  920. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  921. kill_work();
  922. break;
  923. }
  924. /* Pop off the old requests. Cancelling the requests would be better
  925. * but is tricky */
  926. if (unlikely(!discard_request())) {
  927. applog(LOG_ERR, "Failed to discard requests in flush_requests");
  928. kill_work();
  929. break;
  930. }
  931. }
  932. }
  933. static bool get_work(struct work *work, bool queued)
  934. {
  935. struct thr_info *thr = &thr_info[0];
  936. struct work *work_heap;
  937. bool ret = false;
  938. int failures = 0;
  939. getwork_requested++;
  940. retry:
  941. if (unlikely(!queued && !queue_request())) {
  942. applog(LOG_WARNING, "Failed to queue_request in get_work");
  943. goto out;
  944. }
  945. if (!requests_staged()) {
  946. uint32_t *work_ntime;
  947. uint32_t ntime;
  948. /* Only print this message once each time we shift to localgen */
  949. if (!localgen)
  950. applog(LOG_WARNING, "Server not providing work fast enough, generating work locally");
  951. localgen = true;
  952. work_ntime = (uint32_t *)(work->data + 68);
  953. ntime = be32toh(*work_ntime);
  954. ntime++;
  955. *work_ntime = htobe32(ntime);
  956. ret = true;
  957. goto out;
  958. } else if (localgen) {
  959. localgen = false;
  960. applog(LOG_WARNING, "Resumed retrieving work from server");
  961. }
  962. /* wait for 1st response, or get cached response */
  963. work_heap = tq_pop(thr->q, NULL);
  964. if (unlikely(!work_heap)) {
  965. applog(LOG_WARNING, "Failed to tq_pop in get_work");
  966. goto out;
  967. }
  968. dec_queued();
  969. memcpy(work, work_heap, sizeof(*work));
  970. ret = true;
  971. free(work_heap);
  972. out:
  973. if (unlikely(ret == false)) {
  974. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  975. applog(LOG_ERR, "Failed %d times to get_work");
  976. return ret;
  977. }
  978. applog(LOG_DEBUG, "Retrying after %d seconds", opt_fail_pause);
  979. sleep(opt_fail_pause);
  980. goto retry;
  981. }
  982. return ret;
  983. }
  984. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  985. {
  986. struct workio_cmd *wc;
  987. /* fill out work request message */
  988. wc = calloc(1, sizeof(*wc));
  989. if (unlikely(!wc)) {
  990. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  991. return false;
  992. }
  993. wc->u.work = malloc(sizeof(*work_in));
  994. if (unlikely(!wc->u.work)) {
  995. applog(LOG_ERR, "Failed to calloc work in submit_work_sync");
  996. goto err_out;
  997. }
  998. wc->cmd = WC_SUBMIT_WORK;
  999. wc->thr = thr;
  1000. memcpy(wc->u.work, work_in, sizeof(*work_in));
  1001. /* send solution to workio thread */
  1002. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1003. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  1004. goto err_out;
  1005. }
  1006. return true;
  1007. err_out:
  1008. workio_cmd_free(wc);
  1009. return false;
  1010. }
  1011. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  1012. {
  1013. work->data[64+12+0] = (nonce>>0) & 0xff;
  1014. work->data[64+12+1] = (nonce>>8) & 0xff;
  1015. work->data[64+12+2] = (nonce>>16) & 0xff;
  1016. work->data[64+12+3] = (nonce>>24) & 0xff;
  1017. return submit_work_sync(thr, work);
  1018. }
  1019. static inline int cpu_from_thr_id(int thr_id)
  1020. {
  1021. return (thr_id - gpu_threads) % num_processors;
  1022. }
  1023. static void *miner_thread(void *userdata)
  1024. {
  1025. struct thr_info *mythr = userdata;
  1026. const int thr_id = mythr->id;
  1027. uint32_t max_nonce = 0xffffff;
  1028. bool needs_work = true;
  1029. /* Try to cycle approximately 5 times before each log update */
  1030. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1031. /* Request the next work item at 2/3 of the scantime */
  1032. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1033. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1034. bool requested = true;
  1035. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  1036. * and if that fails, then SCHED_BATCH. No need for this to be an
  1037. * error if it fails */
  1038. setpriority(PRIO_PROCESS, 0, 19);
  1039. drop_policy();
  1040. /* Cpu affinity only makes sense if the number of threads is a multiple
  1041. * of the number of CPUs */
  1042. if (!(opt_n_threads % num_processors))
  1043. affine_to_cpu(thr_id - gpu_threads, cpu_from_thr_id(thr_id));
  1044. while (1) {
  1045. struct work work __attribute__((aligned(128)));
  1046. unsigned long hashes_done;
  1047. struct timeval tv_workstart, tv_start, tv_end, diff;
  1048. uint64_t max64;
  1049. bool rc;
  1050. if (needs_work) {
  1051. gettimeofday(&tv_workstart, NULL);
  1052. /* obtain new work from internal workio thread */
  1053. if (unlikely(!get_work(&work, requested))) {
  1054. applog(LOG_ERR, "work retrieval failed, exiting "
  1055. "mining thread %d", thr_id);
  1056. goto out;
  1057. }
  1058. mythr->cgpu->getworks++;
  1059. work.thr_id = thr_id;
  1060. needs_work = requested = false;
  1061. work.blk.nonce = 0;
  1062. }
  1063. hashes_done = 0;
  1064. gettimeofday(&tv_start, NULL);
  1065. /* scan nonces for a proof-of-work hash */
  1066. switch (opt_algo) {
  1067. case ALGO_C:
  1068. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  1069. work.hash1, work.hash, work.target,
  1070. max_nonce, &hashes_done,
  1071. work.blk.nonce);
  1072. break;
  1073. #ifdef WANT_X8664_SSE2
  1074. case ALGO_SSE2_64: {
  1075. unsigned int rc5 =
  1076. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  1077. work.hash1, work.hash,
  1078. work.target,
  1079. max_nonce, &hashes_done,
  1080. work.blk.nonce);
  1081. rc = (rc5 == -1) ? false : true;
  1082. }
  1083. break;
  1084. #endif
  1085. #ifdef WANT_SSE2_4WAY
  1086. case ALGO_4WAY: {
  1087. unsigned int rc4 =
  1088. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  1089. work.hash1, work.hash,
  1090. work.target,
  1091. max_nonce, &hashes_done,
  1092. work.blk.nonce);
  1093. rc = (rc4 == -1) ? false : true;
  1094. }
  1095. break;
  1096. #endif
  1097. #ifdef WANT_VIA_PADLOCK
  1098. case ALGO_VIA:
  1099. rc = scanhash_via(thr_id, work.data, work.target,
  1100. max_nonce, &hashes_done,
  1101. work.blk.nonce);
  1102. break;
  1103. #endif
  1104. case ALGO_CRYPTOPP:
  1105. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  1106. work.hash1, work.hash, work.target,
  1107. max_nonce, &hashes_done,
  1108. work.blk.nonce);
  1109. break;
  1110. #ifdef WANT_CRYPTOPP_ASM32
  1111. case ALGO_CRYPTOPP_ASM32:
  1112. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  1113. work.hash1, work.hash, work.target,
  1114. max_nonce, &hashes_done,
  1115. work.blk.nonce);
  1116. break;
  1117. #endif
  1118. default:
  1119. /* should never happen */
  1120. goto out;
  1121. }
  1122. /* record scanhash elapsed time */
  1123. gettimeofday(&tv_end, NULL);
  1124. timeval_subtract(&diff, &tv_end, &tv_start);
  1125. hashes_done -= work.blk.nonce;
  1126. hashmeter(thr_id, &diff, hashes_done);
  1127. work.blk.nonce += hashes_done;
  1128. /* adjust max_nonce to meet target cycle time */
  1129. if (diff.tv_usec > 500000)
  1130. diff.tv_sec++;
  1131. if (diff.tv_sec && diff.tv_sec != cycle) {
  1132. max64 = work.blk.nonce +
  1133. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  1134. } else
  1135. max64 = work.blk.nonce + hashes_done;
  1136. if (max64 > 0xfffffffaULL)
  1137. max64 = 0xfffffffaULL;
  1138. max_nonce = max64;
  1139. /* if nonce found, submit work */
  1140. if (unlikely(rc)) {
  1141. if (opt_debug)
  1142. applog(LOG_DEBUG, "CPU %d found something?", cpu_from_thr_id(thr_id));
  1143. if (unlikely(!submit_work_sync(mythr, &work))) {
  1144. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  1145. break;
  1146. }
  1147. work.blk.nonce += 4;
  1148. }
  1149. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1150. if (!requested && (diff.tv_sec > request_interval || work.blk.nonce > request_nonce)) {
  1151. if (unlikely(!queue_request())) {
  1152. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  1153. goto out;
  1154. }
  1155. requested = true;
  1156. }
  1157. if (diff.tv_sec > opt_scantime || work_restart[thr_id].restart ||
  1158. work.blk.nonce >= MAXTHREADS - hashes_done)
  1159. needs_work = true;
  1160. }
  1161. out:
  1162. tq_freeze(mythr->q);
  1163. return NULL;
  1164. }
  1165. enum {
  1166. STAT_SLEEP_INTERVAL = 1,
  1167. STAT_CTR_INTERVAL = 10000000,
  1168. FAILURE_INTERVAL = 30,
  1169. };
  1170. #ifdef HAVE_OPENCL
  1171. static _clState *clStates[16];
  1172. static inline cl_int queue_kernel_parameters(_clState *clState, dev_blk_ctx *blk)
  1173. {
  1174. cl_kernel *kernel = &clState->kernel;
  1175. cl_int status = 0;
  1176. int num = 0;
  1177. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  1178. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  1179. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  1180. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  1181. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  1182. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  1183. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  1184. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  1185. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  1186. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  1187. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  1188. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  1189. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  1190. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  1191. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  1192. if (clState->hasBitAlign == true) {
  1193. /* Parameters for phatk kernel */
  1194. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2);
  1195. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  1196. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  1197. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4);
  1198. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1);
  1199. } else {
  1200. /* Parameters for poclbm kernel */
  1201. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  1202. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  1203. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  1204. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  1205. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  1206. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  1207. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  1208. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  1209. }
  1210. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  1211. (void *)&clState->outputBuffer);
  1212. return status;
  1213. }
  1214. static inline int gpu_from_thr_id(int thr_id)
  1215. {
  1216. return thr_id % nDevs;
  1217. }
  1218. static void *gpuminer_thread(void *userdata)
  1219. {
  1220. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1221. struct timeval tv_start, tv_end, diff;
  1222. struct thr_info *mythr = userdata;
  1223. const int thr_id = mythr->id;
  1224. uint32_t *res, *blank_res;
  1225. size_t globalThreads[1];
  1226. size_t localThreads[1];
  1227. cl_int status;
  1228. _clState *clState = clStates[thr_id];
  1229. const cl_kernel *kernel = &clState->kernel;
  1230. struct work *work = malloc(sizeof(struct work));
  1231. unsigned const int threads = 1 << (15 + scan_intensity);
  1232. unsigned const int vectors = clState->preferred_vwidth;
  1233. unsigned const int hashes = threads * vectors;
  1234. unsigned int hashes_done = 0;
  1235. /* Request the next work item at 2/3 of the scantime */
  1236. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1237. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1238. bool requested = true;
  1239. res = calloc(BUFFERSIZE, 1);
  1240. blank_res = calloc(BUFFERSIZE, 1);
  1241. if (!res || !blank_res) {
  1242. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  1243. goto out;
  1244. }
  1245. gettimeofday(&tv_start, NULL);
  1246. globalThreads[0] = threads;
  1247. localThreads[0] = clState->work_size;
  1248. diff.tv_sec = ~0UL;
  1249. gettimeofday(&tv_end, NULL);
  1250. while (1) {
  1251. struct timeval tv_workstart;
  1252. /* This finish flushes the readbuffer set with CL_FALSE later */
  1253. clFinish(clState->commandQueue);
  1254. if (diff.tv_sec > opt_scantime || work->blk.nonce >= MAXTHREADS - hashes || work_restart[thr_id].restart) {
  1255. /* Ignore any reads since we're getting new work and queue a clean buffer */
  1256. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1257. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1258. if (unlikely(status != CL_SUCCESS))
  1259. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1260. memset(res, 0, BUFFERSIZE);
  1261. gettimeofday(&tv_workstart, NULL);
  1262. /* obtain new work from internal workio thread */
  1263. if (unlikely(!get_work(work, requested))) {
  1264. applog(LOG_ERR, "work retrieval failed, exiting "
  1265. "gpu mining thread %d", mythr->id);
  1266. goto out;
  1267. }
  1268. mythr->cgpu->getworks++;
  1269. work->thr_id = thr_id;
  1270. requested = false;
  1271. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  1272. work->blk.nonce = 0;
  1273. work_restart[thr_id].restart = 0;
  1274. if (opt_debug)
  1275. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  1276. /* Flushes the writebuffer set with CL_FALSE above */
  1277. clFinish(clState->commandQueue);
  1278. }
  1279. status = queue_kernel_parameters(clState, &work->blk);
  1280. if (unlikely(status != CL_SUCCESS))
  1281. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  1282. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  1283. if (res[MAXBUFFERS]) {
  1284. /* Clear the buffer again */
  1285. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1286. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1287. if (unlikely(status != CL_SUCCESS))
  1288. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1289. if (opt_debug)
  1290. applog(LOG_DEBUG, "GPU %d found something?", gpu_from_thr_id(thr_id));
  1291. postcalc_hash_async(mythr, work, res);
  1292. memset(res, 0, BUFFERSIZE);
  1293. clFinish(clState->commandQueue);
  1294. }
  1295. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  1296. globalThreads, localThreads, 0, NULL, NULL);
  1297. if (unlikely(status != CL_SUCCESS))
  1298. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  1299. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1300. BUFFERSIZE, res, 0, NULL, NULL);
  1301. if (unlikely(status != CL_SUCCESS))
  1302. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  1303. gettimeofday(&tv_end, NULL);
  1304. timeval_subtract(&diff, &tv_end, &tv_start);
  1305. hashes_done += hashes;
  1306. work->blk.nonce += hashes;
  1307. if (diff.tv_usec > 500000)
  1308. diff.tv_sec++;
  1309. if (diff.tv_sec >= cycle) {
  1310. hashmeter(thr_id, &diff, hashes_done);
  1311. gettimeofday(&tv_start, NULL);
  1312. hashes_done = 0;
  1313. }
  1314. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1315. if (!requested && (diff.tv_sec > request_interval || work->blk.nonce > request_nonce)) {
  1316. if (unlikely(!queue_request())) {
  1317. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  1318. goto out;
  1319. }
  1320. requested = true;
  1321. }
  1322. }
  1323. out:
  1324. tq_freeze(mythr->q);
  1325. return NULL;
  1326. }
  1327. #endif /* HAVE_OPENCL */
  1328. static void restart_threads(bool longpoll)
  1329. {
  1330. int i;
  1331. /* Discard old queued requests and get new ones */
  1332. flush_requests(longpoll);
  1333. for (i = 0; i < opt_n_threads + gpu_threads; i++)
  1334. work_restart[i].restart = 1;
  1335. }
  1336. static void *longpoll_thread(void *userdata)
  1337. {
  1338. struct thr_info *mythr = userdata;
  1339. CURL *curl = NULL;
  1340. char *copy_start, *hdr_path, *lp_url = NULL;
  1341. bool need_slash = false;
  1342. int failures = 0;
  1343. unsigned int i;
  1344. hdr_path = tq_pop(mythr->q, NULL);
  1345. if (!hdr_path)
  1346. goto out;
  1347. /* full URL */
  1348. if (strstr(hdr_path, "://")) {
  1349. lp_url = hdr_path;
  1350. hdr_path = NULL;
  1351. }
  1352. /* absolute path, on current server */
  1353. else {
  1354. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  1355. if (rpc_url[strlen(rpc_url) - 1] != '/')
  1356. need_slash = true;
  1357. lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  1358. if (!lp_url)
  1359. goto out;
  1360. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  1361. }
  1362. applog(LOG_INFO, "Long-polling activated for %s", lp_url);
  1363. curl = curl_easy_init();
  1364. if (unlikely(!curl)) {
  1365. applog(LOG_ERR, "CURL initialisation failed");
  1366. goto out;
  1367. }
  1368. for (i = 0; i < 36; i++)
  1369. strcat(longpoll_block, "0");
  1370. while (1) {
  1371. json_t *val;
  1372. val = json_rpc_call(curl, lp_url, rpc_userpass, rpc_req,
  1373. false, true);
  1374. if (likely(val)) {
  1375. failures = 0;
  1376. json_decref(val);
  1377. /* Keep track of who ordered a restart_threads to make
  1378. * sure it's only done once per new block */
  1379. if (likely(!strncmp(longpoll_block, blank, 36) ||
  1380. !strncmp(longpoll_block, current_block, 36))) {
  1381. applog(LOG_WARNING, "LONGPOLL detected new block, flushing work queue");
  1382. restart_threads(true);
  1383. } else
  1384. applog(LOG_WARNING, "LONGPOLL received - new block detected and work flushed already");
  1385. } else {
  1386. if (failures++ < 10) {
  1387. sleep(30);
  1388. applog(LOG_WARNING,
  1389. "longpoll failed, sleeping for 30s");
  1390. } else {
  1391. applog(LOG_ERR,
  1392. "longpoll failed, ending thread");
  1393. goto out;
  1394. }
  1395. }
  1396. memcpy(longpoll_block, current_block, 36);
  1397. }
  1398. out:
  1399. free(hdr_path);
  1400. free(lp_url);
  1401. tq_freeze(mythr->q);
  1402. if (curl)
  1403. curl_easy_cleanup(curl);
  1404. return NULL;
  1405. }
  1406. /* Makes sure the hashmeter keeps going even if mining threads stall */
  1407. static void *wakeup_thread(void *userdata)
  1408. {
  1409. const unsigned int interval = opt_log_interval / 2 ? : 1;
  1410. struct timeval zero_tv;
  1411. memset(&zero_tv, 0, sizeof(struct timeval));
  1412. while (1) {
  1413. sleep(interval);
  1414. if (requests_queued() < opt_queue)
  1415. queue_request();
  1416. hashmeter(-1, &zero_tv, 0);
  1417. if (unlikely(work_restart[stage_thr_id].restart)) {
  1418. restart_threads(false);
  1419. work_restart[stage_thr_id].restart = 0;
  1420. }
  1421. }
  1422. return NULL;
  1423. }
  1424. int main (int argc, char *argv[])
  1425. {
  1426. struct thr_info *thr;
  1427. unsigned int i, j = 0;
  1428. char name[32];
  1429. struct cgpu_info *gpus = NULL, *cpus = NULL;
  1430. if (unlikely(pthread_mutex_init(&time_lock, NULL)))
  1431. return 1;
  1432. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  1433. return 1;
  1434. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  1435. return 1;
  1436. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  1437. return 1;
  1438. #ifdef WIN32
  1439. opt_n_threads = num_processors = 1;
  1440. #else
  1441. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  1442. opt_n_threads = num_processors;
  1443. #endif /* !WIN32 */
  1444. #ifdef HAVE_OPENCL
  1445. for (i = 0; i < 16; i++)
  1446. gpu_devices[true] = false;
  1447. nDevs = clDevicesNum();
  1448. if (nDevs < 0)
  1449. return 1;
  1450. #endif
  1451. if (nDevs)
  1452. opt_n_threads = 0;
  1453. rpc_url = strdup(DEF_RPC_URL);
  1454. /* parse command line */
  1455. opt_register_table(opt_config_table,
  1456. "Options for both config file and command line");
  1457. opt_register_table(opt_cmdline_table,
  1458. "Options for command line only");
  1459. opt_parse(&argc, argv, applog_and_exit);
  1460. if (argc != 1) {
  1461. applog(LOG_ERR, "Unexpected extra commandline arguments");
  1462. return 1;
  1463. }
  1464. if (total_devices) {
  1465. if (total_devices > nDevs) {
  1466. applog(LOG_ERR, "More devices specified than exist");
  1467. return 1;
  1468. }
  1469. for (i = 0; i < 16; i++)
  1470. if (gpu_devices[i] && i + 1 > nDevs) {
  1471. applog(LOG_ERR, "Command line options set a device that doesn't exist");
  1472. return 1;
  1473. }
  1474. gpu_threads = total_devices * opt_g_threads;
  1475. } else {
  1476. gpu_threads = nDevs * opt_g_threads;
  1477. for (i = 0; i < nDevs; i++)
  1478. gpu_devices[i] = true;
  1479. }
  1480. if (!gpu_threads && !forced_n_threads) {
  1481. /* Maybe they turned GPU off; restore default CPU threads. */
  1482. opt_n_threads = num_processors;
  1483. }
  1484. if (!rpc_userpass) {
  1485. if (!rpc_user || !rpc_pass) {
  1486. applog(LOG_ERR, "No login credentials supplied");
  1487. return 1;
  1488. }
  1489. rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  1490. if (!rpc_userpass)
  1491. return 1;
  1492. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  1493. }
  1494. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  1495. return 1;
  1496. #ifdef HAVE_SYSLOG_H
  1497. if (use_syslog)
  1498. openlog("cpuminer", LOG_PID, LOG_USER);
  1499. #endif
  1500. work_restart = calloc(opt_n_threads + 4 + gpu_threads, sizeof(*work_restart));
  1501. if (!work_restart)
  1502. return 1;
  1503. thr_info = calloc(opt_n_threads + 4 + gpu_threads, sizeof(*thr));
  1504. if (!thr_info)
  1505. return 1;
  1506. /* init workio thread info */
  1507. work_thr_id = opt_n_threads + gpu_threads;
  1508. thr = &thr_info[work_thr_id];
  1509. thr->id = work_thr_id;
  1510. thr->q = tq_new();
  1511. if (!thr->q)
  1512. return 1;
  1513. /* start work I/O thread */
  1514. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  1515. applog(LOG_ERR, "workio thread create failed");
  1516. return 1;
  1517. }
  1518. /* init longpoll thread info */
  1519. if (want_longpoll) {
  1520. longpoll_thr_id = opt_n_threads + gpu_threads + 1;
  1521. thr = &thr_info[longpoll_thr_id];
  1522. thr->id = longpoll_thr_id;
  1523. thr->q = tq_new();
  1524. if (!thr->q)
  1525. return 1;
  1526. /* start longpoll thread */
  1527. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  1528. applog(LOG_ERR, "longpoll thread create failed");
  1529. return 1;
  1530. }
  1531. pthread_detach(thr->pth);
  1532. } else
  1533. longpoll_thr_id = -1;
  1534. gettimeofday(&total_tv_start, NULL);
  1535. gettimeofday(&total_tv_end, NULL);
  1536. if (opt_n_threads ) {
  1537. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  1538. if (unlikely(!cpus)) {
  1539. applog(LOG_ERR, "Failed to calloc cpus");
  1540. return 1;
  1541. }
  1542. }
  1543. if (gpu_threads) {
  1544. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  1545. if (unlikely(!gpus)) {
  1546. applog(LOG_ERR, "Failed to calloc gpus");
  1547. return 1;
  1548. }
  1549. }
  1550. stage_thr_id = opt_n_threads + gpu_threads + 3;
  1551. thr = &thr_info[stage_thr_id];
  1552. thr->q = tq_new();
  1553. if (!thr->q)
  1554. return 1;
  1555. /* start stage thread */
  1556. if (pthread_create(&thr->pth, NULL, stage_thread, thr)) {
  1557. applog(LOG_ERR, "stage thread create failed");
  1558. return 1;
  1559. }
  1560. /* Put enough work in the queue */
  1561. for (i = 0; i < opt_queue + opt_n_threads + gpu_threads; i++) {
  1562. if (unlikely(!queue_request())) {
  1563. applog(LOG_ERR, "Failed to queue_request in main");
  1564. return 1;
  1565. }
  1566. inc_staged(1, true);
  1567. }
  1568. #ifdef HAVE_OPENCL
  1569. i = 0;
  1570. /* start GPU mining threads */
  1571. for (j = 0; j < nDevs * opt_g_threads; j++) {
  1572. int gpu = gpu_from_thr_id(j);
  1573. /* Skip devices not set to work */
  1574. if (!gpu_devices[gpu])
  1575. continue;
  1576. thr = &thr_info[i];
  1577. thr->id = i;
  1578. gpus[gpu].is_gpu = 1;
  1579. gpus[gpu].cpu_gpu = gpu;
  1580. thr->cgpu = &gpus[gpu];
  1581. thr->q = tq_new();
  1582. if (!thr->q) {
  1583. applog(LOG_ERR, "tq_new failed in starting gpu mining threads");
  1584. return 1;
  1585. }
  1586. applog(LOG_INFO, "Init GPU thread %i", i);
  1587. clStates[i] = initCl(gpu, name, sizeof(name));
  1588. if (!clStates[i]) {
  1589. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  1590. continue;
  1591. }
  1592. applog(LOG_INFO, "initCl() finished. Found %s", name);
  1593. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1594. applog(LOG_ERR, "thread %d create failed", i);
  1595. return 1;
  1596. }
  1597. pthread_detach(thr->pth);
  1598. i++;
  1599. }
  1600. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  1601. #endif
  1602. /* start CPU mining threads */
  1603. for (i = gpu_threads; i < gpu_threads + opt_n_threads; i++) {
  1604. int cpu = cpu_from_thr_id(i);
  1605. thr = &thr_info[i];
  1606. thr->id = i;
  1607. cpus[cpu].cpu_gpu = cpu;
  1608. thr->cgpu = &cpus[cpu];
  1609. thr->q = tq_new();
  1610. if (!thr->q) {
  1611. applog(LOG_ERR, "tq_new failed in starting cpu mining threads");
  1612. return 1;
  1613. }
  1614. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1615. applog(LOG_ERR, "thread %d create failed", i);
  1616. return 1;
  1617. }
  1618. pthread_detach(thr->pth);
  1619. }
  1620. applog(LOG_INFO, "%d cpu miner threads started, "
  1621. "using SHA256 '%s' algorithm.",
  1622. opt_n_threads,
  1623. algo_names[opt_algo]);
  1624. thr = &thr_info[opt_n_threads + gpu_threads + 2];
  1625. /* start wakeup thread */
  1626. if (pthread_create(&thr->pth, NULL, wakeup_thread, NULL)) {
  1627. applog(LOG_ERR, "wakeup thread create failed");
  1628. return 1;
  1629. }
  1630. /* Restart count as it will be wrong till all threads are started */
  1631. pthread_mutex_lock(&hash_lock);
  1632. gettimeofday(&total_tv_start, NULL);
  1633. gettimeofday(&total_tv_end, NULL);
  1634. total_mhashes_done = 0;
  1635. pthread_mutex_unlock(&hash_lock);
  1636. /* main loop - simply wait for workio thread to exit */
  1637. pthread_join(thr_info[work_thr_id].pth, NULL);
  1638. curl_global_cleanup();
  1639. if (gpu_threads)
  1640. free(gpus);
  1641. if (opt_n_threads)
  1642. free(cpus);
  1643. applog(LOG_INFO, "workio thread dead, exiting.");
  1644. return 0;
  1645. }