main.c 71 KB

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