main.c 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024
  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. #ifndef WIN32
  24. #include <sys/resource.h>
  25. #endif
  26. #include <ccan/opt/opt.h>
  27. #include <jansson.h>
  28. #include <curl/curl.h>
  29. #include "compat.h"
  30. #include "miner.h"
  31. #include "findnonce.h"
  32. #include "ocl.h"
  33. #define PROGRAM_NAME "cgminer"
  34. #define DEF_RPC_URL "http://127.0.0.1:8332/"
  35. #define DEF_RPC_USERNAME "rpcuser"
  36. #define DEF_RPC_PASSWORD "rpcpass"
  37. #define DEF_RPC_USERPASS DEF_RPC_USERNAME ":" DEF_RPC_PASSWORD
  38. #ifdef __linux /* Linux specific policy and affinity management */
  39. #include <sched.h>
  40. static inline void drop_policy(void)
  41. {
  42. struct sched_param param;
  43. #ifdef SCHED_BATCH
  44. #ifdef SCHED_IDLE
  45. if (unlikely(sched_setscheduler(0, SCHED_IDLE, &param) == -1))
  46. #endif
  47. sched_setscheduler(0, SCHED_BATCH, &param);
  48. #endif
  49. }
  50. static inline void affine_to_cpu(int id, int cpu)
  51. {
  52. cpu_set_t set;
  53. CPU_ZERO(&set);
  54. CPU_SET(cpu, &set);
  55. sched_setaffinity(0, sizeof(&set), &set);
  56. applog(LOG_INFO, "Binding cpu mining thread %d to cpu %d", id, cpu);
  57. }
  58. #else
  59. static inline void drop_policy(void)
  60. {
  61. }
  62. static inline void affine_to_cpu(int id, int cpu)
  63. {
  64. }
  65. #endif
  66. enum workio_commands {
  67. WC_GET_WORK,
  68. WC_SUBMIT_WORK,
  69. WC_DIE,
  70. };
  71. struct workio_cmd {
  72. enum workio_commands cmd;
  73. struct thr_info *thr;
  74. union {
  75. struct work *work;
  76. } u;
  77. };
  78. enum sha256_algos {
  79. ALGO_C, /* plain C */
  80. ALGO_4WAY, /* parallel SSE2 */
  81. ALGO_VIA, /* VIA padlock */
  82. ALGO_CRYPTOPP, /* Crypto++ (C) */
  83. ALGO_CRYPTOPP_ASM32, /* Crypto++ 32-bit assembly */
  84. ALGO_SSE2_64, /* SSE2 for x86_64 */
  85. };
  86. static const char *algo_names[] = {
  87. [ALGO_C] = "c",
  88. #ifdef WANT_SSE2_4WAY
  89. [ALGO_4WAY] = "4way",
  90. #endif
  91. #ifdef WANT_VIA_PADLOCK
  92. [ALGO_VIA] = "via",
  93. #endif
  94. [ALGO_CRYPTOPP] = "cryptopp",
  95. #ifdef WANT_CRYPTOPP_ASM32
  96. [ALGO_CRYPTOPP_ASM32] = "cryptopp_asm32",
  97. #endif
  98. #ifdef WANT_X8664_SSE2
  99. [ALGO_SSE2_64] = "sse2_64",
  100. #endif
  101. };
  102. bool opt_debug = false;
  103. bool opt_protocol = false;
  104. bool want_longpoll = true;
  105. bool have_longpoll = false;
  106. bool use_syslog = false;
  107. static bool opt_quiet = false;
  108. static int opt_retries = -1;
  109. static int opt_fail_pause = 5;
  110. static int opt_log_interval = 5;
  111. bool opt_log_output = false;
  112. static int opt_queue = 1;
  113. int opt_vectors;
  114. int opt_worksize;
  115. int opt_scantime = 60;
  116. static const bool opt_time = true;
  117. #ifdef WANT_X8664_SSE2
  118. static enum sha256_algos opt_algo = ALGO_SSE2_64;
  119. #else
  120. static enum sha256_algos opt_algo = ALGO_C;
  121. #endif
  122. static int nDevs;
  123. static int opt_g_threads = 2;
  124. static int opt_device;
  125. static int total_devices;
  126. static bool gpu_devices[16];
  127. static int gpu_threads;
  128. static bool forced_n_threads;
  129. static int opt_n_threads;
  130. static int mining_threads;
  131. static int num_processors;
  132. static int scan_intensity = 4;
  133. static char *rpc_url;
  134. static char *rpc_userpass;
  135. static char *rpc_user, *rpc_pass;
  136. struct thr_info *thr_info;
  137. static int work_thr_id;
  138. int longpoll_thr_id;
  139. static int stage_thr_id;
  140. struct work_restart *work_restart = NULL;
  141. static pthread_mutex_t hash_lock;
  142. static pthread_mutex_t qd_lock;
  143. static pthread_mutex_t stgd_lock;
  144. static pthread_mutex_t curses_lock;
  145. static double total_mhashes_done;
  146. static struct timeval total_tv_start, total_tv_end;
  147. static int accepted, rejected;
  148. int hw_errors;
  149. static int total_queued, total_staged, lp_staged;
  150. static bool localgen = false;
  151. static unsigned int getwork_requested;
  152. static char current_block[37];
  153. static char longpoll_block[37];
  154. static char blank[37];
  155. static void applog_and_exit(const char *fmt, ...)
  156. {
  157. va_list ap;
  158. va_start(ap, fmt);
  159. vapplog(LOG_ERR, fmt, ap);
  160. va_end(ap);
  161. exit(1);
  162. }
  163. /* FIXME: Use asprintf for better errors. */
  164. static char *set_algo(const char *arg, enum sha256_algos *algo)
  165. {
  166. enum sha256_algos i;
  167. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  168. if (algo_names[i] && !strcmp(arg, algo_names[i])) {
  169. *algo = i;
  170. return NULL;
  171. }
  172. }
  173. return "Unknown algorithm";
  174. }
  175. static void show_algo(char buf[OPT_SHOW_LEN], const enum sha256_algos *algo)
  176. {
  177. strncpy(buf, algo_names[*algo], OPT_SHOW_LEN);
  178. }
  179. static char *set_int_range(const char *arg, int *i, int min, int max)
  180. {
  181. char *err = opt_set_intval(arg, i);
  182. if (err)
  183. return err;
  184. if (*i < min || *i > max)
  185. return "Value out of range";
  186. return NULL;
  187. }
  188. static char *set_int_0_to_9999(const char *arg, int *i)
  189. {
  190. return set_int_range(arg, i, 0, 9999);
  191. }
  192. static char *set_int_0_to_14(const char *arg, int *i)
  193. {
  194. return set_int_range(arg, i, 0, 14);
  195. }
  196. static char *force_nthreads_int(const char *arg, int *i)
  197. {
  198. forced_n_threads = true;
  199. return set_int_range(arg, i, 0, 9999);
  200. }
  201. static char *set_int_0_to_10(const char *arg, int *i)
  202. {
  203. return set_int_range(arg, i, 0, 10);
  204. }
  205. static char *set_int_1_to_10(const char *arg, int *i)
  206. {
  207. return set_int_range(arg, i, 1, 10);
  208. }
  209. static char *set_devices(const char *arg, int *i)
  210. {
  211. char *err = opt_set_intval(arg, i);
  212. if (err)
  213. return err;
  214. if (*i < 0 || *i > 15)
  215. return "Invalid GPU device number";
  216. total_devices++;
  217. gpu_devices[*i] = true;
  218. return NULL;
  219. }
  220. static char *set_url(const char *arg, char **p)
  221. {
  222. opt_set_charp(arg, p);
  223. if (strncmp(arg, "http://", 7) &&
  224. strncmp(arg, "https://", 8))
  225. return "URL must start with http:// or https://";
  226. return NULL;
  227. }
  228. static char *set_vector(const char *arg, int *i)
  229. {
  230. char *err = opt_set_intval(arg, i);
  231. if (err)
  232. return err;
  233. if (*i != 1 && *i != 2 && *i != 4)
  234. return "Valid vectors are 1, 2 or 4";
  235. return NULL;
  236. }
  237. static char *enable_debug(bool *flag)
  238. {
  239. *flag = true;
  240. /* Turn out verbose output, too. */
  241. opt_log_output = true;
  242. return NULL;
  243. }
  244. /* These options are available from config file or commandline */
  245. static struct opt_table opt_config_table[] = {
  246. OPT_WITH_ARG("--algo|-a",
  247. set_algo, show_algo, &opt_algo,
  248. "Specify sha256 implementation:\n"
  249. "\tc\t\tLinux kernel sha256, implemented in C"
  250. #ifdef WANT_SSE2_4WAY
  251. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  252. #endif
  253. #ifdef WANT_VIA_PADLOCK
  254. "\n\tvia\t\tVIA padlock implementation"
  255. #endif
  256. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  257. #ifdef WANT_CRYPTOPP_ASM32
  258. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  259. #endif
  260. #ifdef WANT_X8664_SSE2
  261. "\n\tsse2_64\t\tSSE2 implementation for x86_64 machines"
  262. #endif
  263. ),
  264. OPT_WITH_ARG("--cpu-threads|-t",
  265. force_nthreads_int, opt_show_intval, &opt_n_threads,
  266. "Number of miner CPU threads"),
  267. OPT_WITHOUT_ARG("--debug|-D",
  268. enable_debug, &opt_debug,
  269. "Enable debug output"),
  270. #ifdef HAVE_OPENCL
  271. OPT_WITH_ARG("--device|-d",
  272. set_devices, NULL, &opt_device,
  273. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  274. OPT_WITH_ARG("--gpu-threads|-g",
  275. set_int_0_to_10, opt_show_intval, &opt_g_threads,
  276. "Number of threads per GPU (0 - 10)"),
  277. OPT_WITH_ARG("--intensity|-I",
  278. set_int_0_to_14, opt_show_intval, &scan_intensity,
  279. "Intensity of GPU scanning (0 - 14)"),
  280. #endif
  281. OPT_WITH_ARG("--log|-l",
  282. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  283. "Interval in seconds between log output"),
  284. OPT_WITHOUT_ARG("--no-longpoll",
  285. opt_set_invbool, &want_longpoll,
  286. "Disable X-Long-Polling support"),
  287. OPT_WITH_ARG("--pass|-p",
  288. opt_set_charp, NULL, &rpc_pass,
  289. "Password for bitcoin JSON-RPC server"),
  290. OPT_WITHOUT_ARG("--protocol-dump|-P",
  291. opt_set_bool, &opt_protocol,
  292. "Verbose dump of protocol-level activities"),
  293. OPT_WITH_ARG("--queue|-Q",
  294. set_int_1_to_10, opt_show_intval, &opt_queue,
  295. "Number of extra work items to queue (1 - 10)"),
  296. OPT_WITHOUT_ARG("--quiet|-q",
  297. opt_set_bool, &opt_quiet,
  298. "Disable per-thread hashmeter output"),
  299. OPT_WITH_ARG("--retries|-r",
  300. opt_set_intval, opt_show_intval, &opt_retries,
  301. "Number of times to retry before giving up, if JSON-RPC call fails (-1 means never)"),
  302. OPT_WITH_ARG("--retry-pause|-R",
  303. set_int_0_to_9999, opt_show_intval, &opt_fail_pause,
  304. "Number of seconds to pause, between retries"),
  305. OPT_WITH_ARG("--scan-time|-s",
  306. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  307. "Upper bound on time spent scanning current work, in seconds"),
  308. #ifdef HAVE_SYSLOG_H
  309. OPT_WITHOUT_ARG("--syslog",
  310. opt_set_bool, &use_syslog,
  311. "Use system log for output messages (default: standard error)"),
  312. #endif
  313. OPT_WITH_ARG("--url|-o",
  314. set_url, opt_show_charp, &rpc_url,
  315. "URL for bitcoin JSON-RPC server"),
  316. OPT_WITH_ARG("--user|-u",
  317. opt_set_charp, NULL, &rpc_user,
  318. "Username for bitcoin JSON-RPC server"),
  319. #ifdef HAVE_OPENCL
  320. OPT_WITH_ARG("--vectors|-v",
  321. set_vector, NULL, &opt_vectors,
  322. "Override detected optimal vector width (1, 2 or 4)"),
  323. #endif
  324. OPT_WITHOUT_ARG("--verbose",
  325. opt_set_bool, &opt_log_output,
  326. "Log verbose output to stderr as well as status output"),
  327. #ifdef HAVE_OPENCL
  328. OPT_WITH_ARG("--worksize|-w",
  329. set_int_0_to_9999, opt_show_intval, &opt_worksize,
  330. "Override detected optimal worksize"),
  331. #endif
  332. OPT_WITH_ARG("--userpass|-O",
  333. opt_set_charp, NULL, &rpc_userpass,
  334. "Username:Password pair for bitcoin JSON-RPC server"),
  335. OPT_ENDTABLE
  336. };
  337. static char *parse_config(json_t *config)
  338. {
  339. static char err_buf[200];
  340. json_t *val;
  341. struct opt_table *opt;
  342. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  343. char *p, *name;
  344. /* We don't handle subtables. */
  345. assert(!(opt->type & OPT_SUBTABLE));
  346. /* Pull apart the option name(s). */
  347. name = strdup(opt->names);
  348. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  349. char *err;
  350. /* Ignore short options. */
  351. if (p[1] != '-')
  352. continue;
  353. val = json_object_get(config, p+2);
  354. if (!val)
  355. continue;
  356. if ((opt->type & OPT_HASARG) && json_is_string(val)) {
  357. err = opt->cb_arg(json_string_value(val),
  358. opt->u.arg);
  359. } else if ((opt->type&OPT_NOARG) && json_is_true(val)) {
  360. err = opt->cb(opt->u.arg);
  361. } else {
  362. err = "Invalid value";
  363. }
  364. if (err) {
  365. sprintf(err_buf, "Parsing JSON option %s: %s",
  366. p, err);
  367. return err_buf;
  368. }
  369. }
  370. free(name);
  371. }
  372. return NULL;
  373. }
  374. static char *load_config(const char *arg, void *unused)
  375. {
  376. json_error_t err;
  377. json_t *config;
  378. config = json_load_file(arg, 0, &err);
  379. if (!json_is_object(config))
  380. return "JSON decode of file failed";
  381. /* Parse the config now, so we can override it. That can keep pointers
  382. * so don't free config object. */
  383. return parse_config(config);
  384. }
  385. static char *print_ndevs_and_exit(int *ndevs)
  386. {
  387. printf("%i", *ndevs);
  388. exit(*ndevs);
  389. }
  390. /* These options are available from commandline only */
  391. static struct opt_table opt_cmdline_table[] = {
  392. OPT_WITH_ARG("--config|-c",
  393. load_config, NULL, NULL,
  394. "Load a JSON-format configuration file\n"
  395. "See example-cfg.json for an example configuration."),
  396. OPT_WITHOUT_ARG("--help|-h",
  397. opt_usage_and_exit,
  398. #ifdef HAVE_OPENCL
  399. "\nBuilt with CPU and GPU mining support.\n\n",
  400. #else
  401. "\nBuilt with CPU mining support only.\n\n",
  402. #endif
  403. "Print this message"),
  404. OPT_WITHOUT_ARG("--ndevs|-n",
  405. print_ndevs_and_exit, &nDevs,
  406. "Display number of detected GPUs and exit"),
  407. OPT_ENDTABLE
  408. };
  409. static bool jobj_binary(const json_t *obj, const char *key,
  410. void *buf, size_t buflen)
  411. {
  412. const char *hexstr;
  413. json_t *tmp;
  414. tmp = json_object_get(obj, key);
  415. if (unlikely(!tmp)) {
  416. applog(LOG_ERR, "JSON key '%s' not found", key);
  417. return false;
  418. }
  419. hexstr = json_string_value(tmp);
  420. if (unlikely(!hexstr)) {
  421. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  422. return false;
  423. }
  424. if (!hex2bin(buf, hexstr, buflen))
  425. return false;
  426. return true;
  427. }
  428. static bool work_decode(const json_t *val, struct work *work)
  429. {
  430. if (unlikely(!jobj_binary(val, "midstate",
  431. work->midstate, sizeof(work->midstate)))) {
  432. applog(LOG_ERR, "JSON inval midstate");
  433. goto err_out;
  434. }
  435. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
  436. applog(LOG_ERR, "JSON inval data");
  437. goto err_out;
  438. }
  439. if (unlikely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1)))) {
  440. applog(LOG_ERR, "JSON inval hash1");
  441. goto err_out;
  442. }
  443. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
  444. applog(LOG_ERR, "JSON inval target");
  445. goto err_out;
  446. }
  447. memset(work->hash, 0, sizeof(work->hash));
  448. return true;
  449. err_out:
  450. return false;
  451. }
  452. static inline int gpu_from_thr_id(int thr_id)
  453. {
  454. return thr_id % nDevs;
  455. }
  456. static inline int cpu_from_thr_id(int thr_id)
  457. {
  458. return (thr_id - gpu_threads) % num_processors;
  459. }
  460. static WINDOW *mainwin, *statuswin, *logwin;
  461. static double total_secs = 0.1;
  462. static char statusline[256];
  463. static int cpucursor, gpucursor, logstart, logcursor;
  464. static bool curses_active = false;
  465. static struct cgpu_info *gpus, *cpus;
  466. static inline void print_status(int thr_id)
  467. {
  468. if (unlikely(!curses_active))
  469. return;
  470. pthread_mutex_lock(&curses_lock);
  471. wmove(statuswin, 0, 0);
  472. wattron(statuswin, A_BOLD);
  473. wprintw(statuswin, PROGRAM_NAME " version " VERSION);
  474. wattroff(statuswin, A_BOLD);
  475. wmove(statuswin, 1, 0);
  476. whline(statuswin, '-', 80);
  477. wmove(statuswin, 2,0);
  478. wprintw(statuswin, "Totals: %s", statusline);
  479. wclrtoeol(statuswin);
  480. wmove(statuswin, 3, 0);
  481. whline(statuswin, '-', 80);
  482. wmove(statuswin, logstart - 1, 0);
  483. whline(statuswin, '-', 80);
  484. if (thr_id >= 0 && thr_id < gpu_threads) {
  485. int gpu = gpu_from_thr_id(thr_id);
  486. struct cgpu_info *cgpu = &gpus[gpu];
  487. wmove(statuswin, gpucursor + gpu, 0);
  488. wprintw(statuswin, "GPU %d: [%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  489. gpu, cgpu->total_mhashes / total_secs,
  490. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  491. cgpu->efficiency, cgpu->utility);
  492. wclrtoeol(statuswin);
  493. } else if (thr_id >= gpu_threads) {
  494. int cpu = cpu_from_thr_id(thr_id);
  495. struct cgpu_info *cgpu = &cpus[cpu];
  496. wmove(statuswin, cpucursor + cpu, 0);
  497. wprintw(statuswin, "CPU %d: [%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  498. cpu, cgpu->total_mhashes / total_secs,
  499. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  500. cgpu->efficiency, cgpu->utility);
  501. wclrtoeol(statuswin);
  502. }
  503. wrefresh(statuswin);
  504. pthread_mutex_unlock(&curses_lock);
  505. }
  506. void log_curses(const char *f, va_list ap)
  507. {
  508. if (unlikely(!curses_active))
  509. return;
  510. pthread_mutex_lock(&curses_lock);
  511. vw_printw(logwin, f, ap);
  512. wrefresh(logwin);
  513. pthread_mutex_unlock(&curses_lock);
  514. }
  515. static bool submit_fail = false;
  516. static bool submit_upstream_work(const struct work *work)
  517. {
  518. char *hexstr = NULL;
  519. json_t *val, *res;
  520. char s[345];
  521. bool rc = false;
  522. struct cgpu_info *cgpu = thr_info[work->thr_id].cgpu;
  523. CURL *curl = curl_easy_init();
  524. if (unlikely(!curl)) {
  525. applog(LOG_ERR, "CURL initialisation failed");
  526. return rc;
  527. }
  528. /* build hex string */
  529. hexstr = bin2hex(work->data, sizeof(work->data));
  530. if (unlikely(!hexstr)) {
  531. applog(LOG_ERR, "submit_upstream_work OOM");
  532. goto out_nofree;
  533. }
  534. /* build JSON-RPC request */
  535. sprintf(s,
  536. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  537. hexstr);
  538. if (opt_debug)
  539. applog(LOG_DEBUG, "DBG: sending RPC call: %s", s);
  540. /* issue JSON-RPC request */
  541. val = json_rpc_call(curl, rpc_url, rpc_userpass, s, false, false);
  542. if (unlikely(!val)) {
  543. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  544. if (!submit_fail) {
  545. submit_fail = true;
  546. applog(LOG_WARNING, "Upstream communication failure, caching submissions");
  547. }
  548. goto out;
  549. } else if (submit_fail) {
  550. submit_fail = false;
  551. applog(LOG_WARNING, "Upstream communication resumed, submitting work");
  552. }
  553. res = json_object_get(val, "result");
  554. /* Theoretically threads could race when modifying accepted and
  555. * rejected values but the chance of two submits completing at the
  556. * same time is zero so there is no point adding extra locking */
  557. if (json_is_true(res)) {
  558. cgpu->accepted++;
  559. accepted++;
  560. if (opt_debug)
  561. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  562. if (!opt_quiet)
  563. applog(LOG_WARNING, "Share accepted from %sPU %d",
  564. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu);
  565. } else {
  566. cgpu->rejected++;
  567. rejected++;
  568. if (opt_debug)
  569. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  570. if (!opt_quiet)
  571. applog(LOG_WARNING, "Share rejected from %sPU %d",
  572. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu);
  573. }
  574. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  575. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  576. if (!opt_quiet)
  577. print_status(work->thr_id);
  578. applog(LOG_INFO, "%sPU %d Requested:%d Accepted:%d Rejected:%d HW errors:%d Efficiency:%.0f%% Utility:%.2f/m",
  579. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->getworks, cgpu->accepted,
  580. cgpu->rejected, cgpu->hw_errors, cgpu->efficiency, cgpu->utility);
  581. json_decref(val);
  582. rc = true;
  583. out:
  584. free(hexstr);
  585. out_nofree:
  586. curl_easy_cleanup(curl);
  587. return rc;
  588. }
  589. static const char *rpc_req =
  590. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  591. static bool get_upstream_work(struct work *work)
  592. {
  593. json_t *val;
  594. bool rc = false;
  595. CURL *curl = curl_easy_init();
  596. if (unlikely(!curl)) {
  597. applog(LOG_ERR, "CURL initialisation failed");
  598. return rc;
  599. }
  600. val = json_rpc_call(curl, rpc_url, rpc_userpass, rpc_req,
  601. want_longpoll, false);
  602. if (unlikely(!val)) {
  603. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  604. goto out;
  605. }
  606. rc = work_decode(json_object_get(val, "result"), work);
  607. json_decref(val);
  608. out:
  609. curl_easy_cleanup(curl);
  610. return rc;
  611. }
  612. static void workio_cmd_free(struct workio_cmd *wc)
  613. {
  614. if (!wc)
  615. return;
  616. switch (wc->cmd) {
  617. case WC_SUBMIT_WORK:
  618. free(wc->u.work);
  619. break;
  620. default: /* do nothing */
  621. break;
  622. }
  623. memset(wc, 0, sizeof(*wc)); /* poison */
  624. free(wc);
  625. }
  626. static void kill_work(void)
  627. {
  628. struct workio_cmd *wc;
  629. applog(LOG_INFO, "Received kill message");
  630. wc = calloc(1, sizeof(*wc));
  631. if (unlikely(!wc)) {
  632. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  633. /* We're just trying to die anyway, so forget graceful */
  634. exit (1);
  635. }
  636. wc->cmd = WC_DIE;
  637. wc->thr = 0;
  638. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  639. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  640. exit (1);
  641. }
  642. }
  643. static void *get_work_thread(void *userdata)
  644. {
  645. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  646. struct work *ret_work;
  647. int failures = 0;
  648. pthread_detach(pthread_self());
  649. ret_work = calloc(1, sizeof(*ret_work));
  650. if (unlikely(!ret_work)) {
  651. applog(LOG_ERR, "Failed to calloc ret_work in workio_get_work");
  652. kill_work();
  653. goto out;
  654. }
  655. /* obtain new work from bitcoin via JSON-RPC */
  656. while (!get_upstream_work(ret_work)) {
  657. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  658. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  659. free(ret_work);
  660. kill_work();
  661. goto out;
  662. }
  663. /* pause, then restart work-request loop */
  664. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  665. opt_fail_pause);
  666. sleep(opt_fail_pause);
  667. }
  668. /* send work to requesting thread */
  669. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  670. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  671. kill_work();
  672. free(ret_work);
  673. }
  674. out:
  675. workio_cmd_free(wc);
  676. return NULL;
  677. }
  678. static bool workio_get_work(struct workio_cmd *wc)
  679. {
  680. pthread_t get_thread;
  681. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  682. applog(LOG_ERR, "Failed to create get_work_thread");
  683. return false;
  684. }
  685. return true;
  686. }
  687. static void *submit_work_thread(void *userdata)
  688. {
  689. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  690. int failures = 0;
  691. char *hexstr;
  692. pthread_detach(pthread_self());
  693. hexstr = bin2hex(wc->u.work->data, 36);
  694. if (unlikely(!hexstr)) {
  695. applog(LOG_ERR, "submit_work_thread OOM");
  696. goto out;
  697. }
  698. if (unlikely(strncmp(hexstr, current_block, 36))) {
  699. applog(LOG_WARNING, "Stale work detected, discarding");
  700. goto out_free;
  701. }
  702. /* submit solution to bitcoin via JSON-RPC */
  703. while (!submit_upstream_work(wc->u.work)) {
  704. if (unlikely(strncmp(hexstr, current_block, 36))) {
  705. applog(LOG_WARNING, "Stale work detected, discarding");
  706. goto out_free;
  707. }
  708. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  709. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  710. kill_work();
  711. goto out_free;
  712. }
  713. /* pause, then restart work-request loop */
  714. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  715. opt_fail_pause);
  716. sleep(opt_fail_pause);
  717. }
  718. out_free:
  719. free(hexstr);
  720. out:
  721. workio_cmd_free(wc);
  722. return NULL;
  723. }
  724. static bool workio_submit_work(struct workio_cmd *wc)
  725. {
  726. pthread_t submit_thread;
  727. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  728. applog(LOG_ERR, "Failed to create submit_work_thread");
  729. return false;
  730. }
  731. return true;
  732. }
  733. static void inc_staged(int inc, bool lp)
  734. {
  735. pthread_mutex_lock(&stgd_lock);
  736. if (lp) {
  737. lp_staged += inc;
  738. total_staged += inc;
  739. } else if (lp_staged)
  740. lp_staged--;
  741. else
  742. total_staged += inc;
  743. pthread_mutex_unlock(&stgd_lock);
  744. }
  745. static void dec_staged(int inc)
  746. {
  747. pthread_mutex_lock(&stgd_lock);
  748. if (lp_staged)
  749. lp_staged -= inc;
  750. total_staged -= inc;
  751. pthread_mutex_unlock(&stgd_lock);
  752. }
  753. static int requests_staged(void)
  754. {
  755. int ret;
  756. pthread_mutex_lock(&stgd_lock);
  757. ret = total_staged;
  758. pthread_mutex_unlock(&stgd_lock);
  759. return ret;
  760. }
  761. static void *stage_thread(void *userdata)
  762. {
  763. struct thr_info *mythr = userdata;
  764. bool ok = true;
  765. while (ok) {
  766. struct work *work = NULL;
  767. char *hexstr;
  768. work = tq_pop(mythr->q, NULL);
  769. if (unlikely(!work)) {
  770. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  771. ok = false;
  772. break;
  773. }
  774. hexstr = bin2hex(work->data, 36);
  775. if (unlikely(!hexstr)) {
  776. applog(LOG_ERR, "stage_thread OOM");
  777. break;
  778. }
  779. /* current_block is blanked out on successful longpoll */
  780. if (likely(strncmp(current_block, blank, 36))) {
  781. if (unlikely(strncmp(hexstr, current_block, 36))) {
  782. if (want_longpoll)
  783. applog(LOG_WARNING, "New block detected, possible missed longpoll, flushing work queue");
  784. else
  785. applog(LOG_WARNING, "New block detected, flushing work queue");
  786. /* As we can't flush the work from here, signal
  787. * the wakeup thread to restart all the
  788. * threads */
  789. work_restart[stage_thr_id].restart = 1;
  790. }
  791. } else
  792. memcpy(longpoll_block, hexstr, 36);
  793. memcpy(current_block, hexstr, 36);
  794. free(hexstr);
  795. if (unlikely(!tq_push(thr_info[0].q, work))) {
  796. applog(LOG_ERR, "Failed to tq_push work in stage_thread");
  797. ok = false;
  798. break;
  799. }
  800. inc_staged(1, false);
  801. }
  802. tq_freeze(mythr->q);
  803. return NULL;
  804. }
  805. static void *workio_thread(void *userdata)
  806. {
  807. struct thr_info *mythr = userdata;
  808. bool ok = true;
  809. while (ok) {
  810. struct workio_cmd *wc;
  811. /* wait for workio_cmd sent to us, on our queue */
  812. wc = tq_pop(mythr->q, NULL);
  813. if (unlikely(!wc)) {
  814. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  815. ok = false;
  816. break;
  817. }
  818. /* process workio_cmd */
  819. switch (wc->cmd) {
  820. case WC_GET_WORK:
  821. ok = workio_get_work(wc);
  822. break;
  823. case WC_SUBMIT_WORK:
  824. ok = workio_submit_work(wc);
  825. break;
  826. case WC_DIE:
  827. default:
  828. ok = false;
  829. break;
  830. }
  831. }
  832. tq_freeze(mythr->q);
  833. return NULL;
  834. }
  835. static void hashmeter(int thr_id, struct timeval *diff,
  836. unsigned long hashes_done)
  837. {
  838. struct timeval temp_tv_end, total_diff;
  839. double khashes, secs;
  840. double local_secs;
  841. double utility, efficiency = 0.0;
  842. static double local_mhashes_done = 0;
  843. static double rolling_local = 0;
  844. double local_mhashes = (double)hashes_done / 1000000.0;
  845. /* Don't bother calculating anything if we're not displaying it */
  846. if (opt_quiet || !opt_log_interval)
  847. return;
  848. khashes = hashes_done / 1000.0;
  849. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  850. if (thr_id >= 0 && secs) {
  851. /* So we can call hashmeter from a non worker thread */
  852. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  853. if (opt_debug)
  854. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  855. thr_id, hashes_done, hashes_done / secs);
  856. cgpu->local_mhashes += local_mhashes;
  857. cgpu->total_mhashes += local_mhashes;
  858. }
  859. /* Totals are updated by all threads so can race without locking */
  860. pthread_mutex_lock(&hash_lock);
  861. gettimeofday(&temp_tv_end, NULL);
  862. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  863. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  864. total_mhashes_done += local_mhashes;
  865. local_mhashes_done += local_mhashes;
  866. if (total_diff.tv_sec < opt_log_interval)
  867. /* Only update the total every opt_log_interval seconds */
  868. goto out_unlock;
  869. gettimeofday(&total_tv_end, NULL);
  870. /* Use a rolling average by faking an exponential decay over 5 * log */
  871. rolling_local = ((rolling_local * 0.9) + local_mhashes_done) / 1.9;
  872. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  873. total_secs = (double)total_diff.tv_sec +
  874. ((double)total_diff.tv_usec / 1000000.0);
  875. utility = accepted / ( total_secs ? total_secs : 1 ) * 60;
  876. efficiency = getwork_requested ? accepted * 100.0 / getwork_requested : 0.0;
  877. sprintf(statusline, "[(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m] ",
  878. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  879. getwork_requested, accepted, rejected, hw_errors, efficiency, utility);
  880. print_status(thr_id);
  881. applog(LOG_INFO, "[Rate (%ds):%.1f (avg):%.2f Mhash/s] [Requested:%d Accepted:%d Rejected:%d HW errors:%d Efficiency:%.0f%% Utility:%.2f/m]",
  882. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  883. getwork_requested, accepted, rejected, hw_errors, efficiency, utility);
  884. local_mhashes_done = 0;
  885. out_unlock:
  886. pthread_mutex_unlock(&hash_lock);
  887. }
  888. /* This is overkill, but at least we'll know accurately how much work is
  889. * queued to prevent ever being left without work */
  890. static void inc_queued(void)
  891. {
  892. pthread_mutex_lock(&qd_lock);
  893. total_queued++;
  894. pthread_mutex_unlock(&qd_lock);
  895. }
  896. static void dec_queued(void)
  897. {
  898. pthread_mutex_lock(&qd_lock);
  899. total_queued--;
  900. pthread_mutex_unlock(&qd_lock);
  901. dec_staged(1);
  902. }
  903. static int requests_queued(void)
  904. {
  905. int ret;
  906. pthread_mutex_lock(&qd_lock);
  907. ret = total_queued;
  908. pthread_mutex_unlock(&qd_lock);
  909. return ret;
  910. }
  911. /* All work is queued flagged as being for thread 0 and then the mining thread
  912. * flags it as its own */
  913. static bool queue_request(void)
  914. {
  915. struct thr_info *thr = &thr_info[0];
  916. struct workio_cmd *wc;
  917. /* fill out work request message */
  918. wc = calloc(1, sizeof(*wc));
  919. if (unlikely(!wc)) {
  920. applog(LOG_ERR, "Failed to tq_pop in queue_request");
  921. return false;
  922. }
  923. wc->cmd = WC_GET_WORK;
  924. wc->thr = thr;
  925. /* send work request to workio thread */
  926. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  927. applog(LOG_ERR, "Failed to tq_push in queue_request");
  928. workio_cmd_free(wc);
  929. return false;
  930. }
  931. inc_queued();
  932. return true;
  933. }
  934. static bool discard_request(void)
  935. {
  936. struct thr_info *thr = &thr_info[0];
  937. struct work *work_heap;
  938. /* Just in case we fell in a hole and missed a queue filling */
  939. if (unlikely(!requests_queued())) {
  940. applog(LOG_WARNING, "Tried to discard_request with nil queued");
  941. return true;
  942. }
  943. work_heap = tq_pop(thr->q, NULL);
  944. if (unlikely(!work_heap)) {
  945. applog(LOG_ERR, "Failed to tq_pop in discard_request");
  946. return false;
  947. }
  948. free(work_heap);
  949. dec_queued();
  950. return true;
  951. }
  952. static void flush_requests(bool longpoll)
  953. {
  954. int i, extra;
  955. extra = requests_queued();
  956. /* When flushing from longpoll, we don't know the new work yet. When
  957. * not flushing from longpoll, the first work item is valid so do not
  958. * discard it */
  959. if (longpoll)
  960. memcpy(current_block, blank, 36);
  961. else
  962. extra--;
  963. /* Temporarily increase the staged count so that get_work thinks there
  964. * is work available instead of making threads reuse existing work */
  965. if (extra >= mining_threads)
  966. inc_staged(mining_threads, true);
  967. else
  968. inc_staged(extra, true);
  969. for (i = 0; i < extra; i++) {
  970. /* Queue a whole batch of new requests */
  971. if (unlikely(!queue_request())) {
  972. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  973. kill_work();
  974. break;
  975. }
  976. /* Pop off the old requests. Cancelling the requests would be better
  977. * but is tricky */
  978. if (unlikely(!discard_request())) {
  979. applog(LOG_ERR, "Failed to discard requests in flush_requests");
  980. kill_work();
  981. break;
  982. }
  983. }
  984. }
  985. static bool get_work(struct work *work, bool queued)
  986. {
  987. struct timeval now;
  988. struct timespec abstime = {};
  989. struct thr_info *thr = &thr_info[0];
  990. struct work *work_heap;
  991. bool ret = false;
  992. int failures = 0;
  993. getwork_requested++;
  994. retry:
  995. gettimeofday(&now, NULL);
  996. abstime.tv_sec = now.tv_sec + 60;
  997. if (unlikely(!queued && !queue_request())) {
  998. applog(LOG_WARNING, "Failed to queue_request in get_work");
  999. goto out;
  1000. }
  1001. if (!requests_staged()) {
  1002. uint32_t *work_ntime;
  1003. uint32_t ntime;
  1004. /* Only print this message once each time we shift to localgen */
  1005. if (!localgen)
  1006. applog(LOG_WARNING, "Server not providing work fast enough, generating work locally");
  1007. localgen = true;
  1008. work_ntime = (uint32_t *)(work->data + 68);
  1009. ntime = be32toh(*work_ntime);
  1010. ntime++;
  1011. *work_ntime = htobe32(ntime);
  1012. ret = true;
  1013. goto out;
  1014. } else if (localgen) {
  1015. localgen = false;
  1016. applog(LOG_WARNING, "Resumed retrieving work from server");
  1017. }
  1018. /* Wait for 1st response, or get cached response. We really should
  1019. * never time out on the pop request but something might go amiss :/
  1020. */
  1021. work_heap = tq_pop(thr->q, &abstime);
  1022. if (unlikely(!work_heap)) {
  1023. applog(LOG_INFO, "Failed to tq_pop in get_work");
  1024. goto out;
  1025. }
  1026. dec_queued();
  1027. memcpy(work, work_heap, sizeof(*work));
  1028. ret = true;
  1029. free(work_heap);
  1030. out:
  1031. if (unlikely(ret == false)) {
  1032. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  1033. applog(LOG_ERR, "Failed %d times to get_work");
  1034. return ret;
  1035. }
  1036. applog(LOG_DEBUG, "Retrying after %d seconds", opt_fail_pause);
  1037. sleep(opt_fail_pause);
  1038. goto retry;
  1039. }
  1040. return ret;
  1041. }
  1042. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  1043. {
  1044. struct workio_cmd *wc;
  1045. /* fill out work request message */
  1046. wc = calloc(1, sizeof(*wc));
  1047. if (unlikely(!wc)) {
  1048. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  1049. return false;
  1050. }
  1051. wc->u.work = malloc(sizeof(*work_in));
  1052. if (unlikely(!wc->u.work)) {
  1053. applog(LOG_ERR, "Failed to calloc work in submit_work_sync");
  1054. goto err_out;
  1055. }
  1056. wc->cmd = WC_SUBMIT_WORK;
  1057. wc->thr = thr;
  1058. memcpy(wc->u.work, work_in, sizeof(*work_in));
  1059. /* send solution to workio thread */
  1060. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1061. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  1062. goto err_out;
  1063. }
  1064. return true;
  1065. err_out:
  1066. workio_cmd_free(wc);
  1067. return false;
  1068. }
  1069. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  1070. {
  1071. work->data[64+12+0] = (nonce>>0) & 0xff;
  1072. work->data[64+12+1] = (nonce>>8) & 0xff;
  1073. work->data[64+12+2] = (nonce>>16) & 0xff;
  1074. work->data[64+12+3] = (nonce>>24) & 0xff;
  1075. return submit_work_sync(thr, work);
  1076. }
  1077. static void *miner_thread(void *userdata)
  1078. {
  1079. struct thr_info *mythr = userdata;
  1080. const int thr_id = mythr->id;
  1081. uint32_t max_nonce = 0xffffff;
  1082. bool needs_work = true;
  1083. /* Try to cycle approximately 5 times before each log update */
  1084. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1085. /* Request the next work item at 2/3 of the scantime */
  1086. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1087. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1088. bool requested = true;
  1089. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  1090. * and if that fails, then SCHED_BATCH. No need for this to be an
  1091. * error if it fails */
  1092. setpriority(PRIO_PROCESS, 0, 19);
  1093. drop_policy();
  1094. /* Cpu affinity only makes sense if the number of threads is a multiple
  1095. * of the number of CPUs */
  1096. if (!(opt_n_threads % num_processors))
  1097. affine_to_cpu(thr_id - gpu_threads, cpu_from_thr_id(thr_id));
  1098. while (1) {
  1099. struct work work __attribute__((aligned(128)));
  1100. unsigned long hashes_done;
  1101. struct timeval tv_workstart, tv_start, tv_end, diff;
  1102. uint64_t max64;
  1103. bool rc;
  1104. if (needs_work) {
  1105. gettimeofday(&tv_workstart, NULL);
  1106. /* obtain new work from internal workio thread */
  1107. if (unlikely(!get_work(&work, requested))) {
  1108. applog(LOG_ERR, "work retrieval failed, exiting "
  1109. "mining thread %d", thr_id);
  1110. goto out;
  1111. }
  1112. mythr->cgpu->getworks++;
  1113. work.thr_id = thr_id;
  1114. needs_work = requested = false;
  1115. work.blk.nonce = 0;
  1116. }
  1117. hashes_done = 0;
  1118. gettimeofday(&tv_start, NULL);
  1119. /* scan nonces for a proof-of-work hash */
  1120. switch (opt_algo) {
  1121. case ALGO_C:
  1122. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  1123. work.hash1, work.hash, work.target,
  1124. max_nonce, &hashes_done,
  1125. work.blk.nonce);
  1126. break;
  1127. #ifdef WANT_X8664_SSE2
  1128. case ALGO_SSE2_64: {
  1129. unsigned int rc5 =
  1130. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  1131. work.hash1, work.hash,
  1132. work.target,
  1133. max_nonce, &hashes_done,
  1134. work.blk.nonce);
  1135. rc = (rc5 == -1) ? false : true;
  1136. }
  1137. break;
  1138. #endif
  1139. #ifdef WANT_SSE2_4WAY
  1140. case ALGO_4WAY: {
  1141. unsigned int rc4 =
  1142. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  1143. work.hash1, work.hash,
  1144. work.target,
  1145. max_nonce, &hashes_done,
  1146. work.blk.nonce);
  1147. rc = (rc4 == -1) ? false : true;
  1148. }
  1149. break;
  1150. #endif
  1151. #ifdef WANT_VIA_PADLOCK
  1152. case ALGO_VIA:
  1153. rc = scanhash_via(thr_id, work.data, work.target,
  1154. max_nonce, &hashes_done,
  1155. work.blk.nonce);
  1156. break;
  1157. #endif
  1158. case ALGO_CRYPTOPP:
  1159. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  1160. work.hash1, work.hash, work.target,
  1161. max_nonce, &hashes_done,
  1162. work.blk.nonce);
  1163. break;
  1164. #ifdef WANT_CRYPTOPP_ASM32
  1165. case ALGO_CRYPTOPP_ASM32:
  1166. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  1167. work.hash1, work.hash, work.target,
  1168. max_nonce, &hashes_done,
  1169. work.blk.nonce);
  1170. break;
  1171. #endif
  1172. default:
  1173. /* should never happen */
  1174. goto out;
  1175. }
  1176. /* record scanhash elapsed time */
  1177. gettimeofday(&tv_end, NULL);
  1178. timeval_subtract(&diff, &tv_end, &tv_start);
  1179. hashes_done -= work.blk.nonce;
  1180. hashmeter(thr_id, &diff, hashes_done);
  1181. work.blk.nonce += hashes_done;
  1182. /* adjust max_nonce to meet target cycle time */
  1183. if (diff.tv_usec > 500000)
  1184. diff.tv_sec++;
  1185. if (diff.tv_sec && diff.tv_sec != cycle) {
  1186. max64 = work.blk.nonce +
  1187. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  1188. } else
  1189. max64 = work.blk.nonce + hashes_done;
  1190. if (max64 > 0xfffffffaULL)
  1191. max64 = 0xfffffffaULL;
  1192. max_nonce = max64;
  1193. /* if nonce found, submit work */
  1194. if (unlikely(rc)) {
  1195. if (opt_debug)
  1196. applog(LOG_DEBUG, "CPU %d found something?", cpu_from_thr_id(thr_id));
  1197. if (unlikely(!submit_work_sync(mythr, &work))) {
  1198. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  1199. break;
  1200. }
  1201. work.blk.nonce += 4;
  1202. }
  1203. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1204. if (!requested && (diff.tv_sec > request_interval || work.blk.nonce > request_nonce)) {
  1205. if (unlikely(!queue_request())) {
  1206. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  1207. goto out;
  1208. }
  1209. requested = true;
  1210. }
  1211. if (diff.tv_sec > opt_scantime || work_restart[thr_id].restart ||
  1212. work.blk.nonce >= MAXTHREADS - hashes_done)
  1213. needs_work = true;
  1214. }
  1215. out:
  1216. tq_freeze(mythr->q);
  1217. return NULL;
  1218. }
  1219. enum {
  1220. STAT_SLEEP_INTERVAL = 1,
  1221. STAT_CTR_INTERVAL = 10000000,
  1222. FAILURE_INTERVAL = 30,
  1223. };
  1224. #ifdef HAVE_OPENCL
  1225. static _clState *clStates[16];
  1226. static inline cl_int queue_kernel_parameters(_clState *clState, dev_blk_ctx *blk)
  1227. {
  1228. cl_kernel *kernel = &clState->kernel;
  1229. cl_int status = 0;
  1230. int num = 0;
  1231. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  1232. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  1233. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  1234. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  1235. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  1236. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  1237. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  1238. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  1239. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  1240. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  1241. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  1242. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  1243. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  1244. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  1245. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  1246. if (clState->hasBitAlign == true) {
  1247. /* Parameters for phatk kernel */
  1248. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2);
  1249. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  1250. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  1251. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4);
  1252. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1);
  1253. } else {
  1254. /* Parameters for poclbm kernel */
  1255. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  1256. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  1257. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  1258. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  1259. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  1260. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  1261. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  1262. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  1263. }
  1264. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  1265. (void *)&clState->outputBuffer);
  1266. return status;
  1267. }
  1268. static void *gpuminer_thread(void *userdata)
  1269. {
  1270. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1271. struct timeval tv_start, tv_end, diff;
  1272. struct thr_info *mythr = userdata;
  1273. const int thr_id = mythr->id;
  1274. uint32_t *res, *blank_res;
  1275. size_t globalThreads[1];
  1276. size_t localThreads[1];
  1277. cl_int status;
  1278. _clState *clState = clStates[thr_id];
  1279. const cl_kernel *kernel = &clState->kernel;
  1280. struct work *work = malloc(sizeof(struct work));
  1281. unsigned const int threads = 1 << (15 + scan_intensity);
  1282. unsigned const int vectors = clState->preferred_vwidth;
  1283. unsigned const int hashes = threads * vectors;
  1284. unsigned int hashes_done = 0;
  1285. /* Request the next work item at 2/3 of the scantime */
  1286. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1287. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1288. bool requested = true;
  1289. res = calloc(BUFFERSIZE, 1);
  1290. blank_res = calloc(BUFFERSIZE, 1);
  1291. if (!res || !blank_res) {
  1292. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  1293. goto out;
  1294. }
  1295. gettimeofday(&tv_start, NULL);
  1296. globalThreads[0] = threads;
  1297. localThreads[0] = clState->work_size;
  1298. diff.tv_sec = ~0UL;
  1299. gettimeofday(&tv_end, NULL);
  1300. while (1) {
  1301. struct timeval tv_workstart;
  1302. /* This finish flushes the readbuffer set with CL_FALSE later */
  1303. clFinish(clState->commandQueue);
  1304. if (diff.tv_sec > opt_scantime || work->blk.nonce >= MAXTHREADS - hashes || work_restart[thr_id].restart) {
  1305. /* Ignore any reads since we're getting new work and queue a clean buffer */
  1306. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1307. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1308. if (unlikely(status != CL_SUCCESS))
  1309. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1310. memset(res, 0, BUFFERSIZE);
  1311. gettimeofday(&tv_workstart, NULL);
  1312. /* obtain new work from internal workio thread */
  1313. if (unlikely(!get_work(work, requested))) {
  1314. applog(LOG_ERR, "work retrieval failed, exiting "
  1315. "gpu mining thread %d", mythr->id);
  1316. goto out;
  1317. }
  1318. mythr->cgpu->getworks++;
  1319. work->thr_id = thr_id;
  1320. requested = false;
  1321. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  1322. work->blk.nonce = 0;
  1323. work_restart[thr_id].restart = 0;
  1324. if (opt_debug)
  1325. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  1326. /* Flushes the writebuffer set with CL_FALSE above */
  1327. clFinish(clState->commandQueue);
  1328. }
  1329. status = queue_kernel_parameters(clState, &work->blk);
  1330. if (unlikely(status != CL_SUCCESS))
  1331. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  1332. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  1333. if (res[MAXBUFFERS]) {
  1334. /* Clear the buffer again */
  1335. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1336. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1337. if (unlikely(status != CL_SUCCESS))
  1338. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1339. if (opt_debug)
  1340. applog(LOG_DEBUG, "GPU %d found something?", gpu_from_thr_id(thr_id));
  1341. postcalc_hash_async(mythr, work, res);
  1342. memset(res, 0, BUFFERSIZE);
  1343. clFinish(clState->commandQueue);
  1344. }
  1345. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  1346. globalThreads, localThreads, 0, NULL, NULL);
  1347. if (unlikely(status != CL_SUCCESS))
  1348. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  1349. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1350. BUFFERSIZE, res, 0, NULL, NULL);
  1351. if (unlikely(status != CL_SUCCESS))
  1352. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  1353. gettimeofday(&tv_end, NULL);
  1354. timeval_subtract(&diff, &tv_end, &tv_start);
  1355. hashes_done += hashes;
  1356. work->blk.nonce += hashes;
  1357. if (diff.tv_usec > 500000)
  1358. diff.tv_sec++;
  1359. if (diff.tv_sec >= cycle) {
  1360. hashmeter(thr_id, &diff, hashes_done);
  1361. gettimeofday(&tv_start, NULL);
  1362. hashes_done = 0;
  1363. }
  1364. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1365. if (!requested && (diff.tv_sec > request_interval || work->blk.nonce > request_nonce)) {
  1366. if (unlikely(!queue_request())) {
  1367. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  1368. goto out;
  1369. }
  1370. requested = true;
  1371. }
  1372. }
  1373. out:
  1374. tq_freeze(mythr->q);
  1375. return NULL;
  1376. }
  1377. #endif /* HAVE_OPENCL */
  1378. static void restart_threads(bool longpoll)
  1379. {
  1380. int i;
  1381. /* Discard old queued requests and get new ones */
  1382. flush_requests(longpoll);
  1383. for (i = 0; i < mining_threads; i++)
  1384. work_restart[i].restart = 1;
  1385. }
  1386. static void *longpoll_thread(void *userdata)
  1387. {
  1388. struct thr_info *mythr = userdata;
  1389. CURL *curl = NULL;
  1390. char *copy_start, *hdr_path, *lp_url = NULL;
  1391. bool need_slash = false;
  1392. int failures = 0;
  1393. hdr_path = tq_pop(mythr->q, NULL);
  1394. if (!hdr_path)
  1395. goto out;
  1396. /* full URL */
  1397. if (strstr(hdr_path, "://")) {
  1398. lp_url = hdr_path;
  1399. hdr_path = NULL;
  1400. }
  1401. /* absolute path, on current server */
  1402. else {
  1403. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  1404. if (rpc_url[strlen(rpc_url) - 1] != '/')
  1405. need_slash = true;
  1406. lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  1407. if (!lp_url)
  1408. goto out;
  1409. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  1410. }
  1411. applog(LOG_INFO, "Long-polling activated for %s", lp_url);
  1412. curl = curl_easy_init();
  1413. if (unlikely(!curl)) {
  1414. applog(LOG_ERR, "CURL initialisation failed");
  1415. goto out;
  1416. }
  1417. while (1) {
  1418. json_t *val;
  1419. val = json_rpc_call(curl, lp_url, rpc_userpass, rpc_req,
  1420. false, true);
  1421. if (likely(val)) {
  1422. failures = 0;
  1423. json_decref(val);
  1424. /* Keep track of who ordered a restart_threads to make
  1425. * sure it's only done once per new block */
  1426. if (likely(!strncmp(longpoll_block, blank, 36) ||
  1427. !strncmp(longpoll_block, current_block, 36))) {
  1428. applog(LOG_WARNING, "LONGPOLL detected new block, flushing work queue");
  1429. restart_threads(true);
  1430. } else
  1431. applog(LOG_WARNING, "LONGPOLL received - new block detected and work flushed already");
  1432. } else {
  1433. if (failures++ < 10) {
  1434. sleep(30);
  1435. applog(LOG_WARNING,
  1436. "longpoll failed, sleeping for 30s");
  1437. } else {
  1438. applog(LOG_ERR,
  1439. "longpoll failed, ending thread");
  1440. goto out;
  1441. }
  1442. }
  1443. memcpy(longpoll_block, current_block, 36);
  1444. }
  1445. out:
  1446. free(hdr_path);
  1447. free(lp_url);
  1448. tq_freeze(mythr->q);
  1449. if (curl)
  1450. curl_easy_cleanup(curl);
  1451. return NULL;
  1452. }
  1453. /* Makes sure the hashmeter keeps going even if mining threads stall */
  1454. static void *wakeup_thread(void *userdata)
  1455. {
  1456. const unsigned int interval = opt_log_interval / 2 ? : 1;
  1457. struct timeval zero_tv;
  1458. memset(&zero_tv, 0, sizeof(struct timeval));
  1459. while (1) {
  1460. int x, y, logx, logy;
  1461. sleep(interval);
  1462. if (requests_queued() < opt_queue)
  1463. queue_request();
  1464. hashmeter(-1, &zero_tv, 0);
  1465. if (curses_active) {
  1466. pthread_mutex_lock(&curses_lock);
  1467. getmaxyx(mainwin, y, x);
  1468. getmaxyx(logwin, logy, logx);
  1469. y -= logcursor;
  1470. /* Detect screen size change */
  1471. if (x != logx || y != logy)
  1472. wresize(logwin, y, x);
  1473. redrawwin(logwin);
  1474. redrawwin(statuswin);
  1475. pthread_mutex_unlock(&curses_lock);
  1476. }
  1477. if (unlikely(work_restart[stage_thr_id].restart)) {
  1478. restart_threads(false);
  1479. work_restart[stage_thr_id].restart = 0;
  1480. }
  1481. }
  1482. return NULL;
  1483. }
  1484. int main (int argc, char *argv[])
  1485. {
  1486. struct thr_info *thr;
  1487. unsigned int i, j = 0, x, y;
  1488. char name[32];
  1489. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  1490. return 1;
  1491. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  1492. return 1;
  1493. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  1494. return 1;
  1495. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  1496. return 1;
  1497. for (i = 0; i < 36; i++) {
  1498. strcat(blank, "0");
  1499. strcat(current_block, "0");
  1500. strcat(longpoll_block, "0");
  1501. }
  1502. #ifdef WIN32
  1503. opt_n_threads = num_processors = 1;
  1504. #else
  1505. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  1506. opt_n_threads = num_processors;
  1507. #endif /* !WIN32 */
  1508. #ifdef HAVE_OPENCL
  1509. for (i = 0; i < 16; i++)
  1510. gpu_devices[i] = false;
  1511. nDevs = clDevicesNum();
  1512. if (nDevs < 0)
  1513. return 1;
  1514. #endif
  1515. if (nDevs)
  1516. opt_n_threads = 0;
  1517. rpc_url = strdup(DEF_RPC_URL);
  1518. /* parse command line */
  1519. opt_register_table(opt_config_table,
  1520. "Options for both config file and command line");
  1521. opt_register_table(opt_cmdline_table,
  1522. "Options for command line only");
  1523. opt_parse(&argc, argv, applog_and_exit);
  1524. if (argc != 1) {
  1525. applog(LOG_ERR, "Unexpected extra commandline arguments");
  1526. return 1;
  1527. }
  1528. if (total_devices) {
  1529. if (total_devices > nDevs) {
  1530. applog(LOG_ERR, "More devices specified than exist");
  1531. return 1;
  1532. }
  1533. for (i = 0; i < 16; i++)
  1534. if (gpu_devices[i] && i + 1 > nDevs) {
  1535. applog(LOG_ERR, "Command line options set a device that doesn't exist");
  1536. return 1;
  1537. }
  1538. gpu_threads = total_devices * opt_g_threads;
  1539. } else {
  1540. gpu_threads = nDevs * opt_g_threads;
  1541. for (i = 0; i < nDevs; i++)
  1542. gpu_devices[i] = true;
  1543. }
  1544. if (!gpu_threads && !forced_n_threads) {
  1545. /* Maybe they turned GPU off; restore default CPU threads. */
  1546. opt_n_threads = num_processors;
  1547. }
  1548. logcursor = 4;
  1549. mining_threads = opt_n_threads + gpu_threads;
  1550. gpucursor = logcursor;
  1551. cpucursor = gpucursor + nDevs;
  1552. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  1553. logcursor = logstart + 1;
  1554. if (!rpc_userpass) {
  1555. if (!rpc_user || !rpc_pass) {
  1556. applog(LOG_ERR, "No login credentials supplied");
  1557. return 1;
  1558. }
  1559. rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  1560. if (!rpc_userpass)
  1561. return 1;
  1562. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  1563. }
  1564. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  1565. return 1;
  1566. #ifdef HAVE_SYSLOG_H
  1567. if (use_syslog)
  1568. openlog("cpuminer", LOG_PID, LOG_USER);
  1569. #endif
  1570. work_restart = calloc(mining_threads + 4, sizeof(*work_restart));
  1571. if (!work_restart)
  1572. return 1;
  1573. thr_info = calloc(mining_threads + 4, sizeof(*thr));
  1574. if (!thr_info)
  1575. return 1;
  1576. /* init workio thread info */
  1577. work_thr_id = mining_threads;
  1578. thr = &thr_info[work_thr_id];
  1579. thr->id = work_thr_id;
  1580. thr->q = tq_new();
  1581. if (!thr->q)
  1582. return 1;
  1583. /* start work I/O thread */
  1584. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  1585. applog(LOG_ERR, "workio thread create failed");
  1586. return 1;
  1587. }
  1588. /* init longpoll thread info */
  1589. if (want_longpoll) {
  1590. longpoll_thr_id = mining_threads + 1;
  1591. thr = &thr_info[longpoll_thr_id];
  1592. thr->id = longpoll_thr_id;
  1593. thr->q = tq_new();
  1594. if (!thr->q)
  1595. return 1;
  1596. /* start longpoll thread */
  1597. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  1598. applog(LOG_ERR, "longpoll thread create failed");
  1599. return 1;
  1600. }
  1601. pthread_detach(thr->pth);
  1602. } else
  1603. longpoll_thr_id = -1;
  1604. gettimeofday(&total_tv_start, NULL);
  1605. gettimeofday(&total_tv_end, NULL);
  1606. if (opt_n_threads ) {
  1607. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  1608. if (unlikely(!cpus)) {
  1609. applog(LOG_ERR, "Failed to calloc cpus");
  1610. return 1;
  1611. }
  1612. }
  1613. if (gpu_threads) {
  1614. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  1615. if (unlikely(!gpus)) {
  1616. applog(LOG_ERR, "Failed to calloc gpus");
  1617. return 1;
  1618. }
  1619. }
  1620. stage_thr_id = mining_threads + 3;
  1621. thr = &thr_info[stage_thr_id];
  1622. thr->q = tq_new();
  1623. if (!thr->q)
  1624. return 1;
  1625. /* start stage thread */
  1626. if (pthread_create(&thr->pth, NULL, stage_thread, thr)) {
  1627. applog(LOG_ERR, "stage thread create failed");
  1628. return 1;
  1629. }
  1630. /* Flag the work as ready forcing the mining threads to wait till we
  1631. * actually put something into the queue */
  1632. inc_staged(mining_threads, true);
  1633. #ifdef HAVE_OPENCL
  1634. i = 0;
  1635. /* start GPU mining threads */
  1636. for (j = 0; j < nDevs * opt_g_threads; j++) {
  1637. int gpu = gpu_from_thr_id(j);
  1638. /* Skip devices not set to work */
  1639. if (!gpu_devices[gpu])
  1640. continue;
  1641. thr = &thr_info[i];
  1642. thr->id = i;
  1643. gpus[gpu].is_gpu = 1;
  1644. gpus[gpu].cpu_gpu = gpu;
  1645. thr->cgpu = &gpus[gpu];
  1646. thr->q = tq_new();
  1647. if (!thr->q) {
  1648. applog(LOG_ERR, "tq_new failed in starting gpu mining threads");
  1649. return 1;
  1650. }
  1651. applog(LOG_INFO, "Init GPU thread %i", i);
  1652. clStates[i] = initCl(gpu, name, sizeof(name));
  1653. if (!clStates[i]) {
  1654. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  1655. continue;
  1656. }
  1657. applog(LOG_INFO, "initCl() finished. Found %s", name);
  1658. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1659. applog(LOG_ERR, "thread %d create failed", i);
  1660. return 1;
  1661. }
  1662. pthread_detach(thr->pth);
  1663. i++;
  1664. }
  1665. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  1666. #endif
  1667. /* start CPU mining threads */
  1668. for (i = gpu_threads; i < mining_threads; i++) {
  1669. int cpu = cpu_from_thr_id(i);
  1670. thr = &thr_info[i];
  1671. thr->id = i;
  1672. cpus[cpu].cpu_gpu = cpu;
  1673. thr->cgpu = &cpus[cpu];
  1674. thr->q = tq_new();
  1675. if (!thr->q) {
  1676. applog(LOG_ERR, "tq_new failed in starting cpu mining threads");
  1677. return 1;
  1678. }
  1679. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1680. applog(LOG_ERR, "thread %d create failed", i);
  1681. return 1;
  1682. }
  1683. pthread_detach(thr->pth);
  1684. }
  1685. applog(LOG_INFO, "%d cpu miner threads started, "
  1686. "using SHA256 '%s' algorithm.",
  1687. opt_n_threads,
  1688. algo_names[opt_algo]);
  1689. thr = &thr_info[mining_threads + 2];
  1690. /* start wakeup thread */
  1691. if (pthread_create(&thr->pth, NULL, wakeup_thread, NULL)) {
  1692. applog(LOG_ERR, "wakeup thread create failed");
  1693. return 1;
  1694. }
  1695. /* Restart count as it will be wrong till all threads are started */
  1696. pthread_mutex_lock(&hash_lock);
  1697. gettimeofday(&total_tv_start, NULL);
  1698. gettimeofday(&total_tv_end, NULL);
  1699. total_mhashes_done = 0;
  1700. pthread_mutex_unlock(&hash_lock);
  1701. /* Set up the ncurses interface */
  1702. if (!opt_quiet) {
  1703. mainwin = initscr();
  1704. statuswin = newwin(logstart, 80, 0, 0);
  1705. getmaxyx(mainwin, y, x);
  1706. logwin = newwin(y - logcursor, 0, logcursor, 0);
  1707. idlok(logwin, true);
  1708. scrollok(logwin, true);
  1709. leaveok(logwin, true);
  1710. leaveok(statuswin, true);
  1711. curses_active = true;
  1712. for (i = 0; i < mining_threads; i++)
  1713. print_status(i);
  1714. }
  1715. /* Now that everything's ready put enough work in the queue */
  1716. for (i = 0; i < opt_queue + mining_threads; i++) {
  1717. if (unlikely(!queue_request())) {
  1718. applog(LOG_ERR, "Failed to queue_request in main");
  1719. return 1;
  1720. }
  1721. }
  1722. /* main loop - simply wait for workio thread to exit */
  1723. pthread_join(thr_info[work_thr_id].pth, NULL);
  1724. curl_global_cleanup();
  1725. if (gpu_threads)
  1726. free(gpus);
  1727. if (opt_n_threads)
  1728. free(cpus);
  1729. applog(LOG_INFO, "workio thread dead, exiting.");
  1730. if (curses_active) {
  1731. delwin(logwin);
  1732. delwin(statuswin);
  1733. endwin();
  1734. refresh();
  1735. }
  1736. return 0;
  1737. }