main.c 42 KB

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