cpu-miner.c 41 KB

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