driver-cpu.c 21 KB

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