cpu-miner.c 27 KB

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