cpu-miner.c 39 KB

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