main.c 62 KB

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