driver-cpu.c 21 KB

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