driver-cpu.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2011-2014 Luke Dashjr
  4. * Copyright 2010 Jeff Garzik
  5. *
  6. * This program is free software; you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by the Free
  8. * Software Foundation; either version 3 of the License, or (at your option)
  9. * any later version. See COPYING for more details.
  10. */
  11. #include "config.h"
  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 <signal.h>
  19. #include <sys/stat.h>
  20. #include <sys/types.h>
  21. #ifndef WIN32
  22. #include <sys/wait.h>
  23. #include <sys/resource.h>
  24. #endif
  25. #include <libgen.h>
  26. #include "compat.h"
  27. #include "deviceapi.h"
  28. #include "miner.h"
  29. #include "logging.h"
  30. #include "util.h"
  31. #include "driver-cpu.h"
  32. #if defined(unix)
  33. #include <errno.h>
  34. #include <fcntl.h>
  35. #endif
  36. BFG_REGISTER_DRIVER(cpu_drv)
  37. #if defined(__linux) && defined(CPU_ZERO) /* Linux specific policy and affinity management */
  38. #include <sched.h>
  39. static inline void drop_policy(void)
  40. {
  41. struct sched_param param;
  42. param.sched_priority = 0;
  43. #ifdef SCHED_BATCH
  44. #ifdef SCHED_IDLE
  45. if (unlikely(sched_setscheduler(0, SCHED_IDLE, &param) == -1))
  46. #endif
  47. sched_setscheduler(0, SCHED_BATCH, &param);
  48. #endif
  49. }
  50. static inline void affine_to_cpu(int id, int cpu)
  51. {
  52. cpu_set_t set;
  53. CPU_ZERO(&set);
  54. CPU_SET(cpu, &set);
  55. sched_setaffinity(0, sizeof(set), &set);
  56. applog(LOG_INFO, "Binding cpu mining thread %d to cpu %d", id, cpu);
  57. }
  58. #else
  59. static inline void drop_policy(void)
  60. {
  61. }
  62. static inline void affine_to_cpu(int __maybe_unused id, int __maybe_unused cpu)
  63. {
  64. }
  65. #endif
  66. /* TODO: resolve externals */
  67. extern char *set_int_range(const char *arg, int *i, int min, int max);
  68. extern int dev_from_id(int thr_id);
  69. /* chipset-optimized hash functions */
  70. typedef bool (*sha256_func)(struct thr_info *, struct work *, uint32_t max_nonce, uint32_t *last_nonce, uint32_t nonce);
  71. extern bool ScanHash_4WaySSE2(struct thr_info *, struct work *, uint32_t max_nonce, uint32_t *last_nonce, uint32_t nonce);
  72. extern bool ScanHash_altivec_4way(struct thr_info *, struct work *, uint32_t max_nonce, uint32_t *last_nonce, uint32_t nonce);
  73. extern bool scanhash_via(struct thr_info *, struct work *, uint32_t max_nonce, uint32_t *last_nonce, uint32_t nonce);
  74. extern bool scanhash_c(struct thr_info *, struct work *, uint32_t max_nonce, uint32_t *last_nonce, uint32_t nonce);
  75. extern bool scanhash_cryptopp(struct thr_info *, struct work *, uint32_t max_nonce, uint32_t *last_nonce, uint32_t nonce);
  76. extern bool scanhash_asm32(struct thr_info *, struct work *, uint32_t max_nonce, uint32_t *last_nonce, uint32_t nonce);
  77. extern bool scanhash_sse2_64(struct thr_info *, struct work *, uint32_t max_nonce, uint32_t *last_nonce, uint32_t nonce);
  78. extern bool scanhash_sse4_64(struct thr_info *, struct work *, uint32_t max_nonce, uint32_t *last_nonce, uint32_t nonce);
  79. extern bool scanhash_sse2_32(struct thr_info *, struct work *, uint32_t max_nonce, uint32_t *last_nonce, uint32_t nonce);
  80. extern bool scanhash_scrypt(struct thr_info *, struct work *, uint32_t max_nonce, uint32_t *last_nonce, uint32_t nonce);
  81. #ifdef USE_SHA256D
  82. static size_t max_name_len = 0;
  83. static char *name_spaces_pad = NULL;
  84. #endif
  85. const char *algo_names[] = {
  86. #ifdef USE_SHA256D
  87. [ALGO_C] = "c",
  88. #ifdef WANT_SSE2_4WAY
  89. [ALGO_4WAY] = "4way",
  90. #endif
  91. #ifdef WANT_VIA_PADLOCK
  92. [ALGO_VIA] = "via",
  93. #endif
  94. [ALGO_CRYPTOPP] = "cryptopp",
  95. #ifdef WANT_CRYPTOPP_ASM32
  96. [ALGO_CRYPTOPP_ASM32] = "cryptopp_asm32",
  97. #endif
  98. #ifdef WANT_X8632_SSE2
  99. [ALGO_SSE2_32] = "sse2_32",
  100. #endif
  101. #ifdef WANT_X8664_SSE2
  102. [ALGO_SSE2_64] = "sse2_64",
  103. #endif
  104. #ifdef WANT_X8664_SSE4
  105. [ALGO_SSE4_64] = "sse4_64",
  106. #endif
  107. #ifdef WANT_ALTIVEC_4WAY
  108. [ALGO_ALTIVEC_4WAY] = "altivec_4way",
  109. #endif
  110. #endif
  111. #ifdef WANT_SCRYPT
  112. [ALGO_SCRYPT] = "scrypt",
  113. #endif
  114. #ifdef USE_SHA256D
  115. [ALGO_FASTAUTO] = "fastauto",
  116. [ALGO_AUTO] = "auto",
  117. #endif
  118. };
  119. #ifdef USE_SHA256D
  120. static const sha256_func sha256_funcs[] = {
  121. [ALGO_C] = (sha256_func)scanhash_c,
  122. #ifdef WANT_SSE2_4WAY
  123. [ALGO_4WAY] = (sha256_func)ScanHash_4WaySSE2,
  124. #endif
  125. #ifdef WANT_ALTIVEC_4WAY
  126. [ALGO_ALTIVEC_4WAY] = (sha256_func) ScanHash_altivec_4way,
  127. #endif
  128. #ifdef WANT_VIA_PADLOCK
  129. [ALGO_VIA] = (sha256_func)scanhash_via,
  130. #endif
  131. [ALGO_CRYPTOPP] = (sha256_func)scanhash_cryptopp,
  132. #ifdef WANT_CRYPTOPP_ASM32
  133. [ALGO_CRYPTOPP_ASM32] = (sha256_func)scanhash_asm32,
  134. #endif
  135. #ifdef WANT_X8632_SSE2
  136. [ALGO_SSE2_32] = (sha256_func)scanhash_sse2_32,
  137. #endif
  138. #ifdef WANT_X8664_SSE2
  139. [ALGO_SSE2_64] = (sha256_func)scanhash_sse2_64,
  140. #endif
  141. #ifdef WANT_X8664_SSE4
  142. [ALGO_SSE4_64] = (sha256_func)scanhash_sse4_64,
  143. #endif
  144. };
  145. #endif
  146. #ifdef USE_SHA256D
  147. enum sha256_algos opt_algo = ALGO_FASTAUTO;
  148. #endif
  149. static bool forced_n_threads;
  150. #ifdef USE_SHA256D
  151. const uint32_t hash1_init[] = {
  152. 0,0,0,0,0,0,0,0,
  153. 0x80000000,
  154. 0,0,0,0,0,0,
  155. 0x100,
  156. };
  157. // Algo benchmark, crash-prone, system independent stage
  158. double bench_algo_stage3(
  159. enum sha256_algos algo
  160. )
  161. {
  162. struct work work __attribute__((aligned(128)));
  163. get_benchmark_work(&work, false);
  164. static struct thr_info dummy;
  165. struct timeval end;
  166. struct timeval start;
  167. uint32_t max_nonce = opt_algo == ALGO_FASTAUTO ? (1<<8) : (1<<22);
  168. uint32_t last_nonce = 0;
  169. timer_set_now(&start);
  170. {
  171. sha256_func func = sha256_funcs[algo];
  172. (*func)(
  173. &dummy,
  174. &work,
  175. max_nonce,
  176. &last_nonce,
  177. 0
  178. );
  179. }
  180. timer_set_now(&end);
  181. uint64_t usec_end = ((uint64_t)end.tv_sec)*1000*1000 + end.tv_usec;
  182. uint64_t usec_start = ((uint64_t)start.tv_sec)*1000*1000 + start.tv_usec;
  183. uint64_t usec_elapsed = usec_end - usec_start;
  184. double rate = -1.0;
  185. if (0<usec_elapsed) {
  186. rate = (1.0*(last_nonce+1))/usec_elapsed;
  187. }
  188. return rate;
  189. }
  190. #if defined(unix)
  191. // Change non-blocking status on a file descriptor
  192. static void set_non_blocking(
  193. int fd,
  194. int yes
  195. )
  196. {
  197. int flags = fcntl(fd, F_GETFL, 0);
  198. if (flags<0) {
  199. perror("fcntl(GET) failed");
  200. exit(1);
  201. }
  202. flags = yes ? (flags|O_NONBLOCK) : (flags&~O_NONBLOCK);
  203. int r = fcntl(fd, F_SETFL, flags);
  204. if (r<0) {
  205. perror("fcntl(SET) failed");
  206. exit(1);
  207. }
  208. }
  209. #endif // defined(unix)
  210. // Algo benchmark, crash-safe, system-dependent stage
  211. static double bench_algo_stage2(
  212. enum sha256_algos algo
  213. )
  214. {
  215. // Here, the gig is to safely run a piece of code that potentially
  216. // crashes. Unfortunately, the Right Way (tm) to do this is rather
  217. // heavily platform dependent :(
  218. double rate = -1.23457;
  219. #if defined(unix)
  220. // Make a pipe: [readFD, writeFD]
  221. int pfd[2];
  222. int r = pipe(pfd);
  223. if (r<0) {
  224. perror("pipe - failed to create pipe for --algo auto");
  225. exit(1);
  226. }
  227. // Make pipe non blocking
  228. set_non_blocking(pfd[0], 1);
  229. set_non_blocking(pfd[1], 1);
  230. // Don't allow a crashing child to kill the main process
  231. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  232. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  233. if (SIG_ERR==sr0 || SIG_ERR==sr1) {
  234. perror("signal - failed to edit signal mask for --algo auto");
  235. exit(1);
  236. }
  237. // Fork a child to do the actual benchmarking
  238. pid_t child_pid = fork();
  239. if (child_pid<0) {
  240. perror("fork - failed to create a child process for --algo auto");
  241. exit(1);
  242. }
  243. // Do the dangerous work in the child, knowing we might crash
  244. if (0==child_pid) {
  245. // TODO: some umask trickery to prevent coredumps
  246. // Benchmark this algorithm
  247. double r = bench_algo_stage3(algo);
  248. // We survived, send result to parent and bail
  249. int loop_count = 0;
  250. while (1) {
  251. ssize_t bytes_written = write(pfd[1], &r, sizeof(r));
  252. int try_again = (0==bytes_written || (bytes_written<0 && EAGAIN==errno));
  253. int success = (sizeof(r)==(size_t)bytes_written);
  254. if (success)
  255. break;
  256. if (!try_again) {
  257. perror("write - child failed to write benchmark result to pipe");
  258. exit(1);
  259. }
  260. if (5<loop_count) {
  261. applog(LOG_ERR, "child tried %d times to communicate with parent, giving up", loop_count);
  262. exit(1);
  263. }
  264. ++loop_count;
  265. sleep(1);
  266. }
  267. exit(0);
  268. }
  269. // Parent waits for a result from child
  270. int loop_count = 0;
  271. while (1) {
  272. // Wait for child to die
  273. int status;
  274. int r = waitpid(child_pid, &status, WNOHANG);
  275. if ((child_pid==r) || (r<0 && ECHILD==errno)) {
  276. // Child died somehow. Grab result and bail
  277. double tmp;
  278. ssize_t bytes_read = read(pfd[0], &tmp, sizeof(tmp));
  279. if (sizeof(tmp)==(size_t)bytes_read)
  280. rate = tmp;
  281. break;
  282. } else if (r<0) {
  283. perror("bench_algo: waitpid failed. giving up.");
  284. exit(1);
  285. }
  286. // Give up on child after a ~60s
  287. if (60<loop_count) {
  288. kill(child_pid, SIGKILL);
  289. waitpid(child_pid, &status, 0);
  290. break;
  291. }
  292. // Wait a bit longer
  293. ++loop_count;
  294. sleep(1);
  295. }
  296. // Close pipe
  297. r = close(pfd[0]);
  298. if (r<0) {
  299. perror("close - failed to close read end of pipe for --algo auto");
  300. exit(1);
  301. }
  302. r = close(pfd[1]);
  303. if (r<0) {
  304. perror("close - failed to close read end of pipe for --algo auto");
  305. exit(1);
  306. }
  307. #elif defined(WIN32)
  308. // Get handle to current exe
  309. HINSTANCE module = GetModuleHandle(0);
  310. if (!module) {
  311. applog(LOG_ERR, "failed to retrieve module handle");
  312. exit(1);
  313. }
  314. // Create a unique name
  315. char unique_name[33];
  316. snprintf(
  317. unique_name,
  318. sizeof(unique_name)-1,
  319. "bfgminer-%p",
  320. (void*)module
  321. );
  322. // Create and init a chunked of shared memory
  323. HANDLE map_handle = CreateFileMapping(
  324. INVALID_HANDLE_VALUE, // use paging file
  325. NULL, // default security attributes
  326. PAGE_READWRITE, // read/write access
  327. 0, // size: high 32-bits
  328. 4096, // size: low 32-bits
  329. unique_name // name of map object
  330. );
  331. if (NULL==map_handle) {
  332. applog(LOG_ERR, "could not create shared memory");
  333. exit(1);
  334. }
  335. void *shared_mem = MapViewOfFile(
  336. map_handle, // object to map view of
  337. FILE_MAP_WRITE, // read/write access
  338. 0, // high offset: map from
  339. 0, // low offset: beginning
  340. 0 // default: map entire file
  341. );
  342. if (NULL==shared_mem) {
  343. applog(LOG_ERR, "could not map shared memory");
  344. exit(1);
  345. }
  346. SetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name);
  347. CopyMemory(shared_mem, &rate, sizeof(rate));
  348. // Get path to current exe
  349. char cmd_line[256 + MAX_PATH];
  350. const size_t n = sizeof(cmd_line)-200;
  351. DWORD size = GetModuleFileName(module, cmd_line, n);
  352. if (0==size) {
  353. applog(LOG_ERR, "failed to retrieve module path");
  354. exit(1);
  355. }
  356. // Construct new command line based on that
  357. char buf[0x20];
  358. snprintf(buf, sizeof(buf), "%d", algo);
  359. SetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf);
  360. // Launch a debug copy of BFGMiner
  361. STARTUPINFO startup_info;
  362. PROCESS_INFORMATION process_info;
  363. ZeroMemory(&startup_info, sizeof(startup_info));
  364. ZeroMemory(&process_info, sizeof(process_info));
  365. startup_info.cb = sizeof(startup_info);
  366. BOOL ok = CreateProcess(
  367. NULL, // No module name (use command line)
  368. cmd_line, // Command line
  369. NULL, // Process handle not inheritable
  370. NULL, // Thread handle not inheritable
  371. FALSE, // Set handle inheritance to FALSE
  372. DEBUG_ONLY_THIS_PROCESS,// We're going to debug the child
  373. NULL, // Use parent's environment block
  374. NULL, // Use parent's starting directory
  375. &startup_info, // Pointer to STARTUPINFO structure
  376. &process_info // Pointer to PROCESS_INFORMATION structure
  377. );
  378. if (!ok) {
  379. applog(LOG_ERR, "CreateProcess failed with error %ld\n", (long)GetLastError() );
  380. exit(1);
  381. }
  382. // Debug the child (only clean way to catch exceptions)
  383. while (1) {
  384. // Wait for child to do something
  385. DEBUG_EVENT debug_event;
  386. ZeroMemory(&debug_event, sizeof(debug_event));
  387. BOOL ok = WaitForDebugEvent(&debug_event, 60 * 1000);
  388. if (!ok)
  389. break;
  390. // Decide if event is "normal"
  391. int go_on =
  392. CREATE_PROCESS_DEBUG_EVENT== debug_event.dwDebugEventCode ||
  393. CREATE_THREAD_DEBUG_EVENT == debug_event.dwDebugEventCode ||
  394. EXIT_THREAD_DEBUG_EVENT == debug_event.dwDebugEventCode ||
  395. EXCEPTION_DEBUG_EVENT == debug_event.dwDebugEventCode ||
  396. LOAD_DLL_DEBUG_EVENT == debug_event.dwDebugEventCode ||
  397. OUTPUT_DEBUG_STRING_EVENT == debug_event.dwDebugEventCode ||
  398. UNLOAD_DLL_DEBUG_EVENT == debug_event.dwDebugEventCode;
  399. if (!go_on)
  400. break;
  401. // Some exceptions are also "normal", apparently.
  402. if (EXCEPTION_DEBUG_EVENT== debug_event.dwDebugEventCode) {
  403. int go_on =
  404. EXCEPTION_BREAKPOINT== debug_event.u.Exception.ExceptionRecord.ExceptionCode;
  405. if (!go_on)
  406. break;
  407. }
  408. // If nothing unexpected happened, let child proceed
  409. ContinueDebugEvent(
  410. debug_event.dwProcessId,
  411. debug_event.dwThreadId,
  412. DBG_CONTINUE
  413. );
  414. }
  415. // Clean up child process
  416. TerminateProcess(process_info.hProcess, 1);
  417. CloseHandle(process_info.hProcess);
  418. CloseHandle(process_info.hThread);
  419. // Reap return value and cleanup
  420. CopyMemory(&rate, shared_mem, sizeof(rate));
  421. (void)UnmapViewOfFile(shared_mem);
  422. (void)CloseHandle(map_handle);
  423. #else
  424. // Not linux, not unix, not WIN32 ... do our best
  425. rate = bench_algo_stage3(algo);
  426. #endif // defined(unix)
  427. // Done
  428. return rate;
  429. }
  430. static void bench_algo(
  431. double *best_rate,
  432. enum sha256_algos *best_algo,
  433. enum sha256_algos algo
  434. )
  435. {
  436. size_t n = max_name_len - strlen(algo_names[algo]);
  437. memset(name_spaces_pad, ' ', n);
  438. name_spaces_pad[n] = 0;
  439. applog(
  440. LOG_ERR,
  441. "\"%s\"%s : benchmarking algorithm ...",
  442. algo_names[algo],
  443. name_spaces_pad
  444. );
  445. double rate = bench_algo_stage2(algo);
  446. if (rate<0.0) {
  447. applog(
  448. LOG_ERR,
  449. "\"%s\"%s : algorithm fails on this platform",
  450. algo_names[algo],
  451. name_spaces_pad
  452. );
  453. } else {
  454. applog(
  455. LOG_ERR,
  456. "\"%s\"%s : algorithm runs at %.5f MH/s",
  457. algo_names[algo],
  458. name_spaces_pad,
  459. rate
  460. );
  461. if (*best_rate<rate) {
  462. *best_rate = rate;
  463. *best_algo = algo;
  464. }
  465. }
  466. }
  467. // Figure out the longest algorithm name
  468. void init_max_name_len()
  469. {
  470. size_t i;
  471. size_t nb_names = sizeof(algo_names)/sizeof(algo_names[0]);
  472. for (i=0; i<nb_names; ++i) {
  473. const char *p = algo_names[i];
  474. size_t name_len = p ? strlen(p) : 0;
  475. if (max_name_len<name_len)
  476. max_name_len = name_len;
  477. }
  478. name_spaces_pad = (char*) malloc(max_name_len+16);
  479. if (0==name_spaces_pad) {
  480. perror("malloc failed");
  481. exit(1);
  482. }
  483. }
  484. // Pick the fastest CPU hasher
  485. static enum sha256_algos pick_fastest_algo()
  486. {
  487. double best_rate = -1.0;
  488. enum sha256_algos best_algo = 0;
  489. applog(LOG_ERR, "benchmarking all sha256 algorithms ...");
  490. bench_algo(&best_rate, &best_algo, ALGO_C);
  491. #if defined(WANT_SSE2_4WAY)
  492. bench_algo(&best_rate, &best_algo, ALGO_4WAY);
  493. #endif
  494. #if defined(WANT_VIA_PADLOCK)
  495. bench_algo(&best_rate, &best_algo, ALGO_VIA);
  496. #endif
  497. bench_algo(&best_rate, &best_algo, ALGO_CRYPTOPP);
  498. #if defined(WANT_CRYPTOPP_ASM32)
  499. bench_algo(&best_rate, &best_algo, ALGO_CRYPTOPP_ASM32);
  500. #endif
  501. #if defined(WANT_X8632_SSE2)
  502. bench_algo(&best_rate, &best_algo, ALGO_SSE2_32);
  503. #endif
  504. #if defined(WANT_X8664_SSE2)
  505. bench_algo(&best_rate, &best_algo, ALGO_SSE2_64);
  506. #endif
  507. #if defined(WANT_X8664_SSE4)
  508. bench_algo(&best_rate, &best_algo, ALGO_SSE4_64);
  509. #endif
  510. #if defined(WANT_ALTIVEC_4WAY)
  511. bench_algo(&best_rate, &best_algo, ALGO_ALTIVEC_4WAY);
  512. #endif
  513. size_t n = max_name_len - strlen(algo_names[best_algo]);
  514. memset(name_spaces_pad, ' ', n);
  515. name_spaces_pad[n] = 0;
  516. applog(
  517. LOG_ERR,
  518. "\"%s\"%s : is fastest algorithm at %.5f MH/s",
  519. algo_names[best_algo],
  520. name_spaces_pad,
  521. best_rate
  522. );
  523. return best_algo;
  524. }
  525. char *set_algo(const char *arg, enum sha256_algos *algo)
  526. {
  527. enum sha256_algos i;
  528. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  529. if (algo_names[i] && !strcmp(arg, algo_names[i])) {
  530. *algo = i;
  531. return NULL;
  532. }
  533. }
  534. return "Unknown algorithm";
  535. }
  536. void show_algo(char buf[OPT_SHOW_LEN], const enum sha256_algos *algo)
  537. {
  538. strncpy(buf, algo_names[*algo], OPT_SHOW_LEN);
  539. }
  540. #endif /* USE_SHA256D */
  541. char *force_nthreads_int(const char *arg, int *i)
  542. {
  543. forced_n_threads = true;
  544. return set_int_range(arg, i, 0, 9999);
  545. }
  546. static int cpu_autodetect()
  547. {
  548. RUNONCE(0);
  549. int i;
  550. // Reckon number of cores in the box
  551. #if defined(WIN32)
  552. {
  553. DWORD_PTR system_am;
  554. DWORD_PTR process_am;
  555. BOOL ok = GetProcessAffinityMask(
  556. GetCurrentProcess(),
  557. &system_am,
  558. &process_am
  559. );
  560. if (!ok) {
  561. applog(LOG_ERR, "couldn't figure out number of processors :(");
  562. num_processors = 1;
  563. } else {
  564. size_t n = 32;
  565. num_processors = 0;
  566. while (n--)
  567. if (process_am & (1<<n))
  568. ++num_processors;
  569. }
  570. }
  571. #elif defined(_SC_NPROCESSORS_CONF)
  572. num_processors = sysconf(_SC_NPROCESSORS_CONF);
  573. #elif defined(CTL_HW) && defined(HW_NCPU)
  574. int req[] = { CTL_HW, HW_NCPU };
  575. size_t len = sizeof(num_processors);
  576. sysctl(req, 2, &num_processors, &len, NULL, 0);
  577. #else
  578. num_processors = 1;
  579. #endif /* !WIN32 */
  580. if (opt_n_threads < 0 || !forced_n_threads) {
  581. opt_n_threads = num_processors;
  582. }
  583. if (num_processors < 1)
  584. return 0;
  585. cpus = calloc(opt_n_threads, sizeof(struct cgpu_info));
  586. if (unlikely(!cpus))
  587. quit(1, "Failed to calloc cpus");
  588. for (i = 0; i < opt_n_threads; ++i) {
  589. struct cgpu_info *cgpu;
  590. cgpu = &cpus[i];
  591. cgpu->drv = &cpu_drv;
  592. cgpu->deven = DEV_ENABLED;
  593. cgpu->threads = 1;
  594. #ifdef USE_SHA256D
  595. cgpu->kname = algo_names[opt_algo];
  596. #endif
  597. add_cgpu(cgpu);
  598. }
  599. return opt_n_threads;
  600. }
  601. static void cpu_detect()
  602. {
  603. noserial_detect_manual(&cpu_drv, cpu_autodetect);
  604. }
  605. static pthread_mutex_t cpualgo_lock;
  606. static bool cpu_thread_prepare(struct thr_info *thr)
  607. {
  608. struct cgpu_info *cgpu = thr->cgpu;
  609. if (!(cgpu->device_id || thr->device_thread || cgpu->proc_id))
  610. mutex_init(&cpualgo_lock);
  611. thread_reportin(thr);
  612. return true;
  613. }
  614. static uint64_t cpu_can_limit_work(struct thr_info __maybe_unused *thr)
  615. {
  616. return 0xffff;
  617. }
  618. static bool cpu_thread_init(struct thr_info *thr)
  619. {
  620. const int thr_id = thr->id;
  621. #ifdef USE_SHA256D
  622. struct cgpu_info *cgpu = thr->cgpu;
  623. mutex_lock(&cpualgo_lock);
  624. switch (opt_algo)
  625. {
  626. case ALGO_AUTO:
  627. case ALGO_FASTAUTO:
  628. opt_algo = pick_fastest_algo();
  629. default:
  630. break;
  631. }
  632. mutex_unlock(&cpualgo_lock);
  633. cgpu->kname = algo_names[opt_algo];
  634. #endif
  635. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  636. * and if that fails, then SCHED_BATCH. No need for this to be an
  637. * error if it fails */
  638. setpriority(PRIO_PROCESS, 0, 19);
  639. drop_policy();
  640. /* Cpu affinity only makes sense if the number of threads is a multiple
  641. * of the number of CPUs */
  642. if (num_processors > 1 && opt_n_threads % num_processors == 0)
  643. affine_to_cpu(dev_from_id(thr_id), dev_from_id(thr_id) % num_processors);
  644. return true;
  645. }
  646. static
  647. float cpu_min_nonce_diff(struct cgpu_info * const proc, const struct mining_algorithm * const malgo)
  648. {
  649. return minimum_pdiff;
  650. }
  651. static
  652. bool scanhash_generic(struct thr_info * const thr, struct work * const work, const uint32_t max_nonce, uint32_t * const last_nonce, uint32_t n)
  653. {
  654. struct mining_algorithm * const malgo = work_mining_algorithm(work);
  655. void (* const hash_data_f)(void *, const void *) = malgo->hash_data_f;
  656. uint8_t * const hash = work->hash;
  657. uint8_t *data = work->data;
  658. const uint8_t * const target = work->target;
  659. uint32_t * const out_nonce = (uint32_t *)&data[0x4c];
  660. bool ret = false;
  661. const uint32_t hash7_targ = le32toh(((const uint32_t *)target)[7]);
  662. uint32_t * const hash7_tmp = &((uint32_t *)hash)[7];
  663. while (true)
  664. {
  665. *out_nonce = n;
  666. hash_data_f(hash, data);
  667. if (unlikely(le32toh(*hash7_tmp) <= hash7_targ))
  668. {
  669. ret = true;
  670. break;
  671. }
  672. if ((n >= max_nonce) || thr->work_restart)
  673. break;
  674. n++;
  675. }
  676. *last_nonce = n;
  677. return ret;
  678. }
  679. static int64_t cpu_scanhash(struct thr_info *thr, struct work *work, int64_t max_nonce)
  680. {
  681. uint32_t first_nonce = work->blk.nonce;
  682. uint32_t last_nonce;
  683. bool rc;
  684. CPUSearch:
  685. last_nonce = first_nonce;
  686. rc = false;
  687. /* scan nonces for a proof-of-work hash */
  688. {
  689. sha256_func func = scanhash_generic;
  690. switch (work_mining_algorithm(work)->algo)
  691. {
  692. #ifdef USE_SCRYPT
  693. case POW_SCRYPT:
  694. func = scanhash_scrypt;
  695. break;
  696. #endif
  697. #ifdef USE_SHA256D
  698. case POW_SHA256D:
  699. if (work->nonce_diff >= 1.)
  700. func = sha256_funcs[opt_algo];
  701. break;
  702. #endif
  703. default:
  704. break;
  705. }
  706. if (unlikely(!func))
  707. applogr(0, LOG_ERR, "%"PRIpreprv": Unknown mining algorithm", thr->cgpu->proc_repr);
  708. rc = (*func)(
  709. thr,
  710. work,
  711. max_nonce,
  712. &last_nonce,
  713. work->blk.nonce
  714. );
  715. }
  716. /* if nonce found, submit work */
  717. if (unlikely(rc)) {
  718. applog(LOG_DEBUG, "%"PRIpreprv" found something?", thr->cgpu->proc_repr);
  719. submit_nonce(thr, work, le32toh(*(uint32_t*)&work->data[76]));
  720. work->blk.nonce = last_nonce + 1;
  721. goto CPUSearch;
  722. }
  723. else
  724. if (unlikely(last_nonce == first_nonce))
  725. return 0;
  726. work->blk.nonce = last_nonce + 1;
  727. return last_nonce - first_nonce + 1;
  728. }
  729. struct device_drv cpu_drv = {
  730. .dname = "cpu",
  731. .name = "CPU",
  732. .probe_priority = 120,
  733. .drv_min_nonce_diff = cpu_min_nonce_diff,
  734. .drv_detect = cpu_detect,
  735. .thread_prepare = cpu_thread_prepare,
  736. .can_limit_work = cpu_can_limit_work,
  737. .thread_init = cpu_thread_init,
  738. .scanhash = cpu_scanhash,
  739. };