main.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733
  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_BATCH
  41. #ifdef SCHED_IDLE
  42. if (unlikely(sched_setscheduler(0, SCHED_IDLE, &param) == -1))
  43. #endif
  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. /* 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. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  563. total_secs = (double)total_diff.tv_sec +
  564. ((double)total_diff.tv_usec / 1000000.0);
  565. printf("[Rate (%ds): %.2f (avg): %.2f Mhash/s] [Accepted: %d Rejected: %d HW errors: %d] \r",
  566. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  567. accepted, rejected, hw_errors);
  568. fflush(stdout);
  569. applog(LOG_INFO, "[Rate (%ds): %.2f (avg): %.2f Mhash/s] [Accepted: %d Rejected: %d HW errors: %d]",
  570. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  571. accepted, rejected, hw_errors);
  572. local_mhashes_done = 0;
  573. out_unlock:
  574. pthread_mutex_unlock(&hash_lock);
  575. }
  576. /* This is overkill, but at least we'll know accurately how much work is
  577. * queued to prevent ever being left without work */
  578. static void inc_queued(void)
  579. {
  580. pthread_mutex_lock(&qd_lock);
  581. total_queued++;
  582. pthread_mutex_unlock(&qd_lock);
  583. }
  584. static void dec_queued(void)
  585. {
  586. pthread_mutex_lock(&qd_lock);
  587. total_queued--;
  588. pthread_mutex_unlock(&qd_lock);
  589. }
  590. static int requests_queued(void)
  591. {
  592. int ret;
  593. pthread_mutex_lock(&qd_lock);
  594. ret = total_queued;
  595. pthread_mutex_unlock(&qd_lock);
  596. return ret;
  597. }
  598. /* All work is queued flagged as being for thread 0 and then the mining thread
  599. * flags it as its own */
  600. static bool queue_request(void)
  601. {
  602. struct thr_info *thr = &thr_info[0];
  603. struct workio_cmd *wc;
  604. /* fill out work request message */
  605. wc = calloc(1, sizeof(*wc));
  606. if (unlikely(!wc)) {
  607. applog(LOG_ERR, "Failed to tq_pop in queue_request");
  608. return false;
  609. }
  610. wc->cmd = WC_GET_WORK;
  611. wc->thr = thr;
  612. /* send work request to workio thread */
  613. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  614. applog(LOG_ERR, "Failed to tq_push in queue_request");
  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. applog(LOG_WARNING, "Tried to discard_request with nil queued");
  628. return true;
  629. }
  630. work_heap = tq_pop(thr->q, NULL);
  631. if (unlikely(!work_heap)) {
  632. applog(LOG_ERR, "Failed to tq_pop in discard_request");
  633. return false;
  634. }
  635. free(work_heap);
  636. dec_queued();
  637. return true;
  638. }
  639. static void flush_requests(void)
  640. {
  641. int i, extra;
  642. extra = requests_queued();
  643. for (i = 0; i < extra; i++) {
  644. /* Queue a whole batch of new requests */
  645. if (unlikely(!queue_request())) {
  646. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  647. kill_work();
  648. break;
  649. }
  650. /* Pop off the old requests. Cancelling the requests would be better
  651. * but is tricky */
  652. if (unlikely(!discard_request())) {
  653. applog(LOG_ERR, "Failed to discard requests in flush_requests");
  654. kill_work();
  655. break;
  656. }
  657. }
  658. }
  659. static bool get_work(struct work *work, bool queued)
  660. {
  661. struct thr_info *thr = &thr_info[0];
  662. struct work *work_heap;
  663. bool ret = false;
  664. int failures = 0;
  665. retry:
  666. if (unlikely(!queued && !queue_request())) {
  667. applog(LOG_WARNING, "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_WARNING, "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. if (unlikely(ret == false)) {
  683. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  684. applog(LOG_ERR, "Failed %d times to get_work");
  685. return ret;
  686. }
  687. applog(LOG_WARNING, "Retrying after %d seconds", opt_fail_pause);
  688. sleep(opt_fail_pause);
  689. goto retry;
  690. }
  691. return ret;
  692. }
  693. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  694. {
  695. struct workio_cmd *wc;
  696. /* fill out work request message */
  697. wc = calloc(1, sizeof(*wc));
  698. if (unlikely(!wc)) {
  699. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  700. return false;
  701. }
  702. wc->u.work = malloc(sizeof(*work_in));
  703. if (unlikely(!wc->u.work)) {
  704. applog(LOG_ERR, "Failed to calloc work in submit_work_sync");
  705. goto err_out;
  706. }
  707. wc->cmd = WC_SUBMIT_WORK;
  708. wc->thr = thr;
  709. memcpy(wc->u.work, work_in, sizeof(*work_in));
  710. /* send solution to workio thread */
  711. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  712. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  713. goto err_out;
  714. }
  715. return true;
  716. err_out:
  717. workio_cmd_free(wc);
  718. return false;
  719. }
  720. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  721. {
  722. work->data[64+12+0] = (nonce>>0) & 0xff;
  723. work->data[64+12+1] = (nonce>>8) & 0xff;
  724. work->data[64+12+2] = (nonce>>16) & 0xff;
  725. work->data[64+12+3] = (nonce>>24) & 0xff;
  726. return submit_work_sync(thr, work);
  727. }
  728. static inline int cpu_from_thr_id(int thr_id)
  729. {
  730. return (thr_id - gpu_threads) % num_processors;
  731. }
  732. static void *miner_thread(void *userdata)
  733. {
  734. struct thr_info *mythr = userdata;
  735. const int thr_id = mythr->id;
  736. uint32_t max_nonce = 0xffffff;
  737. bool needs_work = true;
  738. /* Try to cycle approximately 5 times before each log update */
  739. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  740. /* Request the next work item at 2/3 of the scantime */
  741. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  742. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  743. bool requested = false;
  744. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  745. * and if that fails, then SCHED_BATCH. No need for this to be an
  746. * error if it fails */
  747. setpriority(PRIO_PROCESS, 0, 19);
  748. drop_policy();
  749. /* Cpu affinity only makes sense if the number of threads is a multiple
  750. * of the number of CPUs */
  751. if (!(opt_n_threads % num_processors))
  752. affine_to_cpu(thr_id - gpu_threads, cpu_from_thr_id(thr_id));
  753. while (1) {
  754. struct work work __attribute__((aligned(128)));
  755. unsigned long hashes_done;
  756. struct timeval tv_workstart, tv_start, tv_end, diff;
  757. uint64_t max64;
  758. bool rc;
  759. if (needs_work) {
  760. gettimeofday(&tv_workstart, NULL);
  761. /* obtain new work from internal workio thread */
  762. if (unlikely(!get_work(&work, requested))) {
  763. applog(LOG_ERR, "work retrieval failed, exiting "
  764. "mining thread %d", mythr->id);
  765. goto out;
  766. }
  767. work.thr_id = thr_id;
  768. needs_work = requested = false;
  769. work.blk.nonce = 0;
  770. }
  771. hashes_done = 0;
  772. gettimeofday(&tv_start, NULL);
  773. /* scan nonces for a proof-of-work hash */
  774. switch (opt_algo) {
  775. case ALGO_C:
  776. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  777. work.hash1, work.hash, work.target,
  778. max_nonce, &hashes_done,
  779. work.blk.nonce);
  780. break;
  781. #ifdef WANT_X8664_SSE2
  782. case ALGO_SSE2_64: {
  783. unsigned int rc5 =
  784. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  785. work.hash1, work.hash,
  786. work.target,
  787. max_nonce, &hashes_done,
  788. work.blk.nonce);
  789. rc = (rc5 == -1) ? false : true;
  790. }
  791. break;
  792. #endif
  793. #ifdef WANT_SSE2_4WAY
  794. case ALGO_4WAY: {
  795. unsigned int rc4 =
  796. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  797. work.hash1, work.hash,
  798. work.target,
  799. max_nonce, &hashes_done,
  800. work.blk.nonce);
  801. rc = (rc4 == -1) ? false : true;
  802. }
  803. break;
  804. #endif
  805. #ifdef WANT_VIA_PADLOCK
  806. case ALGO_VIA:
  807. rc = scanhash_via(thr_id, work.data, work.target,
  808. max_nonce, &hashes_done,
  809. work.blk.nonce);
  810. break;
  811. #endif
  812. case ALGO_CRYPTOPP:
  813. rc = scanhash_cryptopp(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. #ifdef WANT_CRYPTOPP_ASM32
  819. case ALGO_CRYPTOPP_ASM32:
  820. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  821. work.hash1, work.hash, work.target,
  822. max_nonce, &hashes_done,
  823. work.blk.nonce);
  824. break;
  825. #endif
  826. default:
  827. /* should never happen */
  828. goto out;
  829. }
  830. /* record scanhash elapsed time */
  831. gettimeofday(&tv_end, NULL);
  832. timeval_subtract(&diff, &tv_end, &tv_start);
  833. hashes_done -= work.blk.nonce;
  834. hashmeter(thr_id, &diff, hashes_done);
  835. work.blk.nonce += hashes_done;
  836. /* adjust max_nonce to meet target cycle time */
  837. if (diff.tv_usec > 500000)
  838. diff.tv_sec++;
  839. if (diff.tv_sec && diff.tv_sec != cycle) {
  840. max64 = work.blk.nonce +
  841. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  842. } else
  843. max64 = work.blk.nonce + hashes_done;
  844. if (max64 > 0xfffffffaULL)
  845. max64 = 0xfffffffaULL;
  846. max_nonce = max64;
  847. /* if nonce found, submit work */
  848. if (unlikely(rc)) {
  849. if (opt_debug)
  850. applog(LOG_DEBUG, "CPU %d found something?", cpu_from_thr_id(thr_id));
  851. if (unlikely(!submit_work_sync(mythr, &work))) {
  852. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  853. break;
  854. }
  855. work.blk.nonce += 4;
  856. }
  857. timeval_subtract(&diff, &tv_end, &tv_workstart);
  858. if (!requested && (diff.tv_sec > request_interval || work.blk.nonce > request_nonce)) {
  859. if (unlikely(!queue_request())) {
  860. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  861. goto out;
  862. }
  863. requested = true;
  864. }
  865. if (diff.tv_sec > opt_scantime || work_restart[thr_id].restart ||
  866. work.blk.nonce >= MAXTHREADS - hashes_done)
  867. needs_work = true;
  868. }
  869. out:
  870. tq_freeze(mythr->q);
  871. return NULL;
  872. }
  873. enum {
  874. STAT_SLEEP_INTERVAL = 1,
  875. STAT_CTR_INTERVAL = 10000000,
  876. FAILURE_INTERVAL = 30,
  877. };
  878. #ifdef HAVE_OPENCL
  879. static _clState *clStates[16];
  880. static inline cl_int queue_kernel_parameters(_clState *clState, dev_blk_ctx *blk)
  881. {
  882. cl_kernel *kernel = &clState->kernel;
  883. cl_int status = 0;
  884. int num = 0;
  885. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  886. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  887. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  888. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  889. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  890. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  891. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  892. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  893. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  894. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  895. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  896. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  897. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  898. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  899. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  900. if (clState->hasBitAlign == true) {
  901. /* Parameters for phatk kernel */
  902. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2);
  903. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  904. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  905. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4);
  906. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1);
  907. } else {
  908. /* Parameters for poclbm kernel */
  909. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  910. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  911. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  912. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  913. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  914. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  915. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  916. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  917. }
  918. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  919. (void *)&clState->outputBuffer);
  920. return status;
  921. }
  922. static inline int gpu_from_thr_id(int thr_id)
  923. {
  924. return thr_id % nDevs;
  925. }
  926. static void *gpuminer_thread(void *userdata)
  927. {
  928. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  929. struct timeval tv_start, tv_end, diff;
  930. struct thr_info *mythr = userdata;
  931. const int thr_id = mythr->id;
  932. uint32_t *res, *blank_res;
  933. size_t globalThreads[1];
  934. size_t localThreads[1];
  935. cl_int status;
  936. _clState *clState = clStates[thr_id];
  937. const cl_kernel *kernel = &clState->kernel;
  938. struct work *work = malloc(sizeof(struct work));
  939. unsigned const int threads = 1 << (15 + scan_intensity);
  940. unsigned const int vectors = clState->preferred_vwidth;
  941. unsigned const int hashes = threads * vectors;
  942. unsigned int hashes_done = 0;
  943. /* Request the next work item at 2/3 of the scantime */
  944. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  945. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  946. bool requested = false;
  947. res = calloc(BUFFERSIZE, 1);
  948. blank_res = calloc(BUFFERSIZE, 1);
  949. if (!res || !blank_res) {
  950. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  951. goto out;
  952. }
  953. gettimeofday(&tv_start, NULL);
  954. globalThreads[0] = threads;
  955. localThreads[0] = clState->work_size;
  956. diff.tv_sec = ~0UL;
  957. gettimeofday(&tv_end, NULL);
  958. while (1) {
  959. struct timeval tv_workstart;
  960. /* This finish flushes the readbuffer set with CL_FALSE later */
  961. clFinish(clState->commandQueue);
  962. if (diff.tv_sec > opt_scantime || work->blk.nonce >= MAXTHREADS - hashes || work_restart[thr_id].restart) {
  963. /* Ignore any reads since we're getting new work and queue a clean buffer */
  964. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  965. BUFFERSIZE, blank_res, 0, NULL, NULL);
  966. if (unlikely(status != CL_SUCCESS))
  967. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  968. memset(res, 0, BUFFERSIZE);
  969. gettimeofday(&tv_workstart, NULL);
  970. /* obtain new work from internal workio thread */
  971. if (unlikely(!get_work(work, requested))) {
  972. applog(LOG_ERR, "work retrieval failed, exiting "
  973. "gpu mining thread %d", mythr->id);
  974. goto out;
  975. }
  976. work->thr_id = thr_id;
  977. requested = false;
  978. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  979. work->blk.nonce = 0;
  980. work_restart[thr_id].restart = 0;
  981. if (opt_debug)
  982. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  983. /* Flushes the writebuffer set with CL_FALSE above */
  984. clFinish(clState->commandQueue);
  985. }
  986. status = queue_kernel_parameters(clState, &work->blk);
  987. if (unlikely(status != CL_SUCCESS))
  988. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  989. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  990. if (res[MAXBUFFERS]) {
  991. /* Clear the buffer again */
  992. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  993. BUFFERSIZE, blank_res, 0, NULL, NULL);
  994. if (unlikely(status != CL_SUCCESS))
  995. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  996. if (opt_debug)
  997. applog(LOG_DEBUG, "GPU %d found something?", gpu_from_thr_id(thr_id));
  998. postcalc_hash_async(mythr, work, res);
  999. memset(res, 0, BUFFERSIZE);
  1000. clFinish(clState->commandQueue);
  1001. }
  1002. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  1003. globalThreads, localThreads, 0, NULL, NULL);
  1004. if (unlikely(status != CL_SUCCESS))
  1005. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  1006. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1007. BUFFERSIZE, res, 0, NULL, NULL);
  1008. if (unlikely(status != CL_SUCCESS))
  1009. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  1010. gettimeofday(&tv_end, NULL);
  1011. timeval_subtract(&diff, &tv_end, &tv_start);
  1012. hashes_done += hashes;
  1013. work->blk.nonce += hashes;
  1014. if (diff.tv_usec > 500000)
  1015. diff.tv_sec++;
  1016. if (diff.tv_sec >= cycle) {
  1017. hashmeter(thr_id, &diff, hashes_done);
  1018. gettimeofday(&tv_start, NULL);
  1019. hashes_done = 0;
  1020. }
  1021. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1022. if (!requested && (diff.tv_sec > request_interval || work->blk.nonce > request_nonce)) {
  1023. if (unlikely(!queue_request())) {
  1024. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  1025. goto out;
  1026. }
  1027. requested = true;
  1028. }
  1029. }
  1030. out:
  1031. tq_freeze(mythr->q);
  1032. return NULL;
  1033. }
  1034. #endif /* HAVE_OPENCL */
  1035. static void restart_threads(void)
  1036. {
  1037. int i;
  1038. /* Discard old queued requests and get new ones */
  1039. flush_requests();
  1040. /* Queue extra requests for each worker thread since they'll all need
  1041. * new work. Each worker will set their "requested" flag to true
  1042. * should they receive a .restart */
  1043. for (i = 0; i < opt_n_threads + gpu_threads; i++) {
  1044. if (unlikely(!queue_request())) {
  1045. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  1046. kill_work();
  1047. return;
  1048. }
  1049. work_restart[i].restart = 1;
  1050. }
  1051. }
  1052. static void *longpoll_thread(void *userdata)
  1053. {
  1054. struct thr_info *mythr = userdata;
  1055. CURL *curl = NULL;
  1056. char *copy_start, *hdr_path, *lp_url = NULL;
  1057. bool need_slash = false;
  1058. int failures = 0;
  1059. hdr_path = tq_pop(mythr->q, NULL);
  1060. if (!hdr_path)
  1061. goto out;
  1062. /* full URL */
  1063. if (strstr(hdr_path, "://")) {
  1064. lp_url = hdr_path;
  1065. hdr_path = NULL;
  1066. }
  1067. /* absolute path, on current server */
  1068. else {
  1069. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  1070. if (rpc_url[strlen(rpc_url) - 1] != '/')
  1071. need_slash = true;
  1072. lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  1073. if (!lp_url)
  1074. goto out;
  1075. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  1076. }
  1077. applog(LOG_INFO, "Long-polling activated for %s", lp_url);
  1078. curl = curl_easy_init();
  1079. if (unlikely(!curl)) {
  1080. applog(LOG_ERR, "CURL initialisation failed");
  1081. goto out;
  1082. }
  1083. while (1) {
  1084. json_t *val;
  1085. val = json_rpc_call(curl, lp_url, rpc_userpass, rpc_req,
  1086. false, true);
  1087. if (likely(val)) {
  1088. failures = 0;
  1089. json_decref(val);
  1090. if (!opt_quiet)
  1091. printf("LONGPOLL detected new block \n");
  1092. applog(LOG_INFO, "LONGPOLL detected new block");
  1093. restart_threads();
  1094. } else {
  1095. if (failures++ < 10) {
  1096. sleep(30);
  1097. applog(LOG_ERR,
  1098. "longpoll failed, sleeping for 30s");
  1099. } else {
  1100. applog(LOG_ERR,
  1101. "longpoll failed, ending thread");
  1102. goto out;
  1103. }
  1104. }
  1105. }
  1106. out:
  1107. free(hdr_path);
  1108. free(lp_url);
  1109. tq_freeze(mythr->q);
  1110. if (curl)
  1111. curl_easy_cleanup(curl);
  1112. return NULL;
  1113. }
  1114. static void show_usage(void)
  1115. {
  1116. int i;
  1117. printf("cgminer version %s\n", VERSION);
  1118. #ifdef HAVE_OPENCL
  1119. printf("Built with CPU and GPU mining support.\n\n");
  1120. #else
  1121. printf("Built with CPU mining support only.\n\n");
  1122. #endif
  1123. printf("Usage:\tcgminer [options]\n\nSupported options:\n");
  1124. for (i = 0; i < ARRAY_SIZE(options_help); i++) {
  1125. struct option_help *h;
  1126. h = &options_help[i];
  1127. printf("--%s\n%s\n\n", h->name, h->helptext);
  1128. }
  1129. exit(1);
  1130. }
  1131. static void parse_arg (int key, char *arg)
  1132. {
  1133. int v, i;
  1134. switch(key) {
  1135. case 'a':
  1136. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  1137. if (algo_names[i] &&
  1138. !strcmp(arg, algo_names[i])) {
  1139. opt_algo = i;
  1140. break;
  1141. }
  1142. }
  1143. if (i == ARRAY_SIZE(algo_names))
  1144. show_usage();
  1145. break;
  1146. case 'c': {
  1147. json_error_t err;
  1148. if (opt_config)
  1149. json_decref(opt_config);
  1150. opt_config = json_load_file(arg, &err);
  1151. if (!json_is_object(opt_config)) {
  1152. applog(LOG_ERR, "JSON decode of %s failed", arg);
  1153. show_usage();
  1154. }
  1155. break;
  1156. }
  1157. case 'g':
  1158. v = atoi(arg);
  1159. if (v < 0 || v > 10)
  1160. show_usage();
  1161. opt_g_threads = v;
  1162. break;
  1163. case 'D':
  1164. opt_debug = true;
  1165. opt_log_output = true;
  1166. break;
  1167. case 'I':
  1168. v = atoi(arg);
  1169. if (v < 0 || v > 14) /* sanity check */
  1170. show_usage();
  1171. scan_intensity = v;
  1172. break;
  1173. case 'l':
  1174. v = atoi(arg);
  1175. if (v < 0 || v > 9999) /* sanity check */
  1176. show_usage();
  1177. opt_log_interval = v;
  1178. break;
  1179. case 'n':
  1180. opt_log_output = true;
  1181. opt_ndevs = true;
  1182. break;
  1183. case 'p':
  1184. free(rpc_pass);
  1185. rpc_pass = strdup(arg);
  1186. break;
  1187. case 'P':
  1188. opt_protocol = true;
  1189. break;
  1190. case 'Q':
  1191. v = atoi(arg);
  1192. if (v < 0 || v > 10)
  1193. show_usage();
  1194. opt_queue = v;
  1195. break;
  1196. case 'q':
  1197. opt_quiet = true;
  1198. break;
  1199. case 'r':
  1200. v = atoi(arg);
  1201. if (v < -1 || v > 9999) /* sanity check */
  1202. show_usage();
  1203. opt_retries = v;
  1204. break;
  1205. case 'R':
  1206. v = atoi(arg);
  1207. if (v < 1 || v > 9999) /* sanity check */
  1208. show_usage();
  1209. opt_fail_pause = v;
  1210. break;
  1211. case 's':
  1212. v = atoi(arg);
  1213. if (v < 1 || v > 9999) /* sanity check */
  1214. show_usage();
  1215. opt_scantime = v;
  1216. break;
  1217. case 't':
  1218. v = atoi(arg);
  1219. if (v < 0 || v > 9999) /* sanity check */
  1220. show_usage();
  1221. opt_n_threads = v;
  1222. break;
  1223. case 'u':
  1224. free(rpc_user);
  1225. rpc_user = strdup(arg);
  1226. break;
  1227. case 'V':
  1228. opt_log_output = true;
  1229. break;
  1230. case 'v':
  1231. v = atoi(arg);
  1232. if (v != 1 && v != 2 && v != 4)
  1233. show_usage();
  1234. opt_vectors = v;
  1235. break;
  1236. case 'w':
  1237. v = atoi(arg);
  1238. if (v < 1 || v > 9999) /* sanity check */
  1239. show_usage();
  1240. opt_worksize = v;
  1241. break;
  1242. case 'o': /* --url */
  1243. if (strncmp(arg, "http://", 7) &&
  1244. strncmp(arg, "https://", 8))
  1245. show_usage();
  1246. free(rpc_url);
  1247. rpc_url = strdup(arg);
  1248. break;
  1249. case 'O': /* --userpass */
  1250. if (!strchr(arg, ':'))
  1251. show_usage();
  1252. free(rpc_userpass);
  1253. rpc_userpass = strdup(arg);
  1254. break;
  1255. case 1003:
  1256. want_longpoll = false;
  1257. break;
  1258. case 1004:
  1259. use_syslog = true;
  1260. break;
  1261. case '?':
  1262. default:
  1263. show_usage();
  1264. }
  1265. }
  1266. static void parse_config(void)
  1267. {
  1268. int i;
  1269. json_t *val;
  1270. if (!json_is_object(opt_config))
  1271. return;
  1272. for (i = 0; i < ARRAY_SIZE(options); i++) {
  1273. if (!options[i].name)
  1274. break;
  1275. if (!strcmp(options[i].name, "config"))
  1276. continue;
  1277. val = json_object_get(opt_config, options[i].name);
  1278. if (!val)
  1279. continue;
  1280. if (options[i].has_arg && json_is_string(val)) {
  1281. char *s = strdup(json_string_value(val));
  1282. if (!s)
  1283. break;
  1284. parse_arg(options[i].val, s);
  1285. free(s);
  1286. } else if (!options[i].has_arg && json_is_true(val))
  1287. parse_arg(options[i].val, "");
  1288. else
  1289. applog(LOG_ERR, "JSON option %s invalid",
  1290. options[i].name);
  1291. }
  1292. }
  1293. static void parse_cmdline(int argc, char *argv[])
  1294. {
  1295. int key;
  1296. while (1) {
  1297. key = getopt_long(argc, argv, "a:c:Dg:I:l:no:O:p:PQ:qr:R:s:t:u:Vv:w:h?", options, NULL);
  1298. if (key < 0)
  1299. break;
  1300. parse_arg(key, optarg);
  1301. }
  1302. parse_config();
  1303. }
  1304. int main (int argc, char *argv[])
  1305. {
  1306. struct thr_info *thr;
  1307. unsigned int i;
  1308. char name[32];
  1309. struct cgpu_info *gpus = NULL, *cpus = NULL;
  1310. #ifdef WIN32
  1311. opt_n_threads = num_processors = 1;
  1312. #else
  1313. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  1314. opt_n_threads = num_processors;
  1315. #endif /* !WIN32 */
  1316. #ifdef HAVE_OPENCL
  1317. nDevs = clDevicesNum();
  1318. #endif
  1319. /* Invert the value to determine if we manually set it in cmdline
  1320. * or disable gpu threads */
  1321. if (nDevs)
  1322. opt_n_threads = - opt_n_threads;
  1323. rpc_url = strdup(DEF_RPC_URL);
  1324. /* parse command line */
  1325. parse_cmdline(argc, argv);
  1326. #ifdef HAVE_OPENCL
  1327. if (opt_ndevs) {
  1328. applog(LOG_INFO, "%i", nDevs);
  1329. return nDevs;
  1330. }
  1331. #endif
  1332. gpu_threads = nDevs * opt_g_threads;
  1333. if (opt_n_threads < 0) {
  1334. if (gpu_threads)
  1335. opt_n_threads = 0;
  1336. else
  1337. opt_n_threads = -opt_n_threads;
  1338. }
  1339. if (!rpc_userpass) {
  1340. if (!rpc_user || !rpc_pass) {
  1341. applog(LOG_ERR, "No login credentials supplied");
  1342. return 1;
  1343. }
  1344. rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  1345. if (!rpc_userpass)
  1346. return 1;
  1347. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  1348. }
  1349. if (unlikely(pthread_mutex_init(&time_lock, NULL)))
  1350. return 1;
  1351. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  1352. return 1;
  1353. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  1354. return 1;
  1355. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  1356. return 1;
  1357. #ifdef HAVE_SYSLOG_H
  1358. if (use_syslog)
  1359. openlog("cpuminer", LOG_PID, LOG_USER);
  1360. #endif
  1361. work_restart = calloc(opt_n_threads + gpu_threads, sizeof(*work_restart));
  1362. if (!work_restart)
  1363. return 1;
  1364. thr_info = calloc(opt_n_threads + 2 + gpu_threads, sizeof(*thr));
  1365. if (!thr_info)
  1366. return 1;
  1367. /* init workio thread info */
  1368. work_thr_id = opt_n_threads + gpu_threads;
  1369. thr = &thr_info[work_thr_id];
  1370. thr->id = work_thr_id;
  1371. thr->q = tq_new();
  1372. if (!thr->q)
  1373. return 1;
  1374. /* start work I/O thread */
  1375. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  1376. applog(LOG_ERR, "workio thread create failed");
  1377. return 1;
  1378. }
  1379. /* init longpoll thread info */
  1380. if (want_longpoll) {
  1381. longpoll_thr_id = opt_n_threads + gpu_threads + 1;
  1382. thr = &thr_info[longpoll_thr_id];
  1383. thr->id = longpoll_thr_id;
  1384. thr->q = tq_new();
  1385. if (!thr->q)
  1386. return 1;
  1387. /* start longpoll thread */
  1388. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  1389. applog(LOG_ERR, "longpoll thread create failed");
  1390. return 1;
  1391. }
  1392. pthread_detach(thr->pth);
  1393. } else
  1394. longpoll_thr_id = -1;
  1395. gettimeofday(&total_tv_start, NULL);
  1396. gettimeofday(&total_tv_end, NULL);
  1397. if (opt_n_threads ) {
  1398. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  1399. if (unlikely(!cpus)) {
  1400. applog(LOG_ERR, "Failed to calloc cpus");
  1401. return 1;
  1402. }
  1403. }
  1404. if (gpu_threads) {
  1405. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  1406. if (unlikely(!gpus)) {
  1407. applog(LOG_ERR, "Failed to calloc gpus");
  1408. return 1;
  1409. }
  1410. }
  1411. /* Put the extra work in the queue */
  1412. for (i = 0; i < opt_queue; i++) {
  1413. if (unlikely(!queue_request())) {
  1414. applog(LOG_ERR, "Failed to queue_request in main");
  1415. return 1;
  1416. }
  1417. }
  1418. #ifdef HAVE_OPENCL
  1419. /* start GPU mining threads */
  1420. for (i = 0; i < gpu_threads; i++) {
  1421. int gpu = gpu_from_thr_id(i);
  1422. thr = &thr_info[i];
  1423. thr->id = i;
  1424. gpus[gpu].is_gpu = 1;
  1425. gpus[gpu].cpu_gpu = gpu;
  1426. thr->cgpu = &gpus[gpu];
  1427. thr->q = tq_new();
  1428. if (!thr->q) {
  1429. applog(LOG_ERR, "tq_new failed in starting gpu mining threads");
  1430. return 1;
  1431. }
  1432. applog(LOG_INFO, "Init GPU thread %i", i);
  1433. clStates[i] = initCl(gpu, name, sizeof(name));
  1434. if (!clStates[i]) {
  1435. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  1436. continue;
  1437. }
  1438. applog(LOG_INFO, "initCl() finished. Found %s", name);
  1439. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1440. applog(LOG_ERR, "thread %d create failed", i);
  1441. return 1;
  1442. }
  1443. pthread_detach(thr->pth);
  1444. }
  1445. applog(LOG_INFO, "%d gpu miner threads started", i);
  1446. #endif
  1447. /* start CPU mining threads */
  1448. for (i = gpu_threads; i < gpu_threads + opt_n_threads; i++) {
  1449. int cpu = cpu_from_thr_id(i);
  1450. thr = &thr_info[i];
  1451. thr->id = i;
  1452. cpus[cpu].cpu_gpu = cpu;
  1453. thr->cgpu = &cpus[cpu];
  1454. thr->q = tq_new();
  1455. if (!thr->q) {
  1456. applog(LOG_ERR, "tq_new failed in starting cpu mining threads");
  1457. return 1;
  1458. }
  1459. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1460. applog(LOG_ERR, "thread %d create failed", i);
  1461. return 1;
  1462. }
  1463. pthread_detach(thr->pth);
  1464. }
  1465. applog(LOG_INFO, "%d cpu miner threads started, "
  1466. "using SHA256 '%s' algorithm.",
  1467. opt_n_threads,
  1468. algo_names[opt_algo]);
  1469. /* Restart count as it will be wrong till all threads are started */
  1470. pthread_mutex_lock(&hash_lock);
  1471. gettimeofday(&total_tv_start, NULL);
  1472. gettimeofday(&total_tv_end, NULL);
  1473. total_mhashes_done = 0;
  1474. pthread_mutex_unlock(&hash_lock);
  1475. /* main loop - simply wait for workio thread to exit */
  1476. pthread_join(thr_info[work_thr_id].pth, NULL);
  1477. curl_global_cleanup();
  1478. if (gpu_threads)
  1479. free(gpus);
  1480. if (opt_n_threads)
  1481. free(cpus);
  1482. applog(LOG_INFO, "workio thread dead, exiting.");
  1483. return 0;
  1484. }