driver-cpu.c 21 KB

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