main.c 64 KB

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