driver-cpu.c 21 KB

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