main.c 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721
  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. ok = false;
  509. break;
  510. }
  511. /* process workio_cmd */
  512. switch (wc->cmd) {
  513. case WC_GET_WORK:
  514. ok = workio_get_work(wc);
  515. break;
  516. case WC_SUBMIT_WORK:
  517. ok = workio_submit_work(wc);
  518. break;
  519. case WC_DIE:
  520. default:
  521. ok = false;
  522. break;
  523. }
  524. }
  525. tq_freeze(mythr->q);
  526. return NULL;
  527. }
  528. static void hashmeter(int thr_id, struct timeval *diff,
  529. unsigned long hashes_done)
  530. {
  531. struct timeval temp_tv_end, total_diff;
  532. double khashes, secs;
  533. double local_secs;
  534. static double local_mhashes_done = 0;
  535. static double rolling_local = 0;
  536. double local_mhashes = (double)hashes_done / 1000000.0;
  537. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  538. unsigned int i;
  539. /* Don't bother calculating anything if we're not displaying it */
  540. if (opt_quiet || !opt_log_interval)
  541. return;
  542. khashes = hashes_done / 1000.0;
  543. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  544. if (opt_debug)
  545. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  546. thr_id, hashes_done, hashes_done / secs);
  547. /* Totals are updated by all threads so can race without locking */
  548. pthread_mutex_lock(&hash_lock);
  549. gettimeofday(&temp_tv_end, NULL);
  550. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  551. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  552. total_mhashes_done += local_mhashes;
  553. local_mhashes_done += local_mhashes;
  554. cgpu->local_mhashes += local_mhashes;
  555. cgpu->total_mhashes += local_mhashes;
  556. if (total_diff.tv_sec < opt_log_interval)
  557. /* Only update the total every opt_log_interval seconds */
  558. goto out_unlock;
  559. gettimeofday(&total_tv_end, NULL);
  560. /* Use a rolling average by faking an exponential decay over 5 * log */
  561. rolling_local = ((rolling_local * 0.9) + local_mhashes_done) / 1.9;
  562. cgpu->rolling_local = ((cgpu->rolling_local * 0.9) + cgpu->local_mhashes) / 1.9;
  563. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  564. total_secs = (double)total_diff.tv_sec +
  565. ((double)total_diff.tv_usec / 1000000.0);
  566. applog(LOG_INFO, "[%.2f | %.2f Mhash/s] [%d Accepted] [%d Rejected] [%d HW errors]",
  567. rolling_local / local_secs,
  568. total_mhashes_done / total_secs, accepted, rejected, hw_errors);
  569. printf("[Rate (%ds): %.2f (avg): %.2f Mhash/s] [Accepted: %d Rejected: %d HW errors: %d]\r",
  570. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  571. accepted, rejected, hw_errors);
  572. fflush(stdout);
  573. if (opt_log_output)
  574. printf("\n");
  575. local_mhashes_done = 0;
  576. out_unlock:
  577. pthread_mutex_unlock(&hash_lock);
  578. }
  579. /* This is overkill, but at least we'll know accurately how much work is
  580. * queued to prevent ever being left without work */
  581. static void inc_queued(void)
  582. {
  583. pthread_mutex_lock(&qd_lock);
  584. total_queued++;
  585. pthread_mutex_unlock(&qd_lock);
  586. }
  587. static void dec_queued(void)
  588. {
  589. pthread_mutex_lock(&qd_lock);
  590. total_queued--;
  591. pthread_mutex_unlock(&qd_lock);
  592. }
  593. static int requests_queued(void)
  594. {
  595. int ret;
  596. pthread_mutex_lock(&qd_lock);
  597. ret = total_queued;
  598. pthread_mutex_unlock(&qd_lock);
  599. return ret;
  600. }
  601. /* All work is queued flagged as being for thread 0 and then the mining thread
  602. * flags it as its own */
  603. static bool queue_request(void)
  604. {
  605. struct thr_info *thr = &thr_info[0];
  606. struct workio_cmd *wc;
  607. /* fill out work request message */
  608. wc = calloc(1, sizeof(*wc));
  609. if (unlikely(!wc))
  610. return false;
  611. wc->cmd = WC_GET_WORK;
  612. wc->thr = thr;
  613. /* send work request to workio thread */
  614. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  615. workio_cmd_free(wc);
  616. return false;
  617. }
  618. inc_queued();
  619. return true;
  620. }
  621. static bool discard_request(void)
  622. {
  623. struct thr_info *thr = &thr_info[0];
  624. struct work *work_heap;
  625. /* Just in case we fell in a hole and missed a queue filling */
  626. if (unlikely(!requests_queued()))
  627. return true;
  628. work_heap = tq_pop(thr->q, NULL);
  629. if (unlikely(!work_heap))
  630. return false;
  631. free(work_heap);
  632. dec_queued();
  633. return true;
  634. }
  635. static void flush_requests(void)
  636. {
  637. int i, extra;
  638. extra = requests_queued();
  639. for (i = 0; i < extra; i++) {
  640. /* Queue a whole batch of new requests */
  641. if (unlikely(!queue_request())) {
  642. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  643. kill_work();
  644. break;
  645. }
  646. /* Pop off the old requests. Cancelling the requests would be better
  647. * but is tricky */
  648. if (unlikely(!discard_request())) {
  649. applog(LOG_ERR, "Failed to discard requests in flush_requests");
  650. kill_work();
  651. break;
  652. }
  653. }
  654. }
  655. static bool get_work(struct work *work, bool queued)
  656. {
  657. struct thr_info *thr = &thr_info[0];
  658. struct work *work_heap;
  659. bool ret = false;
  660. if (!queued || !requests_queued()) {
  661. if (unlikely(!queue_request()))
  662. goto out;
  663. }
  664. /* wait for 1st response, or get cached response */
  665. work_heap = tq_pop(thr->q, NULL);
  666. if (unlikely(!work_heap))
  667. goto out;
  668. dec_queued();
  669. memcpy(work, work_heap, sizeof(*work));
  670. memcpy(current_block, work->data, 36);
  671. ret = true;
  672. free(work_heap);
  673. out:
  674. return ret;
  675. }
  676. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  677. {
  678. struct workio_cmd *wc;
  679. /* fill out work request message */
  680. wc = calloc(1, sizeof(*wc));
  681. if (unlikely(!wc)) {
  682. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  683. return false;
  684. }
  685. wc->u.work = malloc(sizeof(*work_in));
  686. if (unlikely(!wc->u.work)) {
  687. applog(LOG_ERR, "Failed to calloc work in submit_work_sync");
  688. goto err_out;
  689. }
  690. wc->cmd = WC_SUBMIT_WORK;
  691. wc->thr = thr;
  692. memcpy(wc->u.work, work_in, sizeof(*work_in));
  693. /* send solution to workio thread */
  694. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  695. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  696. goto err_out;
  697. }
  698. return true;
  699. err_out:
  700. workio_cmd_free(wc);
  701. return false;
  702. }
  703. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  704. {
  705. work->data[64+12+0] = (nonce>>0) & 0xff;
  706. work->data[64+12+1] = (nonce>>8) & 0xff;
  707. work->data[64+12+2] = (nonce>>16) & 0xff;
  708. work->data[64+12+3] = (nonce>>24) & 0xff;
  709. return submit_work_sync(thr, work);
  710. }
  711. static inline int cpu_from_thr_id(int thr_id)
  712. {
  713. return (thr_id - gpu_threads) % num_processors;
  714. }
  715. static void *miner_thread(void *userdata)
  716. {
  717. struct thr_info *mythr = userdata;
  718. const int thr_id = mythr->id;
  719. uint32_t max_nonce = 0xffffff;
  720. bool needs_work = true;
  721. /* Try to cycle approximately 5 times before each log update */
  722. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  723. /* Request the next work item at 2/3 of the scantime */
  724. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  725. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  726. bool requested = false;
  727. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  728. * and if that fails, then SCHED_BATCH. No need for this to be an
  729. * error if it fails */
  730. setpriority(PRIO_PROCESS, 0, 19);
  731. drop_policy();
  732. /* Cpu affinity only makes sense if the number of threads is a multiple
  733. * of the number of CPUs */
  734. if (!(opt_n_threads % num_processors))
  735. affine_to_cpu(thr_id - gpu_threads, cpu_from_thr_id(thr_id));
  736. while (1) {
  737. struct work work __attribute__((aligned(128)));
  738. unsigned long hashes_done;
  739. struct timeval tv_workstart, tv_start, tv_end, diff;
  740. uint64_t max64;
  741. bool rc;
  742. if (needs_work) {
  743. if (work_restart[thr_id].restart) {
  744. if (requested) {
  745. /* We have one extra request than desired now */
  746. if (unlikely(!discard_request())) {
  747. applog(LOG_ERR, "Failed to discard request in uminer thread");
  748. goto out;
  749. }
  750. } else
  751. requested = true;
  752. }
  753. gettimeofday(&tv_workstart, NULL);
  754. /* obtain new work from internal workio thread */
  755. if (unlikely(!get_work(&work, requested))) {
  756. applog(LOG_ERR, "work retrieval failed, exiting "
  757. "mining thread %d", mythr->id);
  758. goto out;
  759. }
  760. work.thr_id = thr_id;
  761. needs_work = requested = false;
  762. work.blk.nonce = 0;
  763. }
  764. hashes_done = 0;
  765. gettimeofday(&tv_start, NULL);
  766. /* scan nonces for a proof-of-work hash */
  767. switch (opt_algo) {
  768. case ALGO_C:
  769. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  770. work.hash1, work.hash, work.target,
  771. max_nonce, &hashes_done,
  772. work.blk.nonce);
  773. break;
  774. #ifdef WANT_X8664_SSE2
  775. case ALGO_SSE2_64: {
  776. unsigned int rc5 =
  777. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  778. work.hash1, work.hash,
  779. work.target,
  780. max_nonce, &hashes_done,
  781. work.blk.nonce);
  782. rc = (rc5 == -1) ? false : true;
  783. }
  784. break;
  785. #endif
  786. #ifdef WANT_SSE2_4WAY
  787. case ALGO_4WAY: {
  788. unsigned int rc4 =
  789. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  790. work.hash1, work.hash,
  791. work.target,
  792. max_nonce, &hashes_done,
  793. work.blk.nonce);
  794. rc = (rc4 == -1) ? false : true;
  795. }
  796. break;
  797. #endif
  798. #ifdef WANT_VIA_PADLOCK
  799. case ALGO_VIA:
  800. rc = scanhash_via(thr_id, work.data, work.target,
  801. max_nonce, &hashes_done,
  802. work.blk.nonce);
  803. break;
  804. #endif
  805. case ALGO_CRYPTOPP:
  806. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  807. work.hash1, work.hash, work.target,
  808. max_nonce, &hashes_done,
  809. work.blk.nonce);
  810. break;
  811. #ifdef WANT_CRYPTOPP_ASM32
  812. case ALGO_CRYPTOPP_ASM32:
  813. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  814. work.hash1, work.hash, work.target,
  815. max_nonce, &hashes_done,
  816. work.blk.nonce);
  817. break;
  818. #endif
  819. default:
  820. /* should never happen */
  821. goto out;
  822. }
  823. /* record scanhash elapsed time */
  824. gettimeofday(&tv_end, NULL);
  825. timeval_subtract(&diff, &tv_end, &tv_start);
  826. hashes_done -= work.blk.nonce;
  827. hashmeter(thr_id, &diff, hashes_done);
  828. work.blk.nonce += hashes_done;
  829. /* adjust max_nonce to meet target cycle time */
  830. if (diff.tv_usec > 500000)
  831. diff.tv_sec++;
  832. if (diff.tv_sec != cycle) {
  833. max64 = work.blk.nonce +
  834. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  835. } else
  836. max64 = work.blk.nonce + hashes_done;
  837. if (max64 > 0xfffffffaULL)
  838. max64 = 0xfffffffaULL;
  839. max_nonce = max64;
  840. /* if nonce found, submit work */
  841. if (unlikely(rc)) {
  842. if (opt_debug)
  843. applog(LOG_DEBUG, "CPU %d found something?", cpu_from_thr_id(thr_id));
  844. if (unlikely(!submit_work_sync(mythr, &work)))
  845. break;
  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. goto out;
  852. requested = true;
  853. }
  854. if (diff.tv_sec > opt_scantime || work_restart[thr_id].restart ||
  855. work.blk.nonce >= MAXTHREADS - hashes_done)
  856. needs_work = true;
  857. }
  858. out:
  859. tq_freeze(mythr->q);
  860. return NULL;
  861. }
  862. enum {
  863. STAT_SLEEP_INTERVAL = 1,
  864. STAT_CTR_INTERVAL = 10000000,
  865. FAILURE_INTERVAL = 30,
  866. };
  867. #ifdef HAVE_OPENCL
  868. static _clState *clStates[16];
  869. static inline cl_int queue_kernel_parameters(_clState *clState, dev_blk_ctx *blk)
  870. {
  871. cl_kernel *kernel = &clState->kernel;
  872. cl_int status = 0;
  873. int num = 0;
  874. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  875. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  876. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  877. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  878. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  879. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  880. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  881. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  882. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  883. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  884. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  885. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  886. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  887. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  888. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  889. if (clState->hasBitAlign == true) {
  890. /* Parameters for phatk kernel */
  891. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2);
  892. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  893. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  894. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4);
  895. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1);
  896. } else {
  897. /* Parameters for poclbm kernel */
  898. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  899. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  900. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  901. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  902. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  903. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  904. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  905. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  906. }
  907. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  908. (void *)&clState->outputBuffer);
  909. return status;
  910. }
  911. static inline int gpu_from_thr_id(int thr_id)
  912. {
  913. return thr_id % nDevs;
  914. }
  915. static void *gpuminer_thread(void *userdata)
  916. {
  917. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  918. struct timeval tv_start, tv_end, diff;
  919. struct thr_info *mythr = userdata;
  920. const int thr_id = mythr->id;
  921. uint32_t *res, *blank_res;
  922. size_t globalThreads[1];
  923. size_t localThreads[1];
  924. cl_int status;
  925. _clState *clState = clStates[thr_id];
  926. const cl_kernel *kernel = &clState->kernel;
  927. struct work *work = malloc(sizeof(struct work));
  928. unsigned const int threads = 1 << (15 + scan_intensity);
  929. unsigned const int vectors = clState->preferred_vwidth;
  930. unsigned const int hashes = threads * vectors;
  931. unsigned int hashes_done = 0;
  932. /* Request the next work item at 2/3 of the scantime */
  933. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  934. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  935. bool requested = false;
  936. res = calloc(BUFFERSIZE, 1);
  937. blank_res = calloc(BUFFERSIZE, 1);
  938. if (!res || !blank_res) {
  939. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  940. goto out;
  941. }
  942. gettimeofday(&tv_start, NULL);
  943. globalThreads[0] = threads;
  944. localThreads[0] = clState->work_size;
  945. diff.tv_sec = ~0UL;
  946. gettimeofday(&tv_end, NULL);
  947. while (1) {
  948. struct timeval tv_workstart;
  949. /* This finish flushes the readbuffer set with CL_FALSE later */
  950. clFinish(clState->commandQueue);
  951. if (diff.tv_sec > opt_scantime || work->blk.nonce >= MAXTHREADS - hashes || work_restart[thr_id].restart) {
  952. /* Ignore any reads since we're getting new work and queue a clean buffer */
  953. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  954. BUFFERSIZE, blank_res, 0, NULL, NULL);
  955. if (unlikely(status != CL_SUCCESS))
  956. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  957. memset(res, 0, BUFFERSIZE);
  958. gettimeofday(&tv_workstart, NULL);
  959. if (work_restart[thr_id].restart) {
  960. if (requested) {
  961. /* We have one extra request than desired now */
  962. if (unlikely(!discard_request())) {
  963. applog(LOG_ERR, "Failed to discard request in gpuminer thread");
  964. goto out;
  965. }
  966. } else
  967. requested = true;
  968. }
  969. /* obtain new work from internal workio thread */
  970. if (unlikely(!get_work(work, requested))) {
  971. applog(LOG_ERR, "work retrieval failed, exiting "
  972. "gpu mining thread %d", mythr->id);
  973. goto out;
  974. }
  975. work->thr_id = thr_id;
  976. requested = false;
  977. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  978. work->blk.nonce = 0;
  979. work_restart[thr_id].restart = 0;
  980. if (opt_debug)
  981. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  982. /* Flushes the writebuffer set with CL_FALSE above */
  983. clFinish(clState->commandQueue);
  984. }
  985. status = queue_kernel_parameters(clState, &work->blk);
  986. if (unlikely(status != CL_SUCCESS))
  987. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  988. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  989. if (res[MAXBUFFERS]) {
  990. /* Clear the buffer again */
  991. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  992. BUFFERSIZE, blank_res, 0, NULL, NULL);
  993. if (unlikely(status != CL_SUCCESS))
  994. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  995. if (opt_debug)
  996. applog(LOG_DEBUG, "GPU %d found something?", gpu_from_thr_id(thr_id));
  997. postcalc_hash_async(mythr, work, res);
  998. memset(res, 0, BUFFERSIZE);
  999. clFinish(clState->commandQueue);
  1000. }
  1001. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  1002. globalThreads, localThreads, 0, NULL, NULL);
  1003. if (unlikely(status != CL_SUCCESS))
  1004. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  1005. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1006. BUFFERSIZE, res, 0, NULL, NULL);
  1007. if (unlikely(status != CL_SUCCESS))
  1008. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  1009. gettimeofday(&tv_end, NULL);
  1010. timeval_subtract(&diff, &tv_end, &tv_start);
  1011. hashes_done += hashes;
  1012. work->blk.nonce += hashes;
  1013. if (diff.tv_usec > 500000)
  1014. diff.tv_sec++;
  1015. if (diff.tv_sec >= cycle) {
  1016. hashmeter(thr_id, &diff, hashes_done);
  1017. gettimeofday(&tv_start, NULL);
  1018. hashes_done = 0;
  1019. }
  1020. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1021. if (!requested && (diff.tv_sec > request_interval || work->blk.nonce > request_nonce)) {
  1022. if (unlikely(!queue_request()))
  1023. goto out;
  1024. requested = true;
  1025. }
  1026. }
  1027. out:
  1028. tq_freeze(mythr->q);
  1029. return NULL;
  1030. }
  1031. #endif /* HAVE_OPENCL */
  1032. static void restart_threads(void)
  1033. {
  1034. int i;
  1035. /* Discard old queued requests and get new ones */
  1036. flush_requests();
  1037. /* Queue extra requests for each worker thread since they'll all need
  1038. * new work. Each worker will set their "requested" flag to true
  1039. * should they receive a .restart */
  1040. for (i = 0; i < opt_n_threads + gpu_threads; i++) {
  1041. if (unlikely(!queue_request())) {
  1042. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  1043. kill_work();
  1044. return;
  1045. }
  1046. work_restart[i].restart = 1;
  1047. }
  1048. }
  1049. static void *longpoll_thread(void *userdata)
  1050. {
  1051. struct thr_info *mythr = userdata;
  1052. CURL *curl = NULL;
  1053. char *copy_start, *hdr_path, *lp_url = NULL;
  1054. bool need_slash = false;
  1055. int failures = 0;
  1056. hdr_path = tq_pop(mythr->q, NULL);
  1057. if (!hdr_path)
  1058. goto out;
  1059. /* full URL */
  1060. if (strstr(hdr_path, "://")) {
  1061. lp_url = hdr_path;
  1062. hdr_path = NULL;
  1063. }
  1064. /* absolute path, on current server */
  1065. else {
  1066. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  1067. if (rpc_url[strlen(rpc_url) - 1] != '/')
  1068. need_slash = true;
  1069. lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  1070. if (!lp_url)
  1071. goto out;
  1072. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  1073. }
  1074. applog(LOG_INFO, "Long-polling activated for %s", lp_url);
  1075. curl = curl_easy_init();
  1076. if (unlikely(!curl)) {
  1077. applog(LOG_ERR, "CURL initialisation failed");
  1078. goto out;
  1079. }
  1080. while (1) {
  1081. json_t *val;
  1082. val = json_rpc_call(curl, lp_url, rpc_userpass, rpc_req,
  1083. false, true);
  1084. if (likely(val)) {
  1085. failures = 0;
  1086. json_decref(val);
  1087. printf("LONGPOLL detected new block \r");
  1088. applog(LOG_INFO, "LONGPOLL detected new block");
  1089. restart_threads();
  1090. } else {
  1091. if (failures++ < 10) {
  1092. sleep(30);
  1093. applog(LOG_ERR,
  1094. "longpoll failed, sleeping for 30s");
  1095. } else {
  1096. applog(LOG_ERR,
  1097. "longpoll failed, ending thread");
  1098. goto out;
  1099. }
  1100. }
  1101. }
  1102. out:
  1103. free(hdr_path);
  1104. free(lp_url);
  1105. tq_freeze(mythr->q);
  1106. if (curl)
  1107. curl_easy_cleanup(curl);
  1108. return NULL;
  1109. }
  1110. static void show_usage(void)
  1111. {
  1112. int i;
  1113. printf("cgminer version %s\n", VERSION);
  1114. #ifdef HAVE_OPENCL
  1115. printf("Built with CPU and GPU mining support.\n\n");
  1116. #else
  1117. printf("Built with CPU mining support only.\n\n");
  1118. #endif
  1119. printf("Usage:\tcgminer [options]\n\nSupported options:\n");
  1120. for (i = 0; i < ARRAY_SIZE(options_help); i++) {
  1121. struct option_help *h;
  1122. h = &options_help[i];
  1123. printf("--%s\n%s\n\n", h->name, h->helptext);
  1124. }
  1125. exit(1);
  1126. }
  1127. static void parse_arg (int key, char *arg)
  1128. {
  1129. int v, i;
  1130. switch(key) {
  1131. case 'a':
  1132. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  1133. if (algo_names[i] &&
  1134. !strcmp(arg, algo_names[i])) {
  1135. opt_algo = i;
  1136. break;
  1137. }
  1138. }
  1139. if (i == ARRAY_SIZE(algo_names))
  1140. show_usage();
  1141. break;
  1142. case 'c': {
  1143. json_error_t err;
  1144. if (opt_config)
  1145. json_decref(opt_config);
  1146. opt_config = json_load_file(arg, &err);
  1147. if (!json_is_object(opt_config)) {
  1148. applog(LOG_ERR, "JSON decode of %s failed", arg);
  1149. show_usage();
  1150. }
  1151. break;
  1152. }
  1153. case 'g':
  1154. v = atoi(arg);
  1155. if (v < 0 || v > 10)
  1156. show_usage();
  1157. opt_g_threads = v;
  1158. break;
  1159. case 'D':
  1160. opt_debug = true;
  1161. break;
  1162. case 'I':
  1163. v = atoi(arg);
  1164. if (v < 0 || v > 14) /* sanity check */
  1165. show_usage();
  1166. scan_intensity = v;
  1167. break;
  1168. case 'l':
  1169. v = atoi(arg);
  1170. if (v < 0 || v > 9999) /* sanity check */
  1171. show_usage();
  1172. opt_log_interval = v;
  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. if (opt_ndevs) {
  1310. applog(LOG_INFO, "%i", nDevs);
  1311. return nDevs;
  1312. }
  1313. #endif
  1314. /* Invert the value to determine if we manually set it in cmdline
  1315. * or disable gpu threads */
  1316. if (nDevs)
  1317. opt_n_threads = - opt_n_threads;
  1318. rpc_url = strdup(DEF_RPC_URL);
  1319. /* parse command line */
  1320. parse_cmdline(argc, argv);
  1321. gpu_threads = nDevs * opt_g_threads;
  1322. if (opt_n_threads < 0) {
  1323. if (gpu_threads)
  1324. opt_n_threads = 0;
  1325. else
  1326. opt_n_threads = -opt_n_threads;
  1327. }
  1328. if (!rpc_userpass) {
  1329. if (!rpc_user || !rpc_pass) {
  1330. applog(LOG_ERR, "No login credentials supplied");
  1331. return 1;
  1332. }
  1333. rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  1334. if (!rpc_userpass)
  1335. return 1;
  1336. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  1337. }
  1338. if (unlikely(pthread_mutex_init(&time_lock, NULL)))
  1339. return 1;
  1340. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  1341. return 1;
  1342. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  1343. return 1;
  1344. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  1345. return 1;
  1346. #ifdef HAVE_SYSLOG_H
  1347. if (use_syslog)
  1348. openlog("cpuminer", LOG_PID, LOG_USER);
  1349. #endif
  1350. work_restart = calloc(opt_n_threads + gpu_threads, sizeof(*work_restart));
  1351. if (!work_restart)
  1352. return 1;
  1353. thr_info = calloc(opt_n_threads + 2 + gpu_threads, sizeof(*thr));
  1354. if (!thr_info)
  1355. return 1;
  1356. /* init workio thread info */
  1357. work_thr_id = opt_n_threads + gpu_threads;
  1358. thr = &thr_info[work_thr_id];
  1359. thr->id = work_thr_id;
  1360. thr->q = tq_new();
  1361. if (!thr->q)
  1362. return 1;
  1363. /* start work I/O thread */
  1364. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  1365. applog(LOG_ERR, "workio thread create failed");
  1366. return 1;
  1367. }
  1368. /* init longpoll thread info */
  1369. if (want_longpoll) {
  1370. longpoll_thr_id = opt_n_threads + gpu_threads + 1;
  1371. thr = &thr_info[longpoll_thr_id];
  1372. thr->id = longpoll_thr_id;
  1373. thr->q = tq_new();
  1374. if (!thr->q)
  1375. return 1;
  1376. /* start longpoll thread */
  1377. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  1378. applog(LOG_ERR, "longpoll thread create failed");
  1379. return 1;
  1380. }
  1381. pthread_detach(thr->pth);
  1382. } else
  1383. longpoll_thr_id = -1;
  1384. gettimeofday(&total_tv_start, NULL);
  1385. gettimeofday(&total_tv_end, NULL);
  1386. if (opt_n_threads ) {
  1387. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  1388. if (unlikely(!cpus)) {
  1389. applog(LOG_ERR, "Failed to calloc cpus");
  1390. return 1;
  1391. }
  1392. }
  1393. if (gpu_threads) {
  1394. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  1395. if (unlikely(!gpus)) {
  1396. applog(LOG_ERR, "Failed to calloc gpus");
  1397. return 1;
  1398. }
  1399. }
  1400. /* Put the extra work in the queue */
  1401. for (i = 0; i < opt_queue; i++) {
  1402. if (unlikely(!queue_request())) {
  1403. applog(LOG_ERR, "Failed to queue_request in main");
  1404. return 1;
  1405. }
  1406. }
  1407. #ifdef HAVE_OPENCL
  1408. /* start GPU mining threads */
  1409. for (i = 0; i < gpu_threads; i++) {
  1410. int gpu = gpu_from_thr_id(i);
  1411. thr = &thr_info[i];
  1412. thr->id = i;
  1413. gpus[gpu].is_gpu = 1;
  1414. gpus[gpu].cpu_gpu = gpu;
  1415. thr->cgpu = &gpus[gpu];
  1416. thr->q = tq_new();
  1417. if (!thr->q) {
  1418. applog(LOG_ERR, "tq_new failed in starting gpu mining threads");
  1419. return 1;
  1420. }
  1421. applog(LOG_INFO, "Init GPU thread %i", i);
  1422. clStates[i] = initCl(gpu, name, sizeof(name));
  1423. if (!clStates[i]) {
  1424. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  1425. continue;
  1426. }
  1427. applog(LOG_INFO, "initCl() finished. Found %s", name);
  1428. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1429. applog(LOG_ERR, "thread %d create failed", i);
  1430. return 1;
  1431. }
  1432. pthread_detach(thr->pth);
  1433. }
  1434. applog(LOG_INFO, "%d gpu miner threads started", i);
  1435. #endif
  1436. /* start CPU mining threads */
  1437. for (i = gpu_threads; i < gpu_threads + opt_n_threads; i++) {
  1438. int cpu = cpu_from_thr_id(i);
  1439. thr = &thr_info[i];
  1440. thr->id = i;
  1441. cpus[cpu].cpu_gpu = cpu;
  1442. thr->cgpu = &cpus[cpu];
  1443. thr->q = tq_new();
  1444. if (!thr->q) {
  1445. applog(LOG_ERR, "tq_new failed in starting cpu mining threads");
  1446. return 1;
  1447. }
  1448. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1449. applog(LOG_ERR, "thread %d create failed", i);
  1450. return 1;
  1451. }
  1452. pthread_detach(thr->pth);
  1453. }
  1454. applog(LOG_INFO, "%d cpu miner threads started, "
  1455. "using SHA256 '%s' algorithm.",
  1456. opt_n_threads,
  1457. algo_names[opt_algo]);
  1458. /* Restart count as it will be wrong till all threads are started */
  1459. pthread_mutex_lock(&hash_lock);
  1460. gettimeofday(&total_tv_start, NULL);
  1461. gettimeofday(&total_tv_end, NULL);
  1462. total_mhashes_done = 0;
  1463. pthread_mutex_unlock(&hash_lock);
  1464. /* main loop - simply wait for workio thread to exit */
  1465. pthread_join(thr_info[work_thr_id].pth, NULL);
  1466. curl_global_cleanup();
  1467. if (gpu_threads)
  1468. free(gpus);
  1469. if (opt_n_threads)
  1470. free(cpus);
  1471. applog(LOG_INFO, "workio thread dead, exiting.");
  1472. return 0;
  1473. }