main.c 43 KB

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