device-cpu.c 18 KB

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