driver-cpu.c 21 KB

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