driver-cpu.c 21 KB

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