cpu-miner.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  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 "cpuminer-config.h"
  11. #define _GNU_SOURCE
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <stdbool.h>
  16. #include <stdint.h>
  17. #include <unistd.h>
  18. #include <sys/time.h>
  19. #include <time.h>
  20. #include <math.h>
  21. #ifndef WIN32
  22. #include <sys/resource.h>
  23. #endif
  24. #include <getopt.h>
  25. #include <jansson.h>
  26. #include <curl/curl.h>
  27. #include "compat.h"
  28. #include "miner.h"
  29. #include "findnonce.h"
  30. #include "ocl.h"
  31. #define PROGRAM_NAME "minerd"
  32. #define DEF_RPC_URL "http://127.0.0.1:8332/"
  33. #define DEF_RPC_USERNAME "rpcuser"
  34. #define DEF_RPC_PASSWORD "rpcpass"
  35. #define DEF_RPC_USERPASS DEF_RPC_USERNAME ":" DEF_RPC_PASSWORD
  36. #ifdef __linux /* Linux specific policy and affinity management */
  37. #include <sched.h>
  38. static inline void drop_policy(void)
  39. {
  40. struct sched_param param;
  41. #ifdef SCHED_IDLE
  42. if (unlikely(sched_setscheduler(0, SCHED_IDLE, &param) == -1))
  43. #endif
  44. #ifdef SCHED_BATCH
  45. sched_setscheduler(0, SCHED_BATCH, &param);
  46. #endif
  47. }
  48. static inline void affine_to_cpu(int id, int cpu)
  49. {
  50. cpu_set_t set;
  51. CPU_ZERO(&set);
  52. CPU_SET(cpu, &set);
  53. sched_setaffinity(0, sizeof(&set), &set);
  54. applog(LOG_INFO, "Binding thread %d to cpu %d", id, cpu);
  55. }
  56. #else
  57. static inline void drop_policy(void)
  58. {
  59. }
  60. static inline void affine_to_cpu(int id, int cpu)
  61. {
  62. }
  63. #endif
  64. enum workio_commands {
  65. WC_GET_WORK,
  66. WC_SUBMIT_WORK,
  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 = 10;
  107. static int opt_fail_pause = 30;
  108. int opt_scantime = 5;
  109. static json_t *opt_config;
  110. static const bool opt_time = true;
  111. #ifdef WANT_X8664_SSE2
  112. static enum sha256_algos opt_algo = ALGO_SSE2_64;
  113. #else
  114. static enum sha256_algos opt_algo = ALGO_C;
  115. #endif
  116. static int nDevs;
  117. static int opt_n_threads = 1;
  118. static int num_processors;
  119. static int scan_intensity = 5;
  120. static char *rpc_url;
  121. static char *rpc_userpass;
  122. static char *rpc_user, *rpc_pass;
  123. struct thr_info *thr_info;
  124. static int work_thr_id;
  125. int longpoll_thr_id;
  126. struct work_restart *work_restart = NULL;
  127. pthread_mutex_t time_lock;
  128. static pthread_mutex_t hash_lock;
  129. static unsigned long total_hashes_done;
  130. static struct timeval total_tv_start, total_tv_end;
  131. static int accepted, rejected;
  132. struct option_help {
  133. const char *name;
  134. const char *helptext;
  135. };
  136. static struct option_help options_help[] = {
  137. { "help",
  138. "(-h) Display this help text" },
  139. { "config FILE",
  140. "(-c FILE) JSON-format configuration file (default: none)\n"
  141. "See example-cfg.json for an example configuration." },
  142. { "algo XXX",
  143. "(-a XXX) Specify sha256 implementation:\n"
  144. "\tc\t\tLinux kernel sha256, implemented in C (default)"
  145. #ifdef WANT_SSE2_4WAY
  146. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  147. #endif
  148. #ifdef WANT_VIA_PADLOCK
  149. "\n\tvia\t\tVIA padlock implementation"
  150. #endif
  151. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  152. #ifdef WANT_CRYPTOPP_ASM32
  153. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  154. #endif
  155. #ifdef WANT_X8664_SSE2
  156. "\n\tsse2_64\t\tSSE2 implementation for x86_64 machines"
  157. #endif
  158. },
  159. { "quiet",
  160. "(-q) Disable per-thread hashmeter output (default: off)" },
  161. { "debug",
  162. "(-D) Enable debug output (default: off)" },
  163. { "intensity",
  164. "(-I) Intensity of scanning (0 - 16, default 5)" },
  165. { "ndevs",
  166. "(-n) Display number of detected GPUs" },
  167. { "no-longpoll",
  168. "Disable X-Long-Polling support (default: enabled)" },
  169. { "protocol-dump",
  170. "(-P) Verbose dump of protocol-level activities (default: off)" },
  171. { "retries N",
  172. "(-r N) Number of times to retry, if JSON-RPC call fails\n"
  173. "\t(default: 10; use -1 for \"never\")" },
  174. { "retry-pause N",
  175. "(-R N) Number of seconds to pause, between retries\n"
  176. "\t(default: 30)" },
  177. { "scantime N",
  178. "(-s N) Upper bound on time spent scanning current work,\n"
  179. "\tin seconds. (default: 5)" },
  180. #ifdef HAVE_SYSLOG_H
  181. { "syslog",
  182. "Use system log for output messages (default: standard error)" },
  183. #endif
  184. { "threads N",
  185. "(-t N) Number of miner CPU threads (default: number of processors)" },
  186. { "url URL",
  187. "URL for bitcoin JSON-RPC server "
  188. "(default: " DEF_RPC_URL ")" },
  189. { "userpass USERNAME:PASSWORD",
  190. "Username:Password pair for bitcoin JSON-RPC server "
  191. "(default: " DEF_RPC_USERPASS ")" },
  192. { "user USERNAME",
  193. "(-u USERNAME) Username for bitcoin JSON-RPC server "
  194. "(default: " DEF_RPC_USERNAME ")" },
  195. { "pass PASSWORD",
  196. "(-p PASSWORD) Password for bitcoin JSON-RPC server "
  197. "(default: " DEF_RPC_PASSWORD ")" },
  198. };
  199. static struct option options[] = {
  200. { "algo", 1, NULL, 'a' },
  201. { "config", 1, NULL, 'c' },
  202. { "debug", 0, NULL, 'D' },
  203. { "help", 0, NULL, 'h' },
  204. { "intensity", 1, NULL, 'I' },
  205. { "ndevs", 0, NULL, 'n' },
  206. { "no-longpoll", 0, NULL, 1003 },
  207. { "pass", 1, NULL, 'p' },
  208. { "protocol-dump", 0, NULL, 'P' },
  209. { "quiet", 0, NULL, 'q' },
  210. { "threads", 1, NULL, 't' },
  211. { "retries", 1, NULL, 'r' },
  212. { "retry-pause", 1, NULL, 'R' },
  213. { "scantime", 1, NULL, 's' },
  214. #ifdef HAVE_SYSLOG_H
  215. { "syslog", 0, NULL, 1004 },
  216. #endif
  217. { "url", 1, NULL, 1001 },
  218. { "user", 1, NULL, 'u' },
  219. { "userpass", 1, NULL, 1002 },
  220. };
  221. struct work {
  222. unsigned char data[128];
  223. unsigned char hash1[64];
  224. unsigned char midstate[32];
  225. unsigned char target[32];
  226. unsigned char hash[32];
  227. uint32_t output[1];
  228. uint32_t res_nonce;
  229. uint32_t valid;
  230. dev_blk_ctx blk;
  231. };
  232. static bool jobj_binary(const json_t *obj, const char *key,
  233. void *buf, size_t buflen)
  234. {
  235. const char *hexstr;
  236. json_t *tmp;
  237. tmp = json_object_get(obj, key);
  238. if (unlikely(!tmp)) {
  239. applog(LOG_ERR, "JSON key '%s' not found", key);
  240. return false;
  241. }
  242. hexstr = json_string_value(tmp);
  243. if (unlikely(!hexstr)) {
  244. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  245. return false;
  246. }
  247. if (!hex2bin(buf, hexstr, buflen))
  248. return false;
  249. return true;
  250. }
  251. static bool work_decode(const json_t *val, struct work *work)
  252. {
  253. if (unlikely(!jobj_binary(val, "midstate",
  254. work->midstate, sizeof(work->midstate)))) {
  255. applog(LOG_ERR, "JSON inval midstate");
  256. goto err_out;
  257. }
  258. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
  259. applog(LOG_ERR, "JSON inval data");
  260. goto err_out;
  261. }
  262. if (unlikely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1)))) {
  263. applog(LOG_ERR, "JSON inval hash1");
  264. goto err_out;
  265. }
  266. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
  267. applog(LOG_ERR, "JSON inval target");
  268. goto err_out;
  269. }
  270. memset(work->hash, 0, sizeof(work->hash));
  271. return true;
  272. err_out:
  273. return false;
  274. }
  275. static bool submit_upstream_work(CURL *curl, const struct work *work)
  276. {
  277. char *hexstr = NULL;
  278. json_t *val, *res;
  279. char s[345];
  280. bool rc = false;
  281. /* build hex string */
  282. hexstr = bin2hex(work->data, sizeof(work->data));
  283. if (unlikely(!hexstr)) {
  284. applog(LOG_ERR, "submit_upstream_work OOM");
  285. goto out;
  286. }
  287. /* build JSON-RPC request */
  288. sprintf(s,
  289. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  290. hexstr);
  291. if (opt_debug)
  292. applog(LOG_DEBUG, "DBG: sending RPC call: %s", s);
  293. /* issue JSON-RPC request */
  294. val = json_rpc_call(curl, rpc_url, rpc_userpass, s, false, false);
  295. if (unlikely(!val)) {
  296. applog(LOG_ERR, "submit_upstream_work json_rpc_call failed");
  297. goto out;
  298. }
  299. res = json_object_get(val, "result");
  300. if (json_is_true(res)) {
  301. accepted++;
  302. applog(LOG_INFO, "PROOF OF WORK RESULT: true (yay!!!)");
  303. } else {
  304. rejected++;
  305. applog(LOG_INFO, "PROOF OF WORK RESULT: false (booooo)");
  306. }
  307. json_decref(val);
  308. rc = true;
  309. out:
  310. free(hexstr);
  311. return rc;
  312. }
  313. static const char *rpc_req =
  314. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  315. static bool get_upstream_work(CURL *curl, struct work *work)
  316. {
  317. json_t *val;
  318. bool rc;
  319. val = json_rpc_call(curl, rpc_url, rpc_userpass, rpc_req,
  320. want_longpoll, false);
  321. if (!val)
  322. return false;
  323. rc = work_decode(json_object_get(val, "result"), work);
  324. json_decref(val);
  325. return rc;
  326. }
  327. static void workio_cmd_free(struct workio_cmd *wc)
  328. {
  329. if (!wc)
  330. return;
  331. switch (wc->cmd) {
  332. case WC_SUBMIT_WORK:
  333. free(wc->u.work);
  334. break;
  335. default: /* do nothing */
  336. break;
  337. }
  338. memset(wc, 0, sizeof(*wc)); /* poison */
  339. free(wc);
  340. }
  341. static bool workio_get_work(struct workio_cmd *wc, CURL *curl)
  342. {
  343. struct work *ret_work;
  344. int failures = 0;
  345. ret_work = calloc(1, sizeof(*ret_work));
  346. if (!ret_work)
  347. return false;
  348. /* obtain new work from bitcoin via JSON-RPC */
  349. while (!get_upstream_work(curl, ret_work)) {
  350. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  351. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  352. free(ret_work);
  353. return false;
  354. }
  355. /* pause, then restart work-request loop */
  356. applog(LOG_ERR, "json_rpc_call failed, retry after %d seconds",
  357. opt_fail_pause);
  358. sleep(opt_fail_pause);
  359. }
  360. /* send work to requesting thread */
  361. if (!tq_push(wc->thr->q, ret_work))
  362. free(ret_work);
  363. return true;
  364. }
  365. static bool workio_submit_work(struct workio_cmd *wc, CURL *curl)
  366. {
  367. int failures = 0;
  368. /* submit solution to bitcoin via JSON-RPC */
  369. while (!submit_upstream_work(curl, wc->u.work)) {
  370. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  371. applog(LOG_ERR, "...terminating workio thread");
  372. return false;
  373. }
  374. /* pause, then restart work-request loop */
  375. applog(LOG_ERR, "...retry after %d seconds",
  376. opt_fail_pause);
  377. sleep(opt_fail_pause);
  378. }
  379. return true;
  380. }
  381. static void *workio_thread(void *userdata)
  382. {
  383. struct thr_info *mythr = userdata;
  384. CURL *curl;
  385. bool ok = true;
  386. curl = curl_easy_init();
  387. if (unlikely(!curl)) {
  388. applog(LOG_ERR, "CURL initialization failed");
  389. return NULL;
  390. }
  391. while (ok) {
  392. struct workio_cmd *wc;
  393. /* wait for workio_cmd sent to us, on our queue */
  394. wc = tq_pop(mythr->q, NULL);
  395. if (!wc) {
  396. ok = false;
  397. break;
  398. }
  399. /* process workio_cmd */
  400. switch (wc->cmd) {
  401. case WC_GET_WORK:
  402. ok = workio_get_work(wc, curl);
  403. break;
  404. case WC_SUBMIT_WORK:
  405. ok = workio_submit_work(wc, curl);
  406. break;
  407. default: /* should never happen */
  408. ok = false;
  409. break;
  410. }
  411. workio_cmd_free(wc);
  412. }
  413. tq_freeze(mythr->q);
  414. curl_easy_cleanup(curl);
  415. return NULL;
  416. }
  417. static void hashmeter(int thr_id, struct timeval *diff,
  418. unsigned long hashes_done)
  419. {
  420. struct timeval temp_tv_end, total_diff;
  421. double khashes, secs;
  422. double total_mhashes, total_secs;
  423. /* Don't bother calculating anything if we're not displaying it */
  424. if (opt_quiet)
  425. return;
  426. khashes = hashes_done / 1000.0;
  427. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  428. if (opt_debug)
  429. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  430. thr_id, hashes_done, hashes_done / secs);
  431. gettimeofday(&temp_tv_end, NULL);
  432. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  433. if (opt_n_threads + nDevs > 1) {
  434. /* Totals are updated by all threads so can race without locking */
  435. pthread_mutex_lock(&hash_lock);
  436. total_hashes_done += hashes_done;
  437. if (total_diff.tv_sec < 5) {
  438. /* Only update the total every 5 seconds */
  439. pthread_mutex_unlock(&hash_lock);
  440. return;
  441. }
  442. gettimeofday(&total_tv_end, NULL);
  443. pthread_mutex_unlock(&hash_lock);
  444. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  445. total_mhashes = total_hashes_done / 1000000.0;
  446. total_secs = (double)total_diff.tv_sec +
  447. ((double)total_diff.tv_usec / 1000000.0);
  448. applog(LOG_INFO, "[%.2f Mhash/sec] [%d Accepted] [%d Rejected]",
  449. total_mhashes / total_secs, accepted, rejected);
  450. } else {
  451. total_hashes_done += hashes_done;
  452. if (total_diff.tv_sec < 5) {
  453. /* Only update the total every 5 seconds */
  454. pthread_mutex_unlock(&hash_lock);
  455. return;
  456. }
  457. gettimeofday(&total_tv_end, NULL);
  458. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  459. total_mhashes = total_hashes_done / 1000000.0;
  460. total_secs = (double)total_diff.tv_sec +
  461. ((double)total_diff.tv_usec / 1000000.0);
  462. applog(LOG_INFO, "[%.2f Mhash/sec] [%d Accepted] [%d Rejected]",
  463. total_mhashes / total_secs, accepted, rejected);
  464. }
  465. }
  466. static bool get_work(struct thr_info *thr, struct work *work)
  467. {
  468. struct workio_cmd *wc;
  469. struct work *work_heap;
  470. /* fill out work request message */
  471. wc = calloc(1, sizeof(*wc));
  472. if (!wc)
  473. return false;
  474. wc->cmd = WC_GET_WORK;
  475. wc->thr = thr;
  476. /* send work request to workio thread */
  477. if (!tq_push(thr_info[work_thr_id].q, wc)) {
  478. workio_cmd_free(wc);
  479. return false;
  480. }
  481. /* wait for response, a unit of work */
  482. work_heap = tq_pop(thr->q, NULL);
  483. if (!work_heap)
  484. return false;
  485. /* copy returned work into storage provided by caller */
  486. memcpy(work, work_heap, sizeof(*work));
  487. free(work_heap);
  488. return true;
  489. }
  490. static bool submit_work(struct thr_info *thr, const struct work *work_in)
  491. {
  492. struct workio_cmd *wc;
  493. /* fill out work request message */
  494. wc = calloc(1, sizeof(*wc));
  495. if (!wc)
  496. return false;
  497. wc->u.work = malloc(sizeof(*work_in));
  498. if (!wc->u.work)
  499. goto err_out;
  500. wc->cmd = WC_SUBMIT_WORK;
  501. wc->thr = thr;
  502. memcpy(wc->u.work, work_in, sizeof(*work_in));
  503. /* send solution to workio thread */
  504. if (!tq_push(thr_info[work_thr_id].q, wc))
  505. goto err_out;
  506. return true;
  507. err_out:
  508. workio_cmd_free(wc);
  509. return false;
  510. }
  511. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  512. {
  513. work->data[64+12+0] = (nonce>>0) & 0xff;
  514. work->data[64+12+1] = (nonce>>8) & 0xff;
  515. work->data[64+12+2] = (nonce>>16) & 0xff;
  516. work->data[64+12+3] = (nonce>>24) & 0xff;
  517. return submit_work(thr, work);
  518. }
  519. static inline int cpu_from_thr_id(int thr_id)
  520. {
  521. return (thr_id - nDevs) % num_processors;
  522. }
  523. static void *miner_thread(void *userdata)
  524. {
  525. struct thr_info *mythr = userdata;
  526. int thr_id = mythr->id;
  527. uint32_t max_nonce = 0xffffff;
  528. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  529. * and if that fails, then SCHED_BATCH. No need for this to be an
  530. * error if it fails */
  531. setpriority(PRIO_PROCESS, 0, 19);
  532. drop_policy();
  533. /* Cpu affinity only makes sense if the number of threads is a multiple
  534. * of the number of CPUs */
  535. if (!(opt_n_threads % num_processors))
  536. affine_to_cpu(mythr->id, mythr->id % num_processors);
  537. while (1) {
  538. struct work work __attribute__((aligned(128)));
  539. unsigned long hashes_done;
  540. struct timeval tv_start, tv_end, diff;
  541. uint64_t max64;
  542. bool rc;
  543. /* obtain new work from internal workio thread */
  544. if (unlikely(!get_work(mythr, &work))) {
  545. applog(LOG_ERR, "work retrieval failed, exiting "
  546. "mining thread %d", mythr->id);
  547. goto out;
  548. }
  549. hashes_done = 0;
  550. gettimeofday(&tv_start, NULL);
  551. /* scan nonces for a proof-of-work hash */
  552. switch (opt_algo) {
  553. case ALGO_C:
  554. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  555. work.hash1, work.hash, work.target,
  556. max_nonce, &hashes_done);
  557. break;
  558. #ifdef WANT_X8664_SSE2
  559. case ALGO_SSE2_64: {
  560. unsigned int rc5 =
  561. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  562. work.hash1, work.hash,
  563. work.target,
  564. max_nonce, &hashes_done);
  565. rc = (rc5 == -1) ? false : true;
  566. }
  567. break;
  568. #endif
  569. #ifdef WANT_SSE2_4WAY
  570. case ALGO_4WAY: {
  571. unsigned int rc4 =
  572. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  573. work.hash1, work.hash,
  574. work.target,
  575. max_nonce, &hashes_done);
  576. rc = (rc4 == -1) ? false : true;
  577. }
  578. break;
  579. #endif
  580. #ifdef WANT_VIA_PADLOCK
  581. case ALGO_VIA:
  582. rc = scanhash_via(thr_id, work.data, work.target,
  583. max_nonce, &hashes_done);
  584. break;
  585. #endif
  586. case ALGO_CRYPTOPP:
  587. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  588. work.hash1, work.hash, work.target,
  589. max_nonce, &hashes_done);
  590. break;
  591. #ifdef WANT_CRYPTOPP_ASM32
  592. case ALGO_CRYPTOPP_ASM32:
  593. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  594. work.hash1, work.hash, work.target,
  595. max_nonce, &hashes_done);
  596. break;
  597. #endif
  598. default:
  599. /* should never happen */
  600. goto out;
  601. }
  602. /* record scanhash elapsed time */
  603. gettimeofday(&tv_end, NULL);
  604. timeval_subtract(&diff, &tv_end, &tv_start);
  605. hashmeter(thr_id, &diff, hashes_done);
  606. /* adjust max_nonce to meet target scan time */
  607. if (diff.tv_usec > 500000)
  608. diff.tv_sec++;
  609. if (diff.tv_sec > 0) {
  610. max64 =
  611. ((uint64_t)hashes_done * opt_scantime) / diff.tv_sec;
  612. if (max64 > 0xfffffffaULL)
  613. max64 = 0xfffffffaULL;
  614. max_nonce = max64;
  615. }
  616. /* if nonce found, submit work */
  617. if (unlikely(rc)) {
  618. applog(LOG_INFO, "CPU %d found something?", cpu_from_thr_id(thr_id));
  619. if (!submit_work(mythr, &work))
  620. break;
  621. }
  622. }
  623. out:
  624. tq_freeze(mythr->q);
  625. return NULL;
  626. }
  627. enum {
  628. STAT_SLEEP_INTERVAL = 1,
  629. STAT_CTR_INTERVAL = 10000000,
  630. FAILURE_INTERVAL = 30,
  631. };
  632. static _clState *clStates[16];
  633. static inline cl_int queue_kernel_parameters(dev_blk_ctx *blk, cl_kernel *kernel,
  634. struct _cl_mem *output)
  635. {
  636. cl_int status = 0;
  637. int num = 0;
  638. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  639. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  640. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  641. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  642. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  643. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  644. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  645. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  646. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  647. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  648. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  649. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  650. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  651. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  652. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  653. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  654. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  655. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  656. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  657. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  658. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  659. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  660. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  661. status |= clSetKernelArg(*kernel, num++, sizeof(output), (void *)&output);
  662. return status;
  663. }
  664. static inline int gpu_from_thr_id(int thr_id)
  665. {
  666. return thr_id;
  667. }
  668. static void *gpuminer_thread(void *userdata)
  669. {
  670. struct thr_info *mythr = userdata;
  671. struct timeval tv_start;
  672. int thr_id = mythr->id;
  673. uint32_t res[128], blank_res[128];
  674. cl_kernel *kernel;
  675. memset(blank_res, 0, BUFFERSIZE);
  676. size_t globalThreads[1];
  677. size_t localThreads[1];
  678. cl_int status;
  679. _clState *clState = clStates[thr_id];
  680. kernel = &clState->kernel;
  681. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  682. BUFFERSIZE, blank_res, 0, NULL, NULL);
  683. if (unlikely(status != CL_SUCCESS))
  684. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  685. struct work *work = malloc(sizeof(struct work));
  686. bool need_work = true;
  687. unsigned int threads = 1 << (15 + scan_intensity);
  688. unsigned int vectors = preferred_vwidth;
  689. unsigned int hashes_done = threads * vectors;
  690. gettimeofday(&tv_start, NULL);
  691. globalThreads[0] = threads;
  692. localThreads[0] = max_work_size / vectors;
  693. while (1) {
  694. struct timeval tv_end, diff;
  695. unsigned int i;
  696. clFinish(clState->commandQueue);
  697. if (need_work) {
  698. /* obtain new work from internal workio thread */
  699. if (unlikely(!get_work(mythr, work))) {
  700. applog(LOG_ERR, "work retrieval failed, exiting "
  701. "gpu mining thread %d", mythr->id);
  702. goto out;
  703. }
  704. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  705. work->blk.nonce = 0;
  706. status = queue_kernel_parameters(&work->blk, kernel, clState->outputBuffer);
  707. if (unlikely(status != CL_SUCCESS))
  708. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); exit (1); }
  709. work_restart[thr_id].restart = 0;
  710. need_work = false;
  711. if (opt_debug)
  712. applog(LOG_DEBUG, "getwork");
  713. } else {
  714. status = clSetKernelArg(*kernel, 14, sizeof(uint), (void *)&work->blk.nonce);
  715. if (unlikely(status != CL_SUCCESS))
  716. { applog(LOG_ERR, "Error: clSetKernelArg of nonce failed."); goto out; }
  717. }
  718. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  719. globalThreads, localThreads, 0, NULL, NULL);
  720. if (unlikely(status != CL_SUCCESS))
  721. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  722. /* 127 is used as a flag to say nonces exist */
  723. if (unlikely(res[127])) {
  724. /* Clear the buffer again */
  725. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  726. BUFFERSIZE, blank_res, 0, NULL, NULL);
  727. if (unlikely(status != CL_SUCCESS))
  728. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  729. for (i = 0; i < 127; i++) {
  730. if (res[i]) {
  731. applog(LOG_INFO, "GPU %d found something?", gpu_from_thr_id(thr_id));
  732. postcalc_hash(mythr, &work->blk, work, res[i]);
  733. } else
  734. break;
  735. }
  736. clFinish(clState->commandQueue);
  737. }
  738. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  739. BUFFERSIZE, res, 0, NULL, NULL);
  740. if (unlikely(status != CL_SUCCESS))
  741. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  742. gettimeofday(&tv_end, NULL);
  743. timeval_subtract(&diff, &tv_end, &tv_start);
  744. hashmeter(thr_id, &diff, hashes_done);
  745. gettimeofday(&tv_start, NULL);
  746. work->blk.nonce += hashes_done;
  747. if (unlikely(work->blk.nonce > MAXTHREADS - hashes_done) ||
  748. (work_restart[thr_id].restart))
  749. need_work = true;
  750. }
  751. out:
  752. tq_freeze(mythr->q);
  753. return NULL;
  754. }
  755. static void restart_threads(void)
  756. {
  757. int i;
  758. for (i = 0; i < opt_n_threads + nDevs; i++)
  759. work_restart[i].restart = 1;
  760. }
  761. static void *longpoll_thread(void *userdata)
  762. {
  763. struct thr_info *mythr = userdata;
  764. CURL *curl = NULL;
  765. char *copy_start, *hdr_path, *lp_url = NULL;
  766. bool need_slash = false;
  767. int failures = 0;
  768. hdr_path = tq_pop(mythr->q, NULL);
  769. if (!hdr_path)
  770. goto out;
  771. /* full URL */
  772. if (strstr(hdr_path, "://")) {
  773. lp_url = hdr_path;
  774. hdr_path = NULL;
  775. }
  776. /* absolute path, on current server */
  777. else {
  778. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  779. if (rpc_url[strlen(rpc_url) - 1] != '/')
  780. need_slash = true;
  781. lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  782. if (!lp_url)
  783. goto out;
  784. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  785. }
  786. applog(LOG_INFO, "Long-polling activated for %s", lp_url);
  787. curl = curl_easy_init();
  788. if (unlikely(!curl)) {
  789. applog(LOG_ERR, "CURL initialization failed");
  790. goto out;
  791. }
  792. while (1) {
  793. json_t *val;
  794. val = json_rpc_call(curl, lp_url, rpc_userpass, rpc_req,
  795. false, true);
  796. if (likely(val)) {
  797. failures = 0;
  798. json_decref(val);
  799. applog(LOG_INFO, "LONGPOLL detected new block");
  800. restart_threads();
  801. } else {
  802. if (failures++ < 10) {
  803. sleep(30);
  804. applog(LOG_ERR,
  805. "longpoll failed, sleeping for 30s");
  806. } else {
  807. applog(LOG_ERR,
  808. "longpoll failed, ending thread");
  809. goto out;
  810. }
  811. }
  812. }
  813. out:
  814. free(hdr_path);
  815. free(lp_url);
  816. tq_freeze(mythr->q);
  817. if (curl)
  818. curl_easy_cleanup(curl);
  819. return NULL;
  820. }
  821. static void show_usage(void)
  822. {
  823. int i;
  824. printf("minerd version %s\n\n", VERSION);
  825. printf("Usage:\tminerd [options]\n\nSupported options:\n");
  826. for (i = 0; i < ARRAY_SIZE(options_help); i++) {
  827. struct option_help *h;
  828. h = &options_help[i];
  829. printf("--%s\n%s\n\n", h->name, h->helptext);
  830. }
  831. exit(1);
  832. }
  833. static void parse_arg (int key, char *arg)
  834. {
  835. int v, i;
  836. switch(key) {
  837. case 'a':
  838. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  839. if (algo_names[i] &&
  840. !strcmp(arg, algo_names[i])) {
  841. opt_algo = i;
  842. break;
  843. }
  844. }
  845. if (i == ARRAY_SIZE(algo_names))
  846. show_usage();
  847. break;
  848. case 'c': {
  849. json_error_t err;
  850. if (opt_config)
  851. json_decref(opt_config);
  852. opt_config = json_load_file(arg, &err);
  853. if (!json_is_object(opt_config)) {
  854. applog(LOG_ERR, "JSON decode of %s failed", arg);
  855. show_usage();
  856. }
  857. break;
  858. }
  859. case 'q':
  860. opt_quiet = true;
  861. break;
  862. case 'I':
  863. v = atoi(arg);
  864. if (v < 0 || v > 16) /* sanity check */
  865. show_usage();
  866. scan_intensity = v;
  867. break;
  868. case 'D':
  869. opt_debug = true;
  870. break;
  871. case 'p':
  872. free(rpc_pass);
  873. rpc_pass = strdup(arg);
  874. break;
  875. case 'P':
  876. opt_protocol = true;
  877. break;
  878. case 'r':
  879. v = atoi(arg);
  880. if (v < -1 || v > 9999) /* sanity check */
  881. show_usage();
  882. opt_retries = v;
  883. break;
  884. case 'R':
  885. v = atoi(arg);
  886. if (v < 1 || v > 9999) /* sanity check */
  887. show_usage();
  888. opt_fail_pause = v;
  889. break;
  890. case 's':
  891. v = atoi(arg);
  892. if (v < 1 || v > 9999) /* sanity check */
  893. show_usage();
  894. opt_scantime = v;
  895. break;
  896. case 't':
  897. v = atoi(arg);
  898. if (v < 0 || v > 9999) /* sanity check */
  899. show_usage();
  900. opt_n_threads = v;
  901. break;
  902. case 'u':
  903. free(rpc_user);
  904. rpc_user = strdup(arg);
  905. break;
  906. case 1001: /* --url */
  907. if (strncmp(arg, "http://", 7) &&
  908. strncmp(arg, "https://", 8))
  909. show_usage();
  910. free(rpc_url);
  911. rpc_url = strdup(arg);
  912. break;
  913. case 1002: /* --userpass */
  914. if (!strchr(arg, ':'))
  915. show_usage();
  916. free(rpc_userpass);
  917. rpc_userpass = strdup(arg);
  918. break;
  919. case 1003:
  920. want_longpoll = false;
  921. break;
  922. case 1004:
  923. use_syslog = true;
  924. break;
  925. default:
  926. show_usage();
  927. }
  928. }
  929. static void parse_config(void)
  930. {
  931. int i;
  932. json_t *val;
  933. if (!json_is_object(opt_config))
  934. return;
  935. for (i = 0; i < ARRAY_SIZE(options); i++) {
  936. if (!options[i].name)
  937. break;
  938. if (!strcmp(options[i].name, "config"))
  939. continue;
  940. val = json_object_get(opt_config, options[i].name);
  941. if (!val)
  942. continue;
  943. if (options[i].has_arg && json_is_string(val)) {
  944. char *s = strdup(json_string_value(val));
  945. if (!s)
  946. break;
  947. parse_arg(options[i].val, s);
  948. free(s);
  949. } else if (!options[i].has_arg && json_is_true(val))
  950. parse_arg(options[i].val, "");
  951. else
  952. applog(LOG_ERR, "JSON option %s invalid",
  953. options[i].name);
  954. }
  955. }
  956. static void parse_cmdline(int argc, char *argv[])
  957. {
  958. int key;
  959. while (1) {
  960. key = getopt_long(argc, argv, "a:c:qDPr:s:t:h?", options, NULL);
  961. if (key < 0)
  962. break;
  963. parse_arg(key, optarg);
  964. }
  965. parse_config();
  966. }
  967. int main (int argc, char *argv[])
  968. {
  969. struct thr_info *thr;
  970. int i;
  971. char name[32];
  972. #ifdef WIN32
  973. opt_n_threads = 1;
  974. #else
  975. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  976. opt_n_threads = num_processors;
  977. #endif /* !WIN32 */
  978. nDevs = clDevicesNum();
  979. if (opt_ndevs) {
  980. printf("%i\n", nDevs);
  981. return nDevs;
  982. }
  983. rpc_url = strdup(DEF_RPC_URL);
  984. /* parse command line */
  985. parse_cmdline(argc, argv);
  986. if (!rpc_userpass) {
  987. if (!rpc_user || !rpc_pass) {
  988. applog(LOG_ERR, "No login credentials supplied");
  989. return 1;
  990. }
  991. rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  992. if (!rpc_userpass)
  993. return 1;
  994. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  995. }
  996. if (unlikely(pthread_mutex_init(&time_lock, NULL)))
  997. return 1;
  998. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  999. return 1;
  1000. #ifdef HAVE_SYSLOG_H
  1001. if (use_syslog)
  1002. openlog("cpuminer", LOG_PID, LOG_USER);
  1003. #endif
  1004. work_restart = calloc(opt_n_threads + nDevs, sizeof(*work_restart));
  1005. if (!work_restart)
  1006. return 1;
  1007. thr_info = calloc(opt_n_threads + 2 + nDevs, sizeof(*thr));
  1008. if (!thr_info)
  1009. return 1;
  1010. /* init workio thread info */
  1011. work_thr_id = opt_n_threads + nDevs;
  1012. thr = &thr_info[work_thr_id];
  1013. thr->id = work_thr_id;
  1014. thr->q = tq_new();
  1015. if (!thr->q)
  1016. return 1;
  1017. /* start work I/O thread */
  1018. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  1019. applog(LOG_ERR, "workio thread create failed");
  1020. return 1;
  1021. }
  1022. /* init longpoll thread info */
  1023. if (want_longpoll) {
  1024. longpoll_thr_id = opt_n_threads + nDevs + 1;
  1025. thr = &thr_info[longpoll_thr_id];
  1026. thr->id = longpoll_thr_id;
  1027. thr->q = tq_new();
  1028. if (!thr->q)
  1029. return 1;
  1030. /* start longpoll thread */
  1031. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  1032. applog(LOG_ERR, "longpoll thread create failed");
  1033. return 1;
  1034. }
  1035. } else
  1036. longpoll_thr_id = -1;
  1037. gettimeofday(&total_tv_start, NULL);
  1038. gettimeofday(&total_tv_end, NULL);
  1039. /* start GPU mining threads */
  1040. for (i = 0; i < nDevs; i++) {
  1041. thr = &thr_info[i];
  1042. thr->id = i;
  1043. thr->q = tq_new();
  1044. if (!thr->q)
  1045. return 1;
  1046. printf("Init GPU %i\n", i);
  1047. clStates[i] = initCl(i, name, sizeof(name));
  1048. if (!clStates[i]) {
  1049. applog(LOG_ERR, "Failed to init GPU %d", i);
  1050. continue;
  1051. }
  1052. printf("initCl() finished. Found %s\n", name);
  1053. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1054. applog(LOG_ERR, "thread %d create failed", i);
  1055. return 1;
  1056. }
  1057. sleep(1); /* don't pound RPC server all at once */
  1058. }
  1059. applog(LOG_INFO, "%d gpu miner threads started", i);
  1060. /* start CPU mining threads */
  1061. for (i = nDevs; i < nDevs + opt_n_threads; i++) {
  1062. thr = &thr_info[i];
  1063. thr->id = i;
  1064. thr->q = tq_new();
  1065. if (!thr->q)
  1066. return 1;
  1067. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1068. applog(LOG_ERR, "thread %d create failed", i);
  1069. return 1;
  1070. }
  1071. sleep(1); /* don't pound RPC server all at once */
  1072. }
  1073. applog(LOG_INFO, "%d cpu miner threads started, "
  1074. "using SHA256 '%s' algorithm.",
  1075. opt_n_threads,
  1076. algo_names[opt_algo]);
  1077. /* Restart count as it will be wrong till all threads are started */
  1078. pthread_mutex_lock(&hash_lock);
  1079. gettimeofday(&total_tv_start, NULL);
  1080. gettimeofday(&total_tv_end, NULL);
  1081. total_hashes_done = 0;
  1082. pthread_mutex_unlock(&hash_lock);
  1083. /* main loop - simply wait for workio thread to exit */
  1084. pthread_join(thr_info[work_thr_id].pth, NULL);
  1085. applog(LOG_INFO, "workio thread dead, exiting.");
  1086. return 0;
  1087. }