driver-cpu.c 21 KB

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