main.c 72 KB

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