driver-cpu.c 21 KB

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