main.c 49 KB

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