driver-cpu.c 20 KB

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