main.c 61 KB

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