driver-cpu.c 21 KB

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