driver-cpu.c 20 KB

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