main.c 41 KB

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