main.c 42 KB

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