main.c 43 KB

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