driver-cpu.c 21 KB

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