main.c 68 KB

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