main.c 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988
  1. /*
  2. * Copyright 2011 Con Kolivas
  3. * Copyright 2010 Jeff Garzik
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the Free
  7. * Software Foundation; either version 2 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #include "config.h"
  11. #include <curses.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 <sys/time.h>
  19. #include <time.h>
  20. #include <math.h>
  21. #include <stdarg.h>
  22. #include <assert.h>
  23. #include <signal.h>
  24. #ifndef WIN32
  25. #include <sys/resource.h>
  26. #endif
  27. #include <ccan/opt/opt.h>
  28. #include <jansson.h>
  29. #include <curl/curl.h>
  30. #include "compat.h"
  31. #include "miner.h"
  32. #include "findnonce.h"
  33. #include "ocl.h"
  34. #define PROGRAM_NAME "cgminer"
  35. #define DEF_RPC_URL "http://127.0.0.1:8332/"
  36. #define DEF_RPC_USERNAME "rpcuser"
  37. #define DEF_RPC_PASSWORD "rpcpass"
  38. #define DEF_RPC_USERPASS DEF_RPC_USERNAME ":" DEF_RPC_PASSWORD
  39. #ifdef __linux /* Linux specific policy and affinity management */
  40. #include <sched.h>
  41. static inline void drop_policy(void)
  42. {
  43. struct sched_param param;
  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 id, int cpu)
  64. {
  65. }
  66. #endif
  67. enum workio_commands {
  68. WC_GET_WORK,
  69. WC_SUBMIT_WORK,
  70. WC_DIE,
  71. };
  72. struct workio_cmd {
  73. enum workio_commands cmd;
  74. struct thr_info *thr;
  75. union {
  76. struct work *work;
  77. } u;
  78. bool lagging;
  79. };
  80. enum sha256_algos {
  81. ALGO_C, /* plain C */
  82. ALGO_4WAY, /* parallel SSE2 */
  83. ALGO_VIA, /* VIA padlock */
  84. ALGO_CRYPTOPP, /* Crypto++ (C) */
  85. ALGO_CRYPTOPP_ASM32, /* Crypto++ 32-bit assembly */
  86. ALGO_SSE2_64, /* SSE2 for x86_64 */
  87. ALGO_SSE4_64, /* SSE4 for x86_64 */
  88. };
  89. enum pool_strategy {
  90. POOL_FAILOVER,
  91. POOL_ROUNDROBIN,
  92. POOL_ROTATE,
  93. POOL_LOADBALANCE,
  94. };
  95. #define TOP_STRATEGY (POOL_LOADBALANCE)
  96. struct strategies {
  97. const char *s;
  98. } strategies[] = {
  99. { "Failover" },
  100. { "Round Robin" },
  101. { "Rotate" },
  102. { "Load Balance" },
  103. };
  104. static const char *algo_names[] = {
  105. [ALGO_C] = "c",
  106. #ifdef WANT_SSE2_4WAY
  107. [ALGO_4WAY] = "4way",
  108. #endif
  109. #ifdef WANT_VIA_PADLOCK
  110. [ALGO_VIA] = "via",
  111. #endif
  112. [ALGO_CRYPTOPP] = "cryptopp",
  113. #ifdef WANT_CRYPTOPP_ASM32
  114. [ALGO_CRYPTOPP_ASM32] = "cryptopp_asm32",
  115. #endif
  116. #ifdef WANT_X8664_SSE2
  117. [ALGO_SSE2_64] = "sse2_64",
  118. #endif
  119. #ifdef WANT_X8664_SSE4
  120. [ALGO_SSE4_64] = "sse4_64",
  121. #endif
  122. };
  123. bool opt_debug = false;
  124. bool opt_protocol = false;
  125. bool want_longpoll = true;
  126. bool have_longpoll = false;
  127. bool use_syslog = false;
  128. static bool opt_quiet = false;
  129. static bool opt_realquiet = false;
  130. static bool opt_loginput = false;
  131. static int opt_retries = -1;
  132. static int opt_fail_pause = 5;
  133. static int opt_log_interval = 5;
  134. bool opt_log_output = false;
  135. static bool opt_dynamic = true;
  136. static int opt_queue;
  137. int opt_vectors;
  138. int opt_worksize;
  139. int opt_scantime = 60;
  140. static const bool opt_time = true;
  141. #if defined(WANT_X8664_SSE4) && defined(__SSE4_1__)
  142. static enum sha256_algos opt_algo = ALGO_SSE4_64;
  143. #elif defined(WANT_X8664_SSE2) && defined(__SSE2__)
  144. static enum sha256_algos opt_algo = ALGO_SSE2_64;
  145. #else
  146. static enum sha256_algos opt_algo = ALGO_C;
  147. #endif
  148. static int nDevs;
  149. static int opt_g_threads = 2;
  150. static int opt_device;
  151. static int total_devices;
  152. static bool gpu_devices[16];
  153. static int gpu_threads;
  154. static bool forced_n_threads;
  155. static int opt_n_threads;
  156. static int mining_threads;
  157. static int num_processors;
  158. static int scan_intensity;
  159. static bool use_curses = true;
  160. #define QUIET (opt_quiet || opt_realquiet)
  161. struct thr_info *thr_info;
  162. static int work_thr_id;
  163. int longpoll_thr_id;
  164. static int stage_thr_id;
  165. static int watchdog_thr_id;
  166. static int input_thr_id;
  167. static int total_threads;
  168. struct work_restart *work_restart = NULL;
  169. static pthread_mutex_t hash_lock;
  170. static pthread_mutex_t qd_lock;
  171. static pthread_mutex_t stgd_lock;
  172. static pthread_mutex_t curses_lock;
  173. static double total_mhashes_done;
  174. static struct timeval total_tv_start, total_tv_end;
  175. pthread_mutex_t control_lock;
  176. int hw_errors;
  177. static int total_accepted, total_rejected;
  178. static int total_getworks, total_stale, total_discarded;
  179. static int total_queued, total_staged, lp_staged;
  180. static unsigned int new_blocks;
  181. enum block_change {
  182. BLOCK_NONE,
  183. BLOCK_LP,
  184. BLOCK_DETECT,
  185. BLOCK_FIRST,
  186. };
  187. static enum block_change block_changed = BLOCK_FIRST;
  188. static unsigned int local_work;
  189. static unsigned int total_lo, total_ro;
  190. #define MAX_POOLS (32)
  191. static struct pool *pools[MAX_POOLS];
  192. static struct pool *currentpool = NULL;
  193. static int total_pools;
  194. static enum pool_strategy pool_strategy = POOL_FAILOVER;
  195. static int opt_rotate_period;
  196. static int total_urls, total_users, total_passes, total_userpasses;
  197. static bool curses_active = false;
  198. static char current_block[37];
  199. static char datestamp[40];
  200. static char blockdate[40];
  201. static char *opt_kernel = NULL;
  202. enum cl_kernel chosen_kernel;
  203. static bool ping = true;
  204. struct sigaction termhandler, inthandler;
  205. struct thread_q *getq;
  206. void get_datestamp(char *f, struct timeval *tv)
  207. {
  208. struct tm tm;
  209. localtime_r(&tv->tv_sec, &tm);
  210. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d]",
  211. tm.tm_year + 1900,
  212. tm.tm_mon + 1,
  213. tm.tm_mday,
  214. tm.tm_hour,
  215. tm.tm_min,
  216. tm.tm_sec);
  217. }
  218. static void applog_and_exit(const char *fmt, ...)
  219. {
  220. va_list ap;
  221. va_start(ap, fmt);
  222. vapplog(LOG_ERR, fmt, ap);
  223. va_end(ap);
  224. exit(1);
  225. }
  226. static void add_pool(void)
  227. {
  228. struct pool *pool;
  229. pool = calloc(sizeof(struct pool), 1);
  230. if (!pool) {
  231. applog(LOG_ERR, "Failed to malloc pool in add_pool");
  232. exit (1);
  233. }
  234. pool->pool_no = pool->prio = total_pools;
  235. pools[total_pools++] = pool;
  236. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL))) {
  237. applog(LOG_ERR, "Failed to pthread_mutex_init in add_pool");
  238. exit (1);
  239. }
  240. /* Make sure the pool doesn't think we've been idle since time 0 */
  241. pool->tv_idle.tv_sec = ~0UL;
  242. }
  243. /* Pool variant of test and set */
  244. static bool pool_tset(struct pool *pool, bool *var)
  245. {
  246. bool ret;
  247. mutex_lock(&pool->pool_lock);
  248. ret = *var;
  249. *var = true;
  250. mutex_unlock(&pool->pool_lock);
  251. return ret;
  252. }
  253. static bool pool_tclear(struct pool *pool, bool *var)
  254. {
  255. bool ret;
  256. mutex_lock(&pool->pool_lock);
  257. ret = *var;
  258. *var = false;
  259. mutex_unlock(&pool->pool_lock);
  260. return ret;
  261. }
  262. static struct pool *current_pool(void)
  263. {
  264. struct pool *pool;
  265. mutex_lock(&control_lock);
  266. pool = currentpool;
  267. mutex_unlock(&control_lock);
  268. return pool;
  269. }
  270. /* FIXME: Use asprintf for better errors. */
  271. static char *set_algo(const char *arg, enum sha256_algos *algo)
  272. {
  273. enum sha256_algos i;
  274. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  275. if (algo_names[i] && !strcmp(arg, algo_names[i])) {
  276. *algo = i;
  277. return NULL;
  278. }
  279. }
  280. return "Unknown algorithm";
  281. }
  282. static void show_algo(char buf[OPT_SHOW_LEN], const enum sha256_algos *algo)
  283. {
  284. strncpy(buf, algo_names[*algo], OPT_SHOW_LEN);
  285. }
  286. static char *set_int_range(const char *arg, int *i, int min, int max)
  287. {
  288. char *err = opt_set_intval(arg, i);
  289. if (err)
  290. return err;
  291. if (*i < min || *i > max)
  292. return "Value out of range";
  293. return NULL;
  294. }
  295. static char *set_int_0_to_9999(const char *arg, int *i)
  296. {
  297. return set_int_range(arg, i, 0, 9999);
  298. }
  299. static char *forced_int_1010(const char *arg, int *i)
  300. {
  301. opt_dynamic = false;
  302. return set_int_range(arg, i, -10, 10);
  303. }
  304. static char *force_nthreads_int(const char *arg, int *i)
  305. {
  306. forced_n_threads = true;
  307. return set_int_range(arg, i, 0, 9999);
  308. }
  309. static char *set_int_0_to_10(const char *arg, int *i)
  310. {
  311. return set_int_range(arg, i, 0, 10);
  312. }
  313. static char *set_devices(const char *arg, int *i)
  314. {
  315. char *err = opt_set_intval(arg, i);
  316. if (err)
  317. return err;
  318. if (*i < 0 || *i > 15)
  319. return "Invalid GPU device number";
  320. total_devices++;
  321. gpu_devices[*i] = true;
  322. return NULL;
  323. }
  324. static char *set_loadbalance(enum pool_strategy *strategy)
  325. {
  326. *strategy = POOL_LOADBALANCE;
  327. return NULL;
  328. }
  329. static char *set_rotate(const char *arg, int *i)
  330. {
  331. pool_strategy = POOL_ROTATE;
  332. return set_int_range(arg, i, 0, 9999);
  333. }
  334. static char *set_rr(enum pool_strategy *strategy)
  335. {
  336. *strategy = POOL_ROUNDROBIN;
  337. return NULL;
  338. }
  339. static char *set_url(char *arg, char **p)
  340. {
  341. struct pool *pool;
  342. total_urls++;
  343. if (total_urls > total_pools)
  344. add_pool();
  345. pool = pools[total_urls - 1];
  346. opt_set_charp(arg, &pool->rpc_url);
  347. if (strncmp(arg, "http://", 7) &&
  348. strncmp(arg, "https://", 8)) {
  349. char *httpinput;
  350. httpinput = malloc(255);
  351. if (!httpinput)
  352. quit(1, "Failed to malloc httpinput");
  353. strcpy(httpinput, "http://");
  354. strncat(httpinput, arg, 248);
  355. pool->rpc_url = httpinput;
  356. }
  357. return NULL;
  358. }
  359. static char *set_user(const char *arg, char **p)
  360. {
  361. struct pool *pool;
  362. if (total_userpasses)
  363. return "Use only user + pass or userpass, but not both";
  364. total_users++;
  365. if (total_users > total_pools)
  366. add_pool();
  367. pool = pools[total_users - 1];
  368. opt_set_charp(arg, &pool->rpc_user);
  369. return NULL;
  370. }
  371. static char *set_pass(const char *arg, char **p)
  372. {
  373. struct pool *pool;
  374. if (total_userpasses)
  375. return "Use only user + pass or userpass, but not both";
  376. total_passes++;
  377. if (total_passes > total_pools)
  378. add_pool();
  379. pool = pools[total_passes - 1];
  380. opt_set_charp(arg, &pool->rpc_pass);
  381. return NULL;
  382. }
  383. static char *set_userpass(const char *arg, char **p)
  384. {
  385. struct pool *pool;
  386. if (total_users || total_passes)
  387. return "Use only user + pass or userpass, but not both";
  388. total_userpasses++;
  389. if (total_userpasses > total_pools)
  390. add_pool();
  391. pool = pools[total_userpasses - 1];
  392. opt_set_charp(arg, &pool->rpc_userpass);
  393. return NULL;
  394. }
  395. static char *set_vector(const char *arg, int *i)
  396. {
  397. char *err = opt_set_intval(arg, i);
  398. if (err)
  399. return err;
  400. if (*i != 1 && *i != 2 && *i != 4)
  401. return "Valid vectors are 1, 2 or 4";
  402. return NULL;
  403. }
  404. static char *enable_debug(bool *flag)
  405. {
  406. *flag = true;
  407. /* Turn out verbose output, too. */
  408. opt_log_output = true;
  409. return NULL;
  410. }
  411. static char *trpc_url;
  412. static char *trpc_userpass;
  413. static char *trpc_user, *trpc_pass;
  414. /* These options are available from config file or commandline */
  415. static struct opt_table opt_config_table[] = {
  416. OPT_WITH_ARG("--algo|-a",
  417. set_algo, show_algo, &opt_algo,
  418. "Specify sha256 implementation for CPU mining:\n"
  419. "\tc\t\tLinux kernel sha256, implemented in C"
  420. #ifdef WANT_SSE2_4WAY
  421. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  422. #endif
  423. #ifdef WANT_VIA_PADLOCK
  424. "\n\tvia\t\tVIA padlock implementation"
  425. #endif
  426. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  427. #ifdef WANT_CRYPTOPP_ASM32
  428. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  429. #endif
  430. #ifdef WANT_X8664_SSE2
  431. "\n\tsse2_64\t\tSSE2 implementation for x86_64 machines"
  432. #endif
  433. #ifdef WANT_X8664_SSE4
  434. "\n\tsse4_64\t\tSSE4 implementation for x86_64 machines"
  435. #endif
  436. ),
  437. OPT_WITH_ARG("--cpu-threads|-t",
  438. force_nthreads_int, opt_show_intval, &opt_n_threads,
  439. "Number of miner CPU threads"),
  440. OPT_WITHOUT_ARG("--debug|-D",
  441. enable_debug, &opt_debug,
  442. "Enable debug output"),
  443. #ifdef HAVE_OPENCL
  444. OPT_WITH_ARG("--device|-d",
  445. set_devices, NULL, &opt_device,
  446. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  447. OPT_WITH_ARG("--gpu-threads|-g",
  448. set_int_0_to_10, opt_show_intval, &opt_g_threads,
  449. "Number of threads per GPU (0 - 10)"),
  450. OPT_WITH_ARG("--intensity|-I",
  451. forced_int_1010, opt_show_intval, &scan_intensity,
  452. "Intensity of GPU scanning (-10 -> 10, default: dynamic to maintain desktop interactivity)"),
  453. OPT_WITH_ARG("--kernel|-k",
  454. opt_set_charp, NULL, &opt_kernel,
  455. "Select kernel to use (poclbm or phatk - default: auto)"),
  456. #endif
  457. OPT_WITHOUT_ARG("--load-balance",
  458. set_loadbalance, &pool_strategy,
  459. "Change multipool strategy from failover to even load balance"),
  460. OPT_WITH_ARG("--log|-l",
  461. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  462. "Interval in seconds between log output"),
  463. OPT_WITHOUT_ARG("--no-longpoll",
  464. opt_set_invbool, &want_longpoll,
  465. "Disable X-Long-Polling support"),
  466. OPT_WITH_ARG("--pass|-p",
  467. set_pass, NULL, &trpc_pass,
  468. "Password for bitcoin JSON-RPC server"),
  469. OPT_WITHOUT_ARG("--protocol-dump|-P",
  470. opt_set_bool, &opt_protocol,
  471. "Verbose dump of protocol-level activities"),
  472. OPT_WITH_ARG("--queue|-Q",
  473. set_int_0_to_10, opt_show_intval, &opt_queue,
  474. "Number of extra work items to queue (0 - 10)"),
  475. OPT_WITHOUT_ARG("--quiet|-q",
  476. opt_set_bool, &opt_quiet,
  477. "Disable logging output, display status and errors"),
  478. OPT_WITHOUT_ARG("--real-quiet",
  479. opt_set_bool, &opt_realquiet,
  480. "Disable all output"),
  481. OPT_WITH_ARG("--retries|-r",
  482. opt_set_intval, opt_show_intval, &opt_retries,
  483. "Number of times to retry before giving up, if JSON-RPC call fails (-1 means never)"),
  484. OPT_WITH_ARG("--retry-pause|-R",
  485. set_int_0_to_9999, opt_show_intval, &opt_fail_pause,
  486. "Number of seconds to pause, between retries"),
  487. OPT_WITH_ARG("--rotate",
  488. set_rotate, opt_show_intval, &opt_rotate_period,
  489. "Change multipool strategy from failover to regularly rotate at N minutes"),
  490. OPT_WITHOUT_ARG("--round-robin",
  491. set_rr, &pool_strategy,
  492. "Change multipool strategy from failover to round robin on failure"),
  493. OPT_WITH_ARG("--scan-time|-s",
  494. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  495. "Upper bound on time spent scanning current work, in seconds"),
  496. #ifdef HAVE_SYSLOG_H
  497. OPT_WITHOUT_ARG("--syslog",
  498. opt_set_bool, &use_syslog,
  499. "Use system log for output messages (default: standard error)"),
  500. #endif
  501. OPT_WITHOUT_ARG("--text-only|-T",
  502. opt_set_invbool, &use_curses,
  503. "Disable ncurses formatted screen output"),
  504. OPT_WITH_ARG("--url|-o",
  505. set_url, opt_show_charp, &trpc_url,
  506. "URL for bitcoin JSON-RPC server"),
  507. OPT_WITH_ARG("--user|-u",
  508. set_user, NULL, &trpc_user,
  509. "Username for bitcoin JSON-RPC server"),
  510. #ifdef HAVE_OPENCL
  511. OPT_WITH_ARG("--vectors|-v",
  512. set_vector, NULL, &opt_vectors,
  513. "Override detected optimal vector width (1, 2 or 4)"),
  514. #endif
  515. OPT_WITHOUT_ARG("--verbose",
  516. opt_set_bool, &opt_log_output,
  517. "Log verbose output to stderr as well as status output"),
  518. #ifdef HAVE_OPENCL
  519. OPT_WITH_ARG("--worksize|-w",
  520. set_int_0_to_9999, opt_show_intval, &opt_worksize,
  521. "Override detected optimal worksize"),
  522. #endif
  523. OPT_WITH_ARG("--userpass|-O",
  524. set_userpass, NULL, &trpc_userpass,
  525. "Username:Password pair for bitcoin JSON-RPC server"),
  526. OPT_ENDTABLE
  527. };
  528. static char *parse_config(json_t *config)
  529. {
  530. static char err_buf[200];
  531. json_t *val;
  532. struct opt_table *opt;
  533. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  534. char *p, *name;
  535. /* We don't handle subtables. */
  536. assert(!(opt->type & OPT_SUBTABLE));
  537. /* Pull apart the option name(s). */
  538. name = strdup(opt->names);
  539. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  540. char *err;
  541. /* Ignore short options. */
  542. if (p[1] != '-')
  543. continue;
  544. val = json_object_get(config, p+2);
  545. if (!val)
  546. continue;
  547. if ((opt->type & OPT_HASARG) && json_is_string(val)) {
  548. err = opt->cb_arg(json_string_value(val),
  549. opt->u.arg);
  550. } else if ((opt->type&OPT_NOARG) && json_is_true(val)) {
  551. err = opt->cb(opt->u.arg);
  552. } else {
  553. err = "Invalid value";
  554. }
  555. if (err) {
  556. sprintf(err_buf, "Parsing JSON option %s: %s",
  557. p, err);
  558. return err_buf;
  559. }
  560. }
  561. free(name);
  562. }
  563. return NULL;
  564. }
  565. static char *load_config(const char *arg, void *unused)
  566. {
  567. json_error_t err;
  568. json_t *config;
  569. config = json_load_file(arg, 0, &err);
  570. if (!json_is_object(config))
  571. return "JSON decode of file failed";
  572. /* Parse the config now, so we can override it. That can keep pointers
  573. * so don't free config object. */
  574. return parse_config(config);
  575. }
  576. #ifdef HAVE_OPENCL
  577. static char *print_ndevs_and_exit(int *ndevs)
  578. {
  579. printf("%i GPU devices detected\n", *ndevs);
  580. exit(*ndevs);
  581. }
  582. #endif
  583. /* These options are available from commandline only */
  584. static struct opt_table opt_cmdline_table[] = {
  585. OPT_WITH_ARG("--config|-c",
  586. load_config, NULL, NULL,
  587. "Load a JSON-format configuration file\n"
  588. "See example-cfg.json for an example configuration."),
  589. OPT_WITHOUT_ARG("--help|-h",
  590. opt_usage_and_exit,
  591. #ifdef HAVE_OPENCL
  592. "\nBuilt with CPU and GPU mining support.\n",
  593. #else
  594. "\nBuilt with CPU mining support only.\n",
  595. #endif
  596. "Print this message"),
  597. #ifdef HAVE_OPENCL
  598. OPT_WITHOUT_ARG("--ndevs|-n",
  599. print_ndevs_and_exit, &nDevs,
  600. "Enumerate number of detected GPUs and exit"),
  601. #endif
  602. OPT_ENDTABLE
  603. };
  604. static bool jobj_binary(const json_t *obj, const char *key,
  605. void *buf, size_t buflen)
  606. {
  607. const char *hexstr;
  608. json_t *tmp;
  609. tmp = json_object_get(obj, key);
  610. if (unlikely(!tmp)) {
  611. applog(LOG_ERR, "JSON key '%s' not found", key);
  612. return false;
  613. }
  614. hexstr = json_string_value(tmp);
  615. if (unlikely(!hexstr)) {
  616. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  617. return false;
  618. }
  619. if (!hex2bin(buf, hexstr, buflen))
  620. return false;
  621. return true;
  622. }
  623. static bool work_decode(const json_t *val, struct work *work)
  624. {
  625. if (unlikely(!jobj_binary(val, "midstate",
  626. work->midstate, sizeof(work->midstate)))) {
  627. applog(LOG_ERR, "JSON inval midstate");
  628. goto err_out;
  629. }
  630. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
  631. applog(LOG_ERR, "JSON inval data");
  632. goto err_out;
  633. }
  634. if (unlikely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1)))) {
  635. applog(LOG_ERR, "JSON inval hash1");
  636. goto err_out;
  637. }
  638. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
  639. applog(LOG_ERR, "JSON inval target");
  640. goto err_out;
  641. }
  642. memset(work->hash, 0, sizeof(work->hash));
  643. return true;
  644. err_out:
  645. return false;
  646. }
  647. static inline int dev_from_id(int thr_id)
  648. {
  649. return thr_info[thr_id].cgpu->cpu_gpu;
  650. }
  651. /* Simulate a rolling average by faking an exponential decay over 5 * log */
  652. static inline void decay_time(double *f, double fadd)
  653. {
  654. *f = (fadd + *f * 0.9) / 1.9;
  655. }
  656. static WINDOW *mainwin, *statuswin, *logwin;
  657. static double total_secs = 0.1;
  658. static char statusline[256];
  659. static int cpucursor, gpucursor, logstart, logcursor;
  660. static struct cgpu_info *gpus, *cpus;
  661. static void text_print_status(int thr_id)
  662. {
  663. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  664. printf(" %sPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]\n",
  665. cgpu->is_gpu ? "G" : "C", cgpu->cpu_gpu, cgpu->rolling,
  666. cgpu->total_mhashes / total_secs, cgpu->getworks,
  667. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  668. cgpu->efficiency, cgpu->utility);
  669. }
  670. /* Must be called with curses mutex lock held and curses_active */
  671. static void curses_print_status(int thr_id)
  672. {
  673. struct pool *pool = current_pool();
  674. wmove(statuswin, 0, 0);
  675. wattron(statuswin, A_BOLD);
  676. wprintw(statuswin, " " PROGRAM_NAME " version " VERSION " - Started: %s", datestamp);
  677. wattroff(statuswin, A_BOLD);
  678. wmove(statuswin, 1, 0);
  679. whline(statuswin, '-', 80);
  680. wmove(statuswin, 2,0);
  681. wprintw(statuswin, " %s", statusline);
  682. wclrtoeol(statuswin);
  683. wmove(statuswin, 3,0);
  684. wprintw(statuswin, " TQ: %d ST: %d LS: %d SS: %d DW: %d NB: %d LW: %d LO: %d RF: %d I: %d",
  685. total_queued, total_staged, lp_staged, total_stale, total_discarded, new_blocks,
  686. local_work, total_lo, total_ro, scan_intensity);
  687. wclrtoeol(statuswin);
  688. wmove(statuswin, 4, 0);
  689. if (pool_strategy == POOL_LOADBALANCE && total_pools > 1)
  690. wprintw(statuswin, " Connected to multiple pools");
  691. else
  692. wprintw(statuswin, " Connected to %s as user %s", pool->rpc_url, pool->rpc_user);
  693. wclrtoeol(statuswin);
  694. wmove(statuswin, 5, 0);
  695. wprintw(statuswin, " Block %s started: %s", current_block + 4, blockdate);
  696. wmove(statuswin, 6, 0);
  697. whline(statuswin, '-', 80);
  698. wmove(statuswin, logstart - 1, 0);
  699. whline(statuswin, '-', 80);
  700. mvwprintw(statuswin, gpucursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
  701. opt_g_threads ? "[G]PU management " : "");
  702. if (thr_id >= 0 && thr_id < gpu_threads) {
  703. int gpu = dev_from_id(thr_id);
  704. struct cgpu_info *cgpu = &gpus[gpu];
  705. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  706. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  707. wmove(statuswin, gpucursor + gpu, 0);
  708. if (!cgpu->alive)
  709. wprintw(statuswin, " GPU %d: [DEAD / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  710. gpu, cgpu->total_mhashes / total_secs,
  711. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  712. cgpu->efficiency, cgpu->utility);
  713. else if (!gpu_devices[gpu])
  714. wprintw(statuswin, " GPU %d: [DISABLED / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  715. gpu, cgpu->total_mhashes / total_secs,
  716. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  717. cgpu->efficiency, cgpu->utility);
  718. else
  719. wprintw(statuswin, " GPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  720. gpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  721. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  722. cgpu->efficiency, cgpu->utility);
  723. wclrtoeol(statuswin);
  724. } else if (thr_id >= gpu_threads) {
  725. int cpu = dev_from_id(thr_id);
  726. struct cgpu_info *cgpu = &cpus[cpu];
  727. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  728. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  729. wmove(statuswin, cpucursor + cpu, 0);
  730. wprintw(statuswin, " CPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  731. cpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  732. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  733. cgpu->efficiency, cgpu->utility);
  734. wclrtoeol(statuswin);
  735. }
  736. wrefresh(statuswin);
  737. }
  738. static void print_status(int thr_id)
  739. {
  740. if (!curses_active)
  741. text_print_status(thr_id);
  742. else {
  743. mutex_lock(&curses_lock);
  744. curses_print_status(thr_id);
  745. mutex_unlock(&curses_lock);
  746. }
  747. }
  748. /* Check for window resize. Called with curses mutex locked */
  749. static inline void check_logwinsize(void)
  750. {
  751. int x, y, logx, logy;
  752. getmaxyx(mainwin, y, x);
  753. getmaxyx(logwin, logy, logx);
  754. y -= logcursor;
  755. /* Detect screen size change */
  756. if ((x != logx || y != logy) && x >= 80 && y >= 25)
  757. wresize(logwin, y, x);
  758. }
  759. /* For mandatory printing when mutex is already locked */
  760. static void wlog(const char *f, ...)
  761. {
  762. va_list ap;
  763. va_start(ap, f);
  764. vw_printw(logwin, f, ap);
  765. va_end(ap);
  766. }
  767. /* Mandatory printing */
  768. static void wlogprint(const char *f, ...)
  769. {
  770. va_list ap;
  771. mutex_lock(&curses_lock);
  772. va_start(ap, f);
  773. vw_printw(logwin, f, ap);
  774. va_end(ap);
  775. wrefresh(logwin);
  776. mutex_unlock(&curses_lock);
  777. }
  778. void log_curses(int prio, const char *f, va_list ap)
  779. {
  780. if (opt_quiet && prio != LOG_ERR)
  781. return;
  782. if (curses_active) {
  783. if (!opt_loginput) {
  784. mutex_lock(&curses_lock);
  785. vw_printw(logwin, f, ap);
  786. wrefresh(logwin);
  787. mutex_unlock(&curses_lock);
  788. }
  789. } else
  790. vprintf(f, ap);
  791. }
  792. static void clear_logwin(void)
  793. {
  794. mutex_lock(&curses_lock);
  795. wclear(logwin);
  796. wrefresh(logwin);
  797. mutex_unlock(&curses_lock);
  798. }
  799. static bool submit_upstream_work(const struct work *work)
  800. {
  801. char *hexstr = NULL;
  802. json_t *val, *res;
  803. char s[345];
  804. bool rc = false;
  805. int thr_id = work->thr_id;
  806. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  807. CURL *curl = curl_easy_init();
  808. struct pool *pool = work->pool;
  809. if (unlikely(!curl)) {
  810. applog(LOG_ERR, "CURL initialisation failed");
  811. return rc;
  812. }
  813. /* build hex string */
  814. hexstr = bin2hex(work->data, sizeof(work->data));
  815. if (unlikely(!hexstr)) {
  816. applog(LOG_ERR, "submit_upstream_work OOM");
  817. goto out_nofree;
  818. }
  819. /* build JSON-RPC request */
  820. sprintf(s,
  821. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  822. hexstr);
  823. if (opt_debug)
  824. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, s);
  825. /* issue JSON-RPC request */
  826. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, pool);
  827. if (unlikely(!val)) {
  828. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  829. if (!pool_tset(pool, &pool->submit_fail)) {
  830. total_ro++;
  831. pool->remotefail_occasions++;
  832. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  833. }
  834. goto out;
  835. } else if (pool_tclear(pool, &pool->submit_fail))
  836. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  837. res = json_object_get(val, "result");
  838. /* Theoretically threads could race when modifying accepted and
  839. * rejected values but the chance of two submits completing at the
  840. * same time is zero so there is no point adding extra locking */
  841. if (json_is_true(res)) {
  842. cgpu->accepted++;
  843. total_accepted++;
  844. pool->accepted++;
  845. if (opt_debug)
  846. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  847. if (!QUIET) {
  848. if (total_pools > 1)
  849. applog(LOG_WARNING, "Accepted %.8s %sPU %d thread %d pool %d",
  850. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  851. else
  852. applog(LOG_WARNING, "Accepted %.8s %sPU %d thread %d",
  853. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  854. }
  855. } else {
  856. cgpu->rejected++;
  857. total_rejected++;
  858. pool->rejected++;
  859. if (opt_debug)
  860. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  861. if (!QUIET) {
  862. if (total_pools > 1)
  863. applog(LOG_WARNING, "Rejected %.8s %sPU %d thread %d pool %d",
  864. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  865. else
  866. applog(LOG_WARNING, "Rejected %.8s %sPU %d thread %d",
  867. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  868. }
  869. }
  870. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  871. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  872. if (!opt_realquiet)
  873. print_status(thr_id);
  874. applog(LOG_INFO, "%sPU %d Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  875. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->getworks, cgpu->accepted,
  876. cgpu->rejected, cgpu->hw_errors, cgpu->efficiency, cgpu->utility);
  877. json_decref(val);
  878. rc = true;
  879. out:
  880. free(hexstr);
  881. out_nofree:
  882. curl_easy_cleanup(curl);
  883. return rc;
  884. }
  885. static const char *rpc_req =
  886. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  887. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  888. static inline struct pool *select_pool(bool lagging)
  889. {
  890. static int rotating_pool = 0;
  891. struct pool *pool, *cp;
  892. cp = current_pool();
  893. if (pool_strategy != POOL_LOADBALANCE && !lagging)
  894. pool = cp;
  895. else
  896. pool = NULL;
  897. while (!pool) {
  898. if (++rotating_pool >= total_pools)
  899. rotating_pool = 0;
  900. pool = pools[rotating_pool];
  901. if ((!pool->idle && pool->enabled) || pool == cp)
  902. break;
  903. pool = NULL;
  904. }
  905. return pool;
  906. }
  907. static bool get_upstream_work(struct work *work, bool lagging)
  908. {
  909. struct pool *pool;
  910. json_t *val;
  911. bool rc = false;
  912. CURL *curl;
  913. curl = curl_easy_init();
  914. if (unlikely(!curl)) {
  915. applog(LOG_ERR, "CURL initialisation failed");
  916. return rc;
  917. }
  918. pool = select_pool(lagging);
  919. if (opt_debug)
  920. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  921. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  922. want_longpoll, false, pool);
  923. if (unlikely(!val)) {
  924. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  925. goto out;
  926. }
  927. rc = work_decode(json_object_get(val, "result"), work);
  928. work->pool = pool;
  929. total_getworks++;
  930. pool->getwork_requested++;
  931. json_decref(val);
  932. out:
  933. curl_easy_cleanup(curl);
  934. return rc;
  935. }
  936. static void workio_cmd_free(struct workio_cmd *wc)
  937. {
  938. if (!wc)
  939. return;
  940. switch (wc->cmd) {
  941. case WC_SUBMIT_WORK:
  942. free(wc->u.work);
  943. break;
  944. default: /* do nothing */
  945. break;
  946. }
  947. memset(wc, 0, sizeof(*wc)); /* poison */
  948. free(wc);
  949. }
  950. static void disable_curses(void)
  951. {
  952. if (test_and_clear(&curses_active)) {
  953. leaveok(logwin, false);
  954. leaveok(statuswin, false);
  955. leaveok(mainwin, false);
  956. nocbreak();
  957. echo();
  958. delwin(logwin);
  959. delwin(statuswin);
  960. delwin(mainwin);
  961. endwin();
  962. refresh();
  963. #ifdef WIN32
  964. // Move the cursor to after curses output.
  965. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  966. CONSOLE_SCREEN_BUFFER_INFO csbi;
  967. COORD coord;
  968. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  969. coord.X = 0;
  970. coord.Y = csbi.dwSize.Y - 1;
  971. SetConsoleCursorPosition(hout, coord);
  972. }
  973. #endif
  974. }
  975. }
  976. void kill_work(void)
  977. {
  978. struct workio_cmd *wc;
  979. struct thr_info *thr;
  980. unsigned int i;
  981. disable_curses();
  982. applog(LOG_INFO, "Received kill message");
  983. /* Kill the watchdog thread */
  984. thr = &thr_info[watchdog_thr_id];
  985. pthread_cancel(*thr->pth);
  986. /* Stop the mining threads*/
  987. for (i = 0; i < mining_threads; i++) {
  988. thr = &thr_info[i];
  989. if (!thr->pth)
  990. continue;
  991. tq_freeze(thr->q);
  992. /* No need to check if this succeeds or not */
  993. pthread_cancel(*thr->pth);
  994. }
  995. /* Stop the others */
  996. thr = &thr_info[stage_thr_id];
  997. pthread_cancel(*thr->pth);
  998. thr = &thr_info[longpoll_thr_id];
  999. pthread_cancel(*thr->pth);
  1000. wc = calloc(1, sizeof(*wc));
  1001. if (unlikely(!wc)) {
  1002. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  1003. /* We're just trying to die anyway, so forget graceful */
  1004. exit (1);
  1005. }
  1006. wc->cmd = WC_DIE;
  1007. wc->thr = 0;
  1008. if (opt_debug)
  1009. applog(LOG_DEBUG, "Pushing die request to work thread");
  1010. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1011. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  1012. exit (1);
  1013. }
  1014. }
  1015. static void sighandler(int sig)
  1016. {
  1017. /* Restore signal handlers so we can still quit if kill_work fails */
  1018. sigaction(SIGTERM, &termhandler, NULL);
  1019. sigaction(SIGINT, &inthandler, NULL);
  1020. kill_work();
  1021. }
  1022. static void *get_work_thread(void *userdata)
  1023. {
  1024. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1025. struct work *ret_work;
  1026. int failures = 0;
  1027. pthread_detach(pthread_self());
  1028. ret_work = calloc(1, sizeof(*ret_work));
  1029. if (unlikely(!ret_work)) {
  1030. applog(LOG_ERR, "Failed to calloc ret_work in workio_get_work");
  1031. kill_work();
  1032. goto out;
  1033. }
  1034. /* obtain new work from bitcoin via JSON-RPC */
  1035. while (!get_upstream_work(ret_work, wc->lagging)) {
  1036. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1037. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  1038. free(ret_work);
  1039. kill_work();
  1040. goto out;
  1041. }
  1042. /* pause, then restart work-request loop */
  1043. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  1044. opt_fail_pause);
  1045. sleep(opt_fail_pause);
  1046. }
  1047. if (opt_debug)
  1048. applog(LOG_DEBUG, "Pushing work to requesting thread");
  1049. /* send work to requesting thread */
  1050. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  1051. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  1052. kill_work();
  1053. free(ret_work);
  1054. }
  1055. out:
  1056. workio_cmd_free(wc);
  1057. return NULL;
  1058. }
  1059. static bool workio_get_work(struct workio_cmd *wc)
  1060. {
  1061. pthread_t get_thread;
  1062. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  1063. applog(LOG_ERR, "Failed to create get_work_thread");
  1064. return false;
  1065. }
  1066. return true;
  1067. }
  1068. static bool stale_work(struct work *work)
  1069. {
  1070. struct timeval now;
  1071. bool ret = false;
  1072. char *hexstr;
  1073. gettimeofday(&now, NULL);
  1074. if ((now.tv_sec - work->tv_staged.tv_sec) > opt_scantime)
  1075. return true;
  1076. /* Only use the primary pool for determination as the work may
  1077. * interleave at times of new blocks */
  1078. if (work->pool != current_pool())
  1079. return ret;
  1080. hexstr = bin2hex(work->data, 36);
  1081. if (unlikely(!hexstr)) {
  1082. applog(LOG_ERR, "submit_work_thread OOM");
  1083. return ret;
  1084. }
  1085. if (strncmp(hexstr, current_block, 36))
  1086. ret = true;
  1087. free(hexstr);
  1088. return ret;
  1089. }
  1090. static void *submit_work_thread(void *userdata)
  1091. {
  1092. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1093. struct work *work = wc->u.work;
  1094. struct pool *pool = work->pool;
  1095. int failures = 0;
  1096. pthread_detach(pthread_self());
  1097. if (stale_work(work)) {
  1098. applog(LOG_WARNING, "Stale share detected, discarding");
  1099. total_stale++;
  1100. pool->stale_shares++;
  1101. goto out;
  1102. }
  1103. /* submit solution to bitcoin via JSON-RPC */
  1104. while (!submit_upstream_work(work)) {
  1105. if (stale_work(work)) {
  1106. applog(LOG_WARNING, "Stale share detected, discarding");
  1107. total_stale++;
  1108. pool->stale_shares++;
  1109. break;
  1110. }
  1111. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1112. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  1113. kill_work();
  1114. break;
  1115. }
  1116. /* pause, then restart work-request loop */
  1117. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  1118. opt_fail_pause);
  1119. sleep(opt_fail_pause);
  1120. }
  1121. out:
  1122. workio_cmd_free(wc);
  1123. return NULL;
  1124. }
  1125. static bool workio_submit_work(struct workio_cmd *wc)
  1126. {
  1127. pthread_t submit_thread;
  1128. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  1129. applog(LOG_ERR, "Failed to create submit_work_thread");
  1130. return false;
  1131. }
  1132. return true;
  1133. }
  1134. static void inc_staged(struct pool *pool, int inc, bool lp)
  1135. {
  1136. mutex_lock(&stgd_lock);
  1137. if (lp) {
  1138. lp_staged += inc;
  1139. total_staged += inc;
  1140. } else if (lp_staged)
  1141. --lp_staged;
  1142. else
  1143. total_staged += inc;
  1144. mutex_unlock(&stgd_lock);
  1145. }
  1146. static void dec_staged(int inc)
  1147. {
  1148. mutex_lock(&stgd_lock);
  1149. total_staged -= inc;
  1150. mutex_unlock(&stgd_lock);
  1151. }
  1152. static int requests_staged(void)
  1153. {
  1154. int ret;
  1155. mutex_lock(&stgd_lock);
  1156. ret = total_staged;
  1157. mutex_unlock(&stgd_lock);
  1158. return ret;
  1159. }
  1160. static int real_staged(void)
  1161. {
  1162. int ret;
  1163. mutex_lock(&stgd_lock);
  1164. ret = total_staged - lp_staged;
  1165. mutex_unlock(&stgd_lock);
  1166. return ret;
  1167. }
  1168. /* Find the pool that currently has the highest priority */
  1169. static struct pool *priority_pool(int choice)
  1170. {
  1171. struct pool *ret = NULL;
  1172. int i;
  1173. for (i = 0; i < total_pools; i++) {
  1174. struct pool *pool = pools[i];
  1175. if (pool->prio == choice) {
  1176. ret = pool;
  1177. break;
  1178. }
  1179. }
  1180. if (unlikely(!ret)) {
  1181. applog(LOG_ERR, "WTF No pool %d found!", choice);
  1182. return pools[choice];
  1183. }
  1184. return ret;
  1185. }
  1186. static void restart_longpoll(void);
  1187. static void switch_pools(struct pool *selected)
  1188. {
  1189. struct pool *pool, *last_pool;
  1190. int i, pool_no;
  1191. mutex_lock(&control_lock);
  1192. last_pool = currentpool;
  1193. pool_no = currentpool->pool_no;
  1194. /* Switch selected to pool number 0 and move the rest down */
  1195. if (selected) {
  1196. if (selected->prio != 0) {
  1197. for (i = 0; i < total_pools; i++) {
  1198. pool = pools[i];
  1199. if (pool->prio < selected->prio)
  1200. pool->prio++;
  1201. }
  1202. selected->prio = 0;
  1203. }
  1204. }
  1205. switch (pool_strategy) {
  1206. /* Both of these set to the master pool */
  1207. case POOL_FAILOVER:
  1208. case POOL_LOADBALANCE:
  1209. for (i = 0; i < total_pools; i++) {
  1210. pool = priority_pool(i);
  1211. if (!pool->idle && pool->enabled) {
  1212. pool_no = pool->pool_no;
  1213. break;
  1214. }
  1215. }
  1216. break;
  1217. /* Both of these simply increment and cycle */
  1218. case POOL_ROUNDROBIN:
  1219. case POOL_ROTATE:
  1220. if (selected) {
  1221. pool_no = selected->pool_no;
  1222. break;
  1223. }
  1224. pool_no++;
  1225. if (pool_no >= total_pools)
  1226. pool_no = 0;
  1227. break;
  1228. default:
  1229. break;
  1230. }
  1231. currentpool = pools[pool_no];
  1232. pool = currentpool;
  1233. mutex_unlock(&control_lock);
  1234. if (pool != last_pool) {
  1235. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  1236. restart_longpoll();
  1237. }
  1238. /* Reset the queued amount to allow more to be queued for the new pool */
  1239. mutex_lock(&qd_lock);
  1240. total_queued = 0;
  1241. mutex_unlock(&qd_lock);
  1242. inc_staged(pool, 1, true);
  1243. }
  1244. static void set_curblock(char *hexstr)
  1245. {
  1246. struct timeval tv_now;
  1247. memcpy(current_block, hexstr, 36);
  1248. gettimeofday(&tv_now, NULL);
  1249. get_datestamp(blockdate, &tv_now);
  1250. }
  1251. static void test_work_current(struct work *work)
  1252. {
  1253. char *hexstr;
  1254. /* Only use the primary pool for determination */
  1255. if (work->pool != current_pool() || work->cloned || work->rolls || work->clone)
  1256. return;
  1257. hexstr = bin2hex(work->data, 36);
  1258. if (unlikely(!hexstr)) {
  1259. applog(LOG_ERR, "stage_thread OOM");
  1260. return;
  1261. }
  1262. /* current_block is blanked out on successful longpoll */
  1263. if (unlikely(strncmp(hexstr, current_block, 36))) {
  1264. if (block_changed != BLOCK_LP && block_changed != BLOCK_FIRST) {
  1265. block_changed = BLOCK_DETECT;
  1266. new_blocks++;
  1267. if (have_longpoll)
  1268. applog(LOG_WARNING, "New block detected on network before longpoll, waiting on fresh work");
  1269. else
  1270. applog(LOG_WARNING, "New block detected on network, waiting on fresh work");
  1271. /* As we can't flush the work from here, signal the
  1272. * wakeup thread to restart all the threads */
  1273. work_restart[watchdog_thr_id].restart = 1;
  1274. } else
  1275. block_changed = BLOCK_NONE;
  1276. set_curblock(hexstr);
  1277. }
  1278. free(hexstr);
  1279. }
  1280. static void *stage_thread(void *userdata)
  1281. {
  1282. struct thr_info *mythr = userdata;
  1283. bool ok = true;
  1284. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1285. while (ok) {
  1286. struct work *work = NULL;
  1287. if (opt_debug)
  1288. applog(LOG_DEBUG, "Popping work to stage thread");
  1289. work = tq_pop(mythr->q, NULL);
  1290. if (unlikely(!work)) {
  1291. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  1292. ok = false;
  1293. break;
  1294. }
  1295. test_work_current(work);
  1296. if (!work->cloned && !work->clone)
  1297. gettimeofday(&work->tv_staged, NULL);
  1298. if (opt_debug)
  1299. applog(LOG_DEBUG, "Pushing work to getwork queue");
  1300. if (unlikely(!tq_push(getq, work))) {
  1301. applog(LOG_ERR, "Failed to tq_push work in stage_thread");
  1302. ok = false;
  1303. break;
  1304. }
  1305. inc_staged(work->pool, 1, false);
  1306. }
  1307. tq_freeze(mythr->q);
  1308. return NULL;
  1309. }
  1310. static char *curses_input(const char *query);
  1311. static int curses_int(const char *query)
  1312. {
  1313. int ret;
  1314. char *cvar;
  1315. cvar = curses_input(query);
  1316. ret = atoi(cvar);
  1317. free(cvar);
  1318. return ret;
  1319. }
  1320. static bool input_pool(bool live);
  1321. static int active_pools(void)
  1322. {
  1323. int ret = 0;
  1324. int i;
  1325. for (i = 0; i < total_pools; i++) {
  1326. if ((pools[i])->enabled)
  1327. ret++;
  1328. }
  1329. return ret;
  1330. }
  1331. static void display_pool_summary(struct pool *pool)
  1332. {
  1333. double efficiency = 0.0;
  1334. mutex_lock(&curses_lock);
  1335. wlog("Pool: %s\n", pool->rpc_url);
  1336. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  1337. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  1338. wlog(" Accepted shares: %d\n", pool->accepted);
  1339. wlog(" Rejected shares: %d\n", pool->rejected);
  1340. if (pool->accepted || pool->rejected)
  1341. wlog(" Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  1342. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  1343. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  1344. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  1345. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  1346. wlog(" Unable to get work from server occasions: %d\n", pool->localgen_occasions);
  1347. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  1348. wrefresh(logwin);
  1349. mutex_unlock(&curses_lock);
  1350. }
  1351. /* We can't remove the memory used for this struct pool because there may
  1352. * still be work referencing it. We just remove it from the pools list */
  1353. static void remove_pool(struct pool *pool)
  1354. {
  1355. int i, last_pool = total_pools - 1;
  1356. struct pool *other;
  1357. /* Boost priority of any lower prio than this one */
  1358. for (i = 0; i < total_pools; i++) {
  1359. other = pools[i];
  1360. if (other->prio > pool->prio)
  1361. other->prio--;
  1362. }
  1363. if (pool->pool_no < last_pool) {
  1364. /* Swap the last pool for this one */
  1365. (pools[last_pool])->pool_no = pool->pool_no;
  1366. pools[pool->pool_no] = pools[last_pool];
  1367. }
  1368. /* Give it an invalid number */
  1369. pool->pool_no = total_pools;
  1370. total_pools--;
  1371. }
  1372. static void display_pools(void)
  1373. {
  1374. struct pool *pool;
  1375. int selected, i;
  1376. char input;
  1377. opt_loginput = true;
  1378. immedok(logwin, true);
  1379. updated:
  1380. clear_logwin();
  1381. for (i = 0; i < total_pools; i++) {
  1382. pool = pools[i];
  1383. if (pool == current_pool())
  1384. wattron(logwin, A_BOLD);
  1385. if (!pool->enabled)
  1386. wattron(logwin, A_DIM);
  1387. wlogprint("%d: %s %s Priority %d: %s User:%s\n",
  1388. pool->pool_no,
  1389. pool->enabled? "Enabled" : "Disabled",
  1390. pool->idle? "Dead" : "Alive",
  1391. pool->prio,
  1392. pool->rpc_url, pool->rpc_user);
  1393. wattroff(logwin, A_BOLD | A_DIM);
  1394. }
  1395. retry:
  1396. wlogprint("\nCurrent pool management strategy: %s\n",
  1397. strategies[pool_strategy]);
  1398. if (pool_strategy == POOL_ROTATE)
  1399. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  1400. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  1401. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  1402. wlogprint("Or press any other key to continue\n");
  1403. input = getch();
  1404. if (!strncasecmp(&input, "a", 1)) {
  1405. input_pool(true);
  1406. goto updated;
  1407. } else if (!strncasecmp(&input, "r", 1)) {
  1408. if (total_pools <= 1) {
  1409. wlogprint("Cannot remove last pool");
  1410. goto retry;
  1411. }
  1412. selected = curses_int("Select pool number");
  1413. if (selected < 0 || selected >= total_pools) {
  1414. wlogprint("Invalid selection\n");
  1415. goto retry;
  1416. }
  1417. pool = pools[selected];
  1418. if (pool == current_pool())
  1419. switch_pools(NULL);
  1420. if (pool == current_pool()) {
  1421. wlogprint("Unable to remove pool due to activity\n");
  1422. goto retry;
  1423. }
  1424. pool->enabled = false;
  1425. remove_pool(pool);
  1426. goto updated;
  1427. } else if (!strncasecmp(&input, "s", 1)) {
  1428. selected = curses_int("Select pool number");
  1429. if (selected < 0 || selected >= total_pools) {
  1430. wlogprint("Invalid selection\n");
  1431. goto retry;
  1432. }
  1433. pool = pools[selected];
  1434. pool->enabled = true;
  1435. switch_pools(pool);
  1436. goto updated;
  1437. } else if (!strncasecmp(&input, "d", 1)) {
  1438. if (active_pools() <= 1) {
  1439. wlogprint("Cannot disable last pool");
  1440. goto retry;
  1441. }
  1442. selected = curses_int("Select pool number");
  1443. if (selected < 0 || selected >= total_pools) {
  1444. wlogprint("Invalid selection\n");
  1445. goto retry;
  1446. }
  1447. pool = pools[selected];
  1448. pool->enabled = false;
  1449. if (pool == current_pool())
  1450. switch_pools(NULL);
  1451. goto updated;
  1452. } else if (!strncasecmp(&input, "e", 1)) {
  1453. selected = curses_int("Select pool number");
  1454. if (selected < 0 || selected >= total_pools) {
  1455. wlogprint("Invalid selection\n");
  1456. goto retry;
  1457. }
  1458. pool = pools[selected];
  1459. pool->enabled = true;
  1460. if (pool->prio < current_pool()->prio)
  1461. switch_pools(pool);
  1462. goto updated;
  1463. } else if (!strncasecmp(&input, "c", 1)) {
  1464. for (i = 0; i <= TOP_STRATEGY; i++)
  1465. wlogprint("%d: %s\n", i, strategies[i]);
  1466. selected = curses_int("Select strategy number type");
  1467. if (selected < 0 || selected > TOP_STRATEGY) {
  1468. wlogprint("Invalid selection\n");
  1469. goto retry;
  1470. }
  1471. if (selected == POOL_ROTATE) {
  1472. opt_rotate_period = curses_int("Select interval in minutes");
  1473. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  1474. opt_rotate_period = 0;
  1475. wlogprint("Invalid selection\n");
  1476. goto retry;
  1477. }
  1478. }
  1479. pool_strategy = selected;
  1480. switch_pools(NULL);
  1481. goto updated;
  1482. } else if (!strncasecmp(&input, "i", 1)) {
  1483. selected = curses_int("Select pool number");
  1484. if (selected < 0 || selected >= total_pools) {
  1485. wlogprint("Invalid selection\n");
  1486. goto retry;
  1487. }
  1488. pool = pools[selected];
  1489. display_pool_summary(pool);
  1490. goto retry;
  1491. }
  1492. clear_logwin();
  1493. immedok(logwin, false);
  1494. opt_loginput = false;
  1495. }
  1496. static void display_options(void)
  1497. {
  1498. int selected;
  1499. char input;
  1500. opt_loginput = true;
  1501. immedok(logwin, true);
  1502. retry:
  1503. clear_logwin();
  1504. wlogprint("\n[D]ebug:%s [Q]uiet:%s [V]erbose:%s [R]PC debug:%s [L]og interval:%d\n",
  1505. opt_debug ? "on" : "off",
  1506. opt_quiet ? "on" : "off",
  1507. opt_log_output ? "on" : "off",
  1508. opt_protocol ? "on" : "off",
  1509. opt_log_interval);
  1510. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  1511. wlogprint("Select an option or any other key to return\n");
  1512. input = getch();
  1513. if (!strncasecmp(&input, "q", 1)) {
  1514. opt_quiet ^= true;
  1515. clear_logwin();
  1516. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  1517. } else if (!strncasecmp(&input, "v", 1)) {
  1518. opt_log_output ^= true;
  1519. if (opt_log_output)
  1520. opt_quiet = false;
  1521. clear_logwin();
  1522. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  1523. } else if (!strncasecmp(&input, "n", 1)) {
  1524. opt_log_output = false;
  1525. opt_debug = false;
  1526. opt_quiet = false;
  1527. opt_protocol = false;
  1528. clear_logwin();
  1529. wlogprint("Output mode reset to normal\n");
  1530. } else if (!strncasecmp(&input, "d", 1)) {
  1531. opt_debug ^= true;
  1532. if (opt_debug) {
  1533. opt_log_output = true;
  1534. opt_quiet = false;
  1535. }
  1536. clear_logwin();
  1537. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  1538. } else if (!strncasecmp(&input, "r", 1)) {
  1539. opt_protocol ^= true;
  1540. if (opt_protocol)
  1541. opt_quiet = false;
  1542. clear_logwin();
  1543. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  1544. } else if (!strncasecmp(&input, "c", 1))
  1545. clear_logwin();
  1546. else if (!strncasecmp(&input, "l", 1)) {
  1547. selected = curses_int("Interval in seconds");
  1548. if (selected < 0 || selected > 9999) {
  1549. wlogprint("Invalid selection\n");
  1550. goto retry;
  1551. }
  1552. opt_log_interval = selected;
  1553. clear_logwin();
  1554. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  1555. } else if (!strncasecmp(&input, "s", 1)) {
  1556. opt_realquiet = true;
  1557. clear_logwin();
  1558. } else clear_logwin();
  1559. immedok(logwin, false);
  1560. opt_loginput = false;
  1561. }
  1562. static void set_options(void)
  1563. {
  1564. int selected;
  1565. char input;
  1566. opt_loginput = true;
  1567. immedok(logwin, true);
  1568. retry:
  1569. clear_logwin();
  1570. wlogprint("\n[D]ynamic mode: %s\n[L]ongpoll: %s\n",
  1571. opt_dynamic ? "On" : "Off", want_longpoll ? "On" : "Off");
  1572. if (opt_dynamic)
  1573. wlogprint("[I]ntensity: Dynamic\n");
  1574. else
  1575. wlogprint("[I]ntensity: %d\n", scan_intensity);
  1576. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[R]etries: %d\n[P]ause: %d\n",
  1577. opt_queue, opt_scantime, opt_retries, opt_fail_pause);
  1578. wlogprint("Select an option or any other key to return\n");
  1579. input = getch();
  1580. if (!strncasecmp(&input, "q", 1)) {
  1581. selected = curses_int("Extra work items to queue");
  1582. if (selected < 0 || selected > 9999) {
  1583. wlogprint("Invalid selection\n");
  1584. goto retry;
  1585. }
  1586. opt_queue = selected;
  1587. goto retry;
  1588. } else if (!strncasecmp(&input, "d", 1)) {
  1589. opt_dynamic ^= true;
  1590. goto retry;
  1591. } else if (!strncasecmp(&input, "l", 1)) {
  1592. want_longpoll ^= true;
  1593. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  1594. restart_longpoll();
  1595. goto retry;
  1596. } else if (!strncasecmp(&input, "i", 1)) {
  1597. selected = curses_int("Set GPU scan intensity (-10 -> 10)");
  1598. if (selected < -10 || selected > 10) {
  1599. wlogprint("Invalid selection\n");
  1600. goto retry;
  1601. }
  1602. opt_dynamic = false;
  1603. scan_intensity = selected;
  1604. goto retry;
  1605. } else if (!strncasecmp(&input, "s", 1)) {
  1606. selected = curses_int("Set scantime in seconds");
  1607. if (selected < 0 || selected > 9999) {
  1608. wlogprint("Invalid selection\n");
  1609. goto retry;
  1610. }
  1611. opt_scantime = selected;
  1612. goto retry;
  1613. } else if (!strncasecmp(&input, "r", 1)) {
  1614. selected = curses_int("Retries before failing (-1 infinite)");
  1615. if (selected < -1 || selected > 9999) {
  1616. wlogprint("Invalid selection\n");
  1617. goto retry;
  1618. }
  1619. opt_retries = selected;
  1620. goto retry;
  1621. } else if (!strncasecmp(&input, "p", 1)) {
  1622. selected = curses_int("Seconds to pause before network retries");
  1623. if (selected < 1 || selected > 9999) {
  1624. wlogprint("Invalid selection\n");
  1625. goto retry;
  1626. }
  1627. opt_fail_pause = selected;
  1628. goto retry;
  1629. }
  1630. clear_logwin();
  1631. immedok(logwin, false);
  1632. opt_loginput = false;
  1633. }
  1634. #ifdef HAVE_OPENCL
  1635. static void reinit_device(struct cgpu_info *cgpu);
  1636. static void manage_gpu(void)
  1637. {
  1638. struct thr_info *thr;
  1639. int selected, gpu, i;
  1640. char checkin[40];
  1641. char input;
  1642. if (!opt_g_threads)
  1643. return;
  1644. opt_loginput = true;
  1645. immedok(logwin, true);
  1646. clear_logwin();
  1647. retry:
  1648. for (gpu = 0; gpu < nDevs; gpu++) {
  1649. struct cgpu_info *cgpu = &gpus[gpu];
  1650. wlog("GPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]\n",
  1651. gpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  1652. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  1653. cgpu->efficiency, cgpu->utility);
  1654. for (i = 0; i < mining_threads; i++) {
  1655. thr = &thr_info[i];
  1656. if (thr->cgpu != cgpu)
  1657. continue;
  1658. get_datestamp(checkin, &thr->last);
  1659. wlog("Thread %d: %.1f Mh/s %s %s reported in %s\n", i,
  1660. thr->rolling, gpu_devices[gpu] ? "Enabled" : "Disabled",
  1661. cgpu->alive ? "Alive" : "Dead", checkin);
  1662. }
  1663. }
  1664. wlogprint("[E]nable [D]isable [R]estart GPU\n");
  1665. wlogprint("Or press any other key to continue\n");
  1666. input = getch();
  1667. if (!strncasecmp(&input, "e", 1)) {
  1668. selected = curses_int("Select GPU to enable");
  1669. if (selected < 0 || selected >= nDevs) {
  1670. wlogprint("Invalid selection\n");
  1671. goto retry;
  1672. }
  1673. if (!gpus[selected].alive) {
  1674. wlogprint("Device dead, need to attempt to restart before enabling\n");
  1675. goto retry;
  1676. }
  1677. if (gpu_devices[selected]) {
  1678. wlogprint("Device already enabled\n");
  1679. goto retry;
  1680. }
  1681. gpu_devices[selected] = true;
  1682. for (i = 0; i < gpu_threads; i++) {
  1683. if (dev_from_id(i) != selected)
  1684. continue;
  1685. thr = &thr_info[i];
  1686. if (opt_debug)
  1687. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  1688. tq_push(thr->q, &ping);
  1689. }
  1690. } if (!strncasecmp(&input, "d", 1)) {
  1691. selected = curses_int("Select GPU to disable");
  1692. if (selected < 0 || selected >= nDevs) {
  1693. wlogprint("Invalid selection\n");
  1694. goto retry;
  1695. }
  1696. if (!gpu_devices[selected]) {
  1697. wlogprint("Device already disabled\n");
  1698. goto retry;
  1699. }
  1700. gpu_devices[selected] = false;
  1701. } else if (!strncasecmp(&input, "r", 1)) {
  1702. selected = curses_int("Select GPU to attempt to restart");
  1703. if (selected < 0 || selected >= nDevs) {
  1704. wlogprint("Invalid selection\n");
  1705. goto retry;
  1706. }
  1707. wlogprint("Attempting to restart threads of GPU %d\n", selected);
  1708. reinit_device(&gpus[selected]);
  1709. }
  1710. clear_logwin();
  1711. immedok(logwin, false);
  1712. opt_loginput = false;
  1713. }
  1714. #else
  1715. static void manage_gpu(void)
  1716. {
  1717. }
  1718. #endif
  1719. static void *input_thread(void *userdata)
  1720. {
  1721. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1722. if (!curses_active)
  1723. return NULL;
  1724. while (1) {
  1725. char input;
  1726. input = getch();
  1727. if (!strncasecmp(&input, "q", 1)) {
  1728. kill_work();
  1729. return NULL;
  1730. } else if (!strncasecmp(&input, "d", 1))
  1731. display_options();
  1732. else if (!strncasecmp(&input, "p", 1))
  1733. display_pools();
  1734. else if (!strncasecmp(&input, "s", 1))
  1735. set_options();
  1736. else if (!strncasecmp(&input, "g", 1))
  1737. manage_gpu();
  1738. if (opt_realquiet) {
  1739. disable_curses();
  1740. break;
  1741. }
  1742. }
  1743. return NULL;
  1744. }
  1745. static void *workio_thread(void *userdata)
  1746. {
  1747. struct thr_info *mythr = userdata;
  1748. bool ok = true;
  1749. while (ok) {
  1750. struct workio_cmd *wc;
  1751. if (opt_debug)
  1752. applog(LOG_DEBUG, "Popping work to work thread");
  1753. /* wait for workio_cmd sent to us, on our queue */
  1754. wc = tq_pop(mythr->q, NULL);
  1755. if (unlikely(!wc)) {
  1756. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  1757. ok = false;
  1758. break;
  1759. }
  1760. /* process workio_cmd */
  1761. switch (wc->cmd) {
  1762. case WC_GET_WORK:
  1763. ok = workio_get_work(wc);
  1764. break;
  1765. case WC_SUBMIT_WORK:
  1766. ok = workio_submit_work(wc);
  1767. break;
  1768. case WC_DIE:
  1769. default:
  1770. ok = false;
  1771. break;
  1772. }
  1773. }
  1774. tq_freeze(mythr->q);
  1775. return NULL;
  1776. }
  1777. static void thread_reportin(struct thr_info *thr)
  1778. {
  1779. gettimeofday(&thr->last, NULL);
  1780. thr->cgpu->alive = true;
  1781. thr->getwork = false;
  1782. }
  1783. static inline void thread_reportout(struct thr_info *thr)
  1784. {
  1785. thr->getwork = true;
  1786. }
  1787. static void hashmeter(int thr_id, struct timeval *diff,
  1788. unsigned long hashes_done)
  1789. {
  1790. struct timeval temp_tv_end, total_diff;
  1791. double secs;
  1792. double local_secs;
  1793. double utility, efficiency = 0.0;
  1794. static double local_mhashes_done = 0;
  1795. static double rolling = 0;
  1796. double local_mhashes = (double)hashes_done / 1000000.0;
  1797. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1798. bool showlog = false;
  1799. /* Update the last time this thread reported in */
  1800. if (thr_id >= 0)
  1801. gettimeofday(&thr_info[thr_id].last, NULL);
  1802. /* Don't bother calculating anything if we're not displaying it */
  1803. if (opt_realquiet || !opt_log_interval)
  1804. return;
  1805. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  1806. /* So we can call hashmeter from a non worker thread */
  1807. if (thr_id >= 0) {
  1808. struct thr_info *thr = &thr_info[thr_id];
  1809. double thread_rolling = 0.0;
  1810. int i;
  1811. if (opt_debug)
  1812. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  1813. thr_id, hashes_done, hashes_done / secs);
  1814. /* Rolling average for each thread and each device */
  1815. decay_time(&thr->rolling, local_mhashes / secs);
  1816. for (i = 0; i < mining_threads; i++) {
  1817. struct thr_info *th = &thr_info[i];
  1818. if (th->cgpu == cgpu)
  1819. thread_rolling += th->rolling;
  1820. }
  1821. decay_time(&cgpu->rolling, thread_rolling);
  1822. cgpu->total_mhashes += local_mhashes;
  1823. }
  1824. /* Totals are updated by all threads so can race without locking */
  1825. mutex_lock(&hash_lock);
  1826. gettimeofday(&temp_tv_end, NULL);
  1827. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  1828. total_mhashes_done += local_mhashes;
  1829. local_mhashes_done += local_mhashes;
  1830. if (total_diff.tv_sec < opt_log_interval)
  1831. /* Only update the total every opt_log_interval seconds */
  1832. goto out_unlock;
  1833. showlog = true;
  1834. gettimeofday(&total_tv_end, NULL);
  1835. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  1836. decay_time(&rolling, local_mhashes_done / local_secs);
  1837. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  1838. total_secs = (double)total_diff.tv_sec +
  1839. ((double)total_diff.tv_usec / 1000000.0);
  1840. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  1841. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  1842. sprintf(statusline, "[(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  1843. opt_log_interval, rolling, total_mhashes_done / total_secs,
  1844. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  1845. local_mhashes_done = 0;
  1846. out_unlock:
  1847. mutex_unlock(&hash_lock);
  1848. if (showlog) {
  1849. if (!curses_active) {
  1850. printf("%s \r", statusline);
  1851. fflush(stdout);
  1852. } else
  1853. applog(LOG_INFO, "%s", statusline);
  1854. }
  1855. }
  1856. /* This is overkill, but at least we'll know accurately how much work is
  1857. * queued to prevent ever being left without work */
  1858. static void inc_queued(void)
  1859. {
  1860. mutex_lock(&qd_lock);
  1861. total_queued++;
  1862. mutex_unlock(&qd_lock);
  1863. }
  1864. static void dec_queued(void)
  1865. {
  1866. mutex_lock(&qd_lock);
  1867. if (total_queued > 0)
  1868. total_queued--;
  1869. mutex_unlock(&qd_lock);
  1870. dec_staged(1);
  1871. }
  1872. static int requests_queued(void)
  1873. {
  1874. int ret;
  1875. mutex_lock(&qd_lock);
  1876. ret = total_queued;
  1877. mutex_unlock(&qd_lock);
  1878. return ret;
  1879. }
  1880. static bool pool_active(struct pool *pool)
  1881. {
  1882. bool ret = false;
  1883. json_t *val;
  1884. CURL *curl;
  1885. curl = curl_easy_init();
  1886. if (unlikely(!curl)) {
  1887. applog(LOG_ERR, "CURL initialisation failed");
  1888. return false;
  1889. }
  1890. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  1891. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  1892. true, false, pool);
  1893. if (val) {
  1894. struct work *work = malloc(sizeof(struct work));
  1895. bool rc;
  1896. if (!work) {
  1897. applog(LOG_ERR, "Unable to malloc work in pool_active");
  1898. goto out;
  1899. }
  1900. rc = work_decode(json_object_get(val, "result"), work);
  1901. if (rc) {
  1902. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  1903. pool->pool_no, pool->rpc_url);
  1904. work->pool = pool;
  1905. if (opt_debug)
  1906. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  1907. tq_push(thr_info[stage_thr_id].q, work);
  1908. total_getworks++;
  1909. pool->getwork_requested++;
  1910. inc_queued();
  1911. ret = true;
  1912. gettimeofday(&pool->tv_idle, NULL);
  1913. } else {
  1914. applog(LOG_DEBUG, "Successfully retreived but FAILED to decipher work from pool %u %s",
  1915. pool->pool_no, pool->rpc_url);
  1916. free(work);
  1917. }
  1918. json_decref(val);
  1919. } else {
  1920. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  1921. pool->pool_no, pool->rpc_url);
  1922. applog(LOG_WARNING, "Pool down, URL or credentials invalid");
  1923. }
  1924. out:
  1925. curl_easy_cleanup(curl);
  1926. return ret;
  1927. }
  1928. static void pool_died(struct pool *pool)
  1929. {
  1930. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  1931. gettimeofday(&pool->tv_idle, NULL);
  1932. switch_pools(NULL);
  1933. }
  1934. static void pool_resus(struct pool *pool)
  1935. {
  1936. applog(LOG_WARNING, "Pool %d %s recovered", pool->pool_no, pool->rpc_url);
  1937. if (pool->prio < current_pool()->prio && pool_strategy == POOL_FAILOVER)
  1938. switch_pools(NULL);
  1939. }
  1940. static bool queue_request(void)
  1941. {
  1942. int maxq = opt_queue + mining_threads;
  1943. struct workio_cmd *wc;
  1944. int rq, rs;
  1945. rq = requests_queued();
  1946. rs = real_staged();
  1947. /* If we've been generating lots of local work we may already have
  1948. * enough in the queue */
  1949. if (rq >= maxq || rs >= maxq)
  1950. return true;
  1951. /* fill out work request message */
  1952. wc = calloc(1, sizeof(*wc));
  1953. if (unlikely(!wc)) {
  1954. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  1955. return false;
  1956. }
  1957. wc->cmd = WC_GET_WORK;
  1958. /* The get work does not belong to any thread */
  1959. wc->thr = NULL;
  1960. /* If we've queued more than 2/3 of the maximum and still have no
  1961. * staged work, consider the system lagging and allow work to be
  1962. * gathered from another pool if possible */
  1963. if (rq > (maxq * 2 / 3) && !rs)
  1964. wc->lagging = true;
  1965. if (opt_debug)
  1966. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  1967. /* send work request to workio thread */
  1968. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1969. applog(LOG_ERR, "Failed to tq_push in queue_request");
  1970. workio_cmd_free(wc);
  1971. return false;
  1972. }
  1973. inc_queued();
  1974. return true;
  1975. }
  1976. static void discard_work(struct work *work)
  1977. {
  1978. if (!work->clone) {
  1979. if (work->pool)
  1980. work->pool->discarded_work++;
  1981. total_discarded++;
  1982. if (opt_debug)
  1983. applog(LOG_DEBUG, "Discarded cloned work");
  1984. } else if (opt_debug)
  1985. applog(LOG_DEBUG, "Discarded work");
  1986. free(work);
  1987. }
  1988. static void discard_staged(void)
  1989. {
  1990. struct timespec abstime = {};
  1991. struct timeval now;
  1992. struct work *work_heap;
  1993. /* Just in case we fell in a hole and missed a queue filling */
  1994. if (unlikely(!requests_staged()))
  1995. return;
  1996. gettimeofday(&now, NULL);
  1997. abstime.tv_sec = now.tv_sec + 60;
  1998. if (opt_debug)
  1999. applog(LOG_DEBUG, "Popping work to discard staged");
  2000. work_heap = tq_pop(getq, &abstime);
  2001. if (unlikely(!work_heap))
  2002. return;
  2003. discard_work(work_heap);
  2004. dec_queued();
  2005. }
  2006. static void flush_requests(void)
  2007. {
  2008. struct pool *pool = current_pool();
  2009. int i, stale;
  2010. /* We should have one fresh work item staged from the block change. */
  2011. stale = requests_staged() - 1;
  2012. /* Temporarily increase the staged count so that get_work thinks there
  2013. * is work available instead of making threads reuse existing work */
  2014. inc_staged(pool, mining_threads, true);
  2015. for (i = 0; i < stale; i++) {
  2016. /* Queue a whole batch of new requests */
  2017. if (unlikely(!queue_request())) {
  2018. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  2019. kill_work();
  2020. break;
  2021. }
  2022. /* Pop off the old requests. Cancelling the requests would be better
  2023. * but is tricky */
  2024. discard_staged();
  2025. }
  2026. }
  2027. static inline bool can_roll(struct work *work)
  2028. {
  2029. return (work->pool && !stale_work(work) && work->pool->has_rolltime &&
  2030. work->rolls < 11 && !work->clone);
  2031. }
  2032. static void roll_work(struct work *work)
  2033. {
  2034. uint32_t *work_ntime;
  2035. uint32_t ntime;
  2036. work_ntime = (uint32_t *)(work->data + 68);
  2037. ntime = be32toh(*work_ntime);
  2038. ntime++;
  2039. *work_ntime = htobe32(ntime);
  2040. local_work++;
  2041. work->rolls++;
  2042. work->blk.nonce = 0;
  2043. gettimeofday(&work->tv_staged, NULL);
  2044. if (opt_debug)
  2045. applog(LOG_DEBUG, "Successfully rolled work");
  2046. }
  2047. /* Recycle the work at a higher starting res_nonce if we know the thread we're
  2048. * giving it to will not finish scanning it. We keep the master copy to be
  2049. * recycled more rapidly and discard the clone to avoid repeating work */
  2050. static bool divide_work(struct timeval *now, struct work *work, uint32_t hash_div)
  2051. {
  2052. uint64_t hash_inc;
  2053. if (hash_div < 3 || work->clone)
  2054. return false;
  2055. hash_inc = MAXTHREADS / hash_div * 2;
  2056. if ((uint64_t)work->blk.nonce + hash_inc < MAXTHREADS) {
  2057. /* Don't keep handing it out if it's getting old, but try to
  2058. * roll it instead */
  2059. if ((now->tv_sec - work->tv_staged.tv_sec) > opt_scantime) {
  2060. if (!can_roll(work))
  2061. return false;
  2062. else {
  2063. roll_work(work);
  2064. return true;
  2065. }
  2066. }
  2067. /* Okay we can divide it up */
  2068. work->blk.nonce += hash_inc;
  2069. work->cloned = true;
  2070. local_work++;
  2071. if (opt_debug)
  2072. applog(LOG_DEBUG, "Successfully divided work");
  2073. return true;
  2074. }
  2075. return false;
  2076. }
  2077. static bool get_work(struct work *work, bool requested, struct thr_info *thr,
  2078. const int thr_id, uint32_t hash_div)
  2079. {
  2080. struct timespec abstime = {};
  2081. struct timeval now;
  2082. struct work *work_heap;
  2083. struct pool *pool;
  2084. bool ret = false;
  2085. int failures = 0;
  2086. /* Tell the watchdog thread this thread is waiting on getwork and
  2087. * should not be restarted */
  2088. thread_reportout(thr);
  2089. retry:
  2090. pool = current_pool();
  2091. if (unlikely(!requested && !queue_request())) {
  2092. applog(LOG_WARNING, "Failed to queue_request in get_work");
  2093. goto out;
  2094. }
  2095. requested = false;
  2096. if (!requests_staged() && can_roll(work)) {
  2097. /* Only print this message once each time we shift to localgen */
  2098. if (!pool_tset(pool, &pool->idle)) {
  2099. applog(LOG_WARNING, "Pool %d not providing work fast enough, generating work locally",
  2100. pool->pool_no);
  2101. pool->localgen_occasions++;
  2102. total_lo++;
  2103. gettimeofday(&pool->tv_idle, NULL);
  2104. } else {
  2105. struct timeval tv_now, diff;
  2106. gettimeofday(&tv_now, NULL);
  2107. timeval_subtract(&diff, &tv_now, &pool->tv_idle);
  2108. /* Attempt to switch pools if this one has been unresponsive for >half
  2109. * a block's duration */
  2110. if (diff.tv_sec > 300) {
  2111. pool_died(pool);
  2112. goto retry;
  2113. }
  2114. }
  2115. roll_work(work);
  2116. ret = true;
  2117. goto out;
  2118. }
  2119. gettimeofday(&now, NULL);
  2120. abstime.tv_sec = now.tv_sec + 60;
  2121. if (opt_debug)
  2122. applog(LOG_DEBUG, "Popping work from get queue to get work");
  2123. /* wait for 1st response, or get cached response */
  2124. work_heap = tq_pop(getq, &abstime);
  2125. if (unlikely(!work_heap)) {
  2126. /* Attempt to switch pools if this one has mandatory work that
  2127. * has timed out or does not support rolltime */
  2128. pool->localgen_occasions++;
  2129. total_lo++;
  2130. pool_died(pool);
  2131. goto retry;
  2132. }
  2133. if (stale_work(work_heap)) {
  2134. dec_queued();
  2135. discard_work(work_heap);
  2136. goto retry;
  2137. }
  2138. pool = work_heap->pool;
  2139. /* If we make it here we have succeeded in getting fresh work */
  2140. if (pool_tclear(pool, &pool->idle))
  2141. pool_resus(pool);
  2142. memcpy(work, work_heap, sizeof(*work));
  2143. /* Copy the res nonce back so we know to start at a higher baseline
  2144. * should we divide the same work up again. Make the work we're
  2145. * handing out be clone */
  2146. if (divide_work(&now, work_heap, hash_div)) {
  2147. if (opt_debug)
  2148. applog(LOG_DEBUG, "Pushing divided work to get queue head");
  2149. tq_push_head(getq, work_heap);
  2150. work->clone = true;
  2151. } else {
  2152. dec_queued();
  2153. free(work_heap);
  2154. }
  2155. ret = true;
  2156. out:
  2157. if (unlikely(ret == false)) {
  2158. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  2159. applog(LOG_ERR, "Failed %d times to get_work");
  2160. return ret;
  2161. }
  2162. applog(LOG_DEBUG, "Retrying after %d seconds", opt_fail_pause);
  2163. sleep(opt_fail_pause);
  2164. goto retry;
  2165. }
  2166. work->thr_id = thr_id;
  2167. thread_reportin(thr);
  2168. return ret;
  2169. }
  2170. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  2171. {
  2172. struct workio_cmd *wc;
  2173. /* fill out work request message */
  2174. wc = calloc(1, sizeof(*wc));
  2175. if (unlikely(!wc)) {
  2176. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  2177. return false;
  2178. }
  2179. wc->u.work = malloc(sizeof(*work_in));
  2180. if (unlikely(!wc->u.work)) {
  2181. applog(LOG_ERR, "Failed to calloc work in submit_work_sync");
  2182. goto err_out;
  2183. }
  2184. wc->cmd = WC_SUBMIT_WORK;
  2185. wc->thr = thr;
  2186. memcpy(wc->u.work, work_in, sizeof(*work_in));
  2187. if (opt_debug)
  2188. applog(LOG_DEBUG, "Pushing submit work to work thread");
  2189. /* send solution to workio thread */
  2190. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2191. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  2192. goto err_out;
  2193. }
  2194. return true;
  2195. err_out:
  2196. workio_cmd_free(wc);
  2197. return false;
  2198. }
  2199. struct swa {
  2200. struct thr_info *thr;
  2201. const struct work *work_in;
  2202. };
  2203. static void *swasync_thread(void *userdata)
  2204. {
  2205. struct swa *swa = (struct swa *)userdata;
  2206. /* Return value ignored */
  2207. submit_work_sync(swa->thr, swa->work_in);
  2208. free(swa);
  2209. return NULL;
  2210. }
  2211. static bool submit_work_async(struct thr_info *thr, const struct work *work_in)
  2212. {
  2213. pthread_t sw_thread;
  2214. struct swa *swa;
  2215. swa = malloc(sizeof(struct swa));
  2216. if (unlikely(!swa)) {
  2217. applog(LOG_ERR, "Failed to malloc swa in submit_work_async");
  2218. return false;
  2219. }
  2220. swa->thr = thr;
  2221. swa->work_in = work_in;
  2222. if (unlikely(pthread_create(&sw_thread, NULL, swasync_thread, (void *)swa))) {
  2223. applog(LOG_ERR, "Failed to create swasync_thread");
  2224. return false;
  2225. }
  2226. return true;
  2227. }
  2228. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  2229. {
  2230. work->data[64+12+0] = (nonce>>0) & 0xff;
  2231. work->data[64+12+1] = (nonce>>8) & 0xff;
  2232. work->data[64+12+2] = (nonce>>16) & 0xff;
  2233. work->data[64+12+3] = (nonce>>24) & 0xff;
  2234. /* Do one last check before attempting to submit the work */
  2235. if (!fulltest(work->data + 64, work->target))
  2236. return true;
  2237. return submit_work_sync(thr, work);
  2238. }
  2239. static void *miner_thread(void *userdata)
  2240. {
  2241. struct work work __attribute__((aligned(128)));
  2242. struct thr_info *mythr = userdata;
  2243. const int thr_id = mythr->id;
  2244. uint32_t max_nonce = 0xffffff, total_hashes = 0;
  2245. unsigned long hashes_done = max_nonce;
  2246. bool needs_work = true;
  2247. /* Try to cycle approximately 5 times before each log update */
  2248. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  2249. int request_interval;
  2250. bool requested = false;
  2251. uint32_t hash_div = 1;
  2252. double hash_divfloat = 1.0;
  2253. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2254. /* Request the next work item just before the end of the scantime. We
  2255. * don't want the work lying around too long since the CPU will always
  2256. * spend the full scantime */
  2257. request_interval = opt_scantime - 5;
  2258. if (request_interval < 1)
  2259. request_interval = 1;
  2260. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  2261. * and if that fails, then SCHED_BATCH. No need for this to be an
  2262. * error if it fails */
  2263. setpriority(PRIO_PROCESS, 0, 19);
  2264. drop_policy();
  2265. /* Cpu affinity only makes sense if the number of threads is a multiple
  2266. * of the number of CPUs */
  2267. if (!(opt_n_threads % num_processors))
  2268. affine_to_cpu(thr_id - gpu_threads, dev_from_id(thr_id));
  2269. /* Invalidate pool so it fails can_roll() test */
  2270. work.pool = NULL;
  2271. while (1) {
  2272. struct timeval tv_workstart, tv_start, tv_end, diff;
  2273. uint64_t max64;
  2274. bool rc;
  2275. if (needs_work) {
  2276. gettimeofday(&tv_workstart, NULL);
  2277. /* obtain new work from internal workio thread */
  2278. if (unlikely(!get_work(&work, requested, mythr, thr_id, hash_div))) {
  2279. applog(LOG_ERR, "work retrieval failed, exiting "
  2280. "mining thread %d", thr_id);
  2281. goto out;
  2282. }
  2283. mythr->cgpu->getworks++;
  2284. needs_work = requested = false;
  2285. total_hashes = 0;
  2286. max_nonce = work.blk.nonce + hashes_done;
  2287. }
  2288. hashes_done = 0;
  2289. gettimeofday(&tv_start, NULL);
  2290. /* scan nonces for a proof-of-work hash */
  2291. switch (opt_algo) {
  2292. case ALGO_C:
  2293. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  2294. work.hash1, work.hash, work.target,
  2295. max_nonce, &hashes_done,
  2296. work.blk.nonce);
  2297. break;
  2298. #ifdef WANT_X8664_SSE2
  2299. case ALGO_SSE2_64: {
  2300. unsigned int rc5 =
  2301. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  2302. work.hash1, work.hash,
  2303. work.target,
  2304. max_nonce, &hashes_done,
  2305. work.blk.nonce);
  2306. rc = (rc5 == -1) ? false : true;
  2307. }
  2308. break;
  2309. #endif
  2310. #ifdef WANT_X8664_SSE4
  2311. case ALGO_SSE4_64: {
  2312. unsigned int rc5 =
  2313. scanhash_sse4_64(thr_id, work.midstate, work.data + 64,
  2314. work.hash1, work.hash,
  2315. work.target,
  2316. max_nonce, &hashes_done,
  2317. work.blk.nonce);
  2318. rc = (rc5 == -1) ? false : true;
  2319. }
  2320. break;
  2321. #endif
  2322. #ifdef WANT_SSE2_4WAY
  2323. case ALGO_4WAY: {
  2324. unsigned int rc4 =
  2325. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  2326. work.hash1, work.hash,
  2327. work.target,
  2328. max_nonce, &hashes_done,
  2329. work.blk.nonce);
  2330. rc = (rc4 == -1) ? false : true;
  2331. }
  2332. break;
  2333. #endif
  2334. #ifdef WANT_VIA_PADLOCK
  2335. case ALGO_VIA:
  2336. rc = scanhash_via(thr_id, work.data, work.target,
  2337. max_nonce, &hashes_done,
  2338. work.blk.nonce);
  2339. break;
  2340. #endif
  2341. case ALGO_CRYPTOPP:
  2342. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  2343. work.hash1, work.hash, work.target,
  2344. max_nonce, &hashes_done,
  2345. work.blk.nonce);
  2346. break;
  2347. #ifdef WANT_CRYPTOPP_ASM32
  2348. case ALGO_CRYPTOPP_ASM32:
  2349. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  2350. work.hash1, work.hash, work.target,
  2351. max_nonce, &hashes_done,
  2352. work.blk.nonce);
  2353. break;
  2354. #endif
  2355. default:
  2356. /* should never happen */
  2357. goto out;
  2358. }
  2359. /* record scanhash elapsed time */
  2360. gettimeofday(&tv_end, NULL);
  2361. timeval_subtract(&diff, &tv_end, &tv_start);
  2362. hashes_done -= work.blk.nonce;
  2363. hashmeter(thr_id, &diff, hashes_done);
  2364. total_hashes += hashes_done;
  2365. work.blk.nonce += hashes_done;
  2366. /* adjust max_nonce to meet target cycle time */
  2367. if (diff.tv_usec > 500000)
  2368. diff.tv_sec++;
  2369. if (diff.tv_sec && diff.tv_sec != cycle) {
  2370. max64 = work.blk.nonce +
  2371. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  2372. } else if (!diff.tv_sec)
  2373. max64 = work.blk.nonce + (hashes_done * 2);
  2374. else
  2375. max64 = work.blk.nonce + hashes_done;
  2376. if (max64 > 0xfffffffaULL)
  2377. max64 = 0xfffffffaULL;
  2378. max_nonce = max64;
  2379. /* if nonce found, submit work */
  2380. if (unlikely(rc)) {
  2381. if (opt_debug)
  2382. applog(LOG_DEBUG, "CPU %d found something?", dev_from_id(thr_id));
  2383. if (unlikely(!submit_work_async(mythr, &work))) {
  2384. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  2385. break;
  2386. }
  2387. work.blk.nonce += 4;
  2388. }
  2389. timeval_subtract(&diff, &tv_end, &tv_workstart);
  2390. if (!requested && (diff.tv_sec >= request_interval)) {
  2391. thread_reportout(mythr);
  2392. if (unlikely(!queue_request())) {
  2393. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  2394. goto out;
  2395. }
  2396. thread_reportin(mythr);
  2397. requested = true;
  2398. }
  2399. if (diff.tv_sec > opt_scantime) {
  2400. decay_time(&hash_divfloat , (double)((MAXTHREADS / total_hashes) ? : 1));
  2401. hash_div = hash_divfloat;
  2402. needs_work = true;
  2403. } else if (work_restart[thr_id].restart || stale_work(&work) ||
  2404. work.blk.nonce >= MAXTHREADS - hashes_done)
  2405. needs_work = true;
  2406. }
  2407. out:
  2408. thread_reportin(mythr);
  2409. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  2410. tq_freeze(mythr->q);
  2411. return NULL;
  2412. }
  2413. enum {
  2414. STAT_SLEEP_INTERVAL = 1,
  2415. STAT_CTR_INTERVAL = 10000000,
  2416. FAILURE_INTERVAL = 30,
  2417. };
  2418. #ifdef HAVE_OPENCL
  2419. static _clState *clStates[16];
  2420. static cl_int queue_poclbm_kernel(_clState *clState, dev_blk_ctx *blk)
  2421. {
  2422. cl_kernel *kernel = &clState->kernel;
  2423. cl_int status = 0;
  2424. int num = 0;
  2425. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  2426. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  2427. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  2428. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  2429. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  2430. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  2431. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  2432. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  2433. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  2434. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  2435. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  2436. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  2437. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  2438. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  2439. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  2440. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  2441. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  2442. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  2443. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  2444. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  2445. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  2446. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  2447. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  2448. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  2449. (void *)&clState->outputBuffer);
  2450. return status;
  2451. }
  2452. static cl_int queue_phatk_kernel(_clState *clState, dev_blk_ctx *blk)
  2453. {
  2454. cl_kernel *kernel = &clState->kernel;
  2455. cl_int status = 0;
  2456. int num = 0;
  2457. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  2458. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  2459. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  2460. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  2461. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  2462. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  2463. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  2464. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  2465. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  2466. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  2467. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->C1addK5);
  2468. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->D1A);
  2469. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  2470. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  2471. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  2472. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  2473. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2A);
  2474. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  2475. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  2476. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17_2);
  2477. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4addT1);
  2478. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1substate0);
  2479. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  2480. (void *)&clState->outputBuffer);
  2481. return status;
  2482. }
  2483. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  2484. unsigned int *hashes, size_t *globalThreads,
  2485. unsigned int minthreads)
  2486. {
  2487. *threads = 1 << (15 + scan_intensity);
  2488. if (*threads < minthreads)
  2489. *threads = minthreads;
  2490. *globalThreads = *threads;
  2491. *hashes = *threads * vectors;
  2492. }
  2493. static void *gpuminer_thread(void *userdata)
  2494. {
  2495. cl_int (*queue_kernel_parameters)(_clState *, dev_blk_ctx *);
  2496. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  2497. struct timeval tv_start, tv_end, diff, tv_workstart;
  2498. struct thr_info *mythr = userdata;
  2499. const int thr_id = mythr->id;
  2500. uint32_t *res, *blank_res;
  2501. double gpu_ms_average = 7;
  2502. int gpu = dev_from_id(thr_id);
  2503. size_t globalThreads[1];
  2504. size_t localThreads[1];
  2505. cl_int status;
  2506. _clState *clState = clStates[thr_id];
  2507. const cl_kernel *kernel = &clState->kernel;
  2508. struct work *work = malloc(sizeof(struct work));
  2509. unsigned int threads;
  2510. unsigned const int vectors = clState->preferred_vwidth;
  2511. unsigned int hashes;
  2512. unsigned int hashes_done = 0;
  2513. /* Request the next work item at 2/3 of the scantime */
  2514. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  2515. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  2516. bool requested = false;
  2517. uint32_t total_hashes = 0, hash_div = 1;
  2518. switch (chosen_kernel) {
  2519. case KL_POCLBM:
  2520. queue_kernel_parameters = &queue_poclbm_kernel;
  2521. break;
  2522. case KL_PHATK:
  2523. default:
  2524. queue_kernel_parameters = &queue_phatk_kernel;
  2525. break;
  2526. }
  2527. if (opt_dynamic) {
  2528. /* Minimise impact on desktop if we want dynamic mode */
  2529. setpriority(PRIO_PROCESS, 0, 19);
  2530. drop_policy();
  2531. }
  2532. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2533. res = calloc(BUFFERSIZE, 1);
  2534. blank_res = calloc(BUFFERSIZE, 1);
  2535. if (!res || !blank_res) {
  2536. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  2537. goto out;
  2538. }
  2539. gettimeofday(&tv_start, NULL);
  2540. localThreads[0] = clState->work_size;
  2541. set_threads_hashes(vectors, &threads, &hashes, &globalThreads[0],
  2542. localThreads[0]);
  2543. diff.tv_sec = 0;
  2544. gettimeofday(&tv_end, NULL);
  2545. work->pool = NULL;
  2546. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  2547. BUFFERSIZE, blank_res, 0, NULL, NULL);
  2548. if (unlikely(status != CL_SUCCESS))
  2549. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  2550. mythr->cgpu->alive = true;
  2551. if (opt_debug)
  2552. applog(LOG_DEBUG, "Popping ping in gpuminer thread");
  2553. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  2554. gettimeofday(&tv_workstart, NULL);
  2555. /* obtain new work from internal workio thread */
  2556. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  2557. applog(LOG_ERR, "work retrieval failed, exiting "
  2558. "gpu mining thread %d", thr_id);
  2559. goto out;
  2560. }
  2561. mythr->cgpu->getworks++;
  2562. requested = false;
  2563. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  2564. work->blk.nonce = 0;
  2565. while (1) {
  2566. struct timeval tv_gpustart, tv_gpuend;
  2567. suseconds_t gpu_us;
  2568. gettimeofday(&tv_gpustart, NULL);
  2569. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  2570. /* This finish flushes the readbuffer set with CL_FALSE later */
  2571. clFinish(clState->commandQueue);
  2572. gettimeofday(&tv_gpuend, NULL);
  2573. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  2574. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  2575. decay_time(&gpu_ms_average, gpu_us / 1000);
  2576. if (opt_dynamic) {
  2577. /* Try to not let the GPU be out for longer than 6ms, but
  2578. * increase intensity when the system is idle, unless
  2579. * dynamic is disabled. */
  2580. if (gpu_ms_average > 7) {
  2581. if (scan_intensity > -10)
  2582. scan_intensity--;
  2583. } else if (gpu_ms_average < 3) {
  2584. if (scan_intensity < 10)
  2585. scan_intensity++;
  2586. }
  2587. }
  2588. set_threads_hashes(vectors, &threads, &hashes, globalThreads, localThreads[0]);
  2589. if (diff.tv_sec > opt_scantime ||
  2590. work->blk.nonce >= MAXTHREADS - hashes ||
  2591. work_restart[thr_id].restart ||
  2592. stale_work(work)) {
  2593. /* Ignore any reads since we're getting new work and queue a clean buffer */
  2594. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  2595. BUFFERSIZE, blank_res, 0, NULL, NULL);
  2596. if (unlikely(status != CL_SUCCESS))
  2597. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  2598. memset(res, 0, BUFFERSIZE);
  2599. gettimeofday(&tv_workstart, NULL);
  2600. if (opt_debug)
  2601. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  2602. /* obtain new work from internal workio thread */
  2603. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  2604. applog(LOG_ERR, "work retrieval failed, exiting "
  2605. "gpu mining thread %d", thr_id);
  2606. goto out;
  2607. }
  2608. mythr->cgpu->getworks++;
  2609. requested = false;
  2610. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  2611. work_restart[thr_id].restart = 0;
  2612. /* Flushes the writebuffer set with CL_FALSE above */
  2613. clFinish(clState->commandQueue);
  2614. }
  2615. status = queue_kernel_parameters(clState, &work->blk);
  2616. if (unlikely(status != CL_SUCCESS))
  2617. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  2618. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  2619. if (res[MAXBUFFERS]) {
  2620. /* Clear the buffer again */
  2621. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  2622. BUFFERSIZE, blank_res, 0, NULL, NULL);
  2623. if (unlikely(status != CL_SUCCESS))
  2624. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  2625. if (opt_debug)
  2626. applog(LOG_DEBUG, "GPU %d found something?", gpu);
  2627. postcalc_hash_async(mythr, work, res);
  2628. memset(res, 0, BUFFERSIZE);
  2629. clFinish(clState->commandQueue);
  2630. }
  2631. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  2632. globalThreads, localThreads, 0, NULL, NULL);
  2633. if (unlikely(status != CL_SUCCESS))
  2634. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  2635. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  2636. BUFFERSIZE, res, 0, NULL, NULL);
  2637. if (unlikely(status != CL_SUCCESS))
  2638. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  2639. gettimeofday(&tv_end, NULL);
  2640. timeval_subtract(&diff, &tv_end, &tv_start);
  2641. hashes_done += hashes;
  2642. total_hashes += hashes;
  2643. work->blk.nonce += hashes;
  2644. if (diff.tv_sec >= cycle) {
  2645. hashmeter(thr_id, &diff, hashes_done);
  2646. gettimeofday(&tv_start, NULL);
  2647. hashes_done = 0;
  2648. }
  2649. timeval_subtract(&diff, &tv_end, &tv_workstart);
  2650. if (!requested) {
  2651. #if 0
  2652. if (diff.tv_sec > request_interval)
  2653. hash_div = (MAXTHREADS / total_hashes) ? : 1;
  2654. #endif
  2655. if (diff.tv_sec > request_interval || work->blk.nonce > request_nonce) {
  2656. thread_reportout(mythr);
  2657. if (unlikely(!queue_request())) {
  2658. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  2659. goto out;
  2660. }
  2661. thread_reportin(mythr);
  2662. requested = true;
  2663. }
  2664. }
  2665. if (unlikely(!gpu_devices[gpu])) {
  2666. applog(LOG_WARNING, "Thread %d being disabled\n", thr_id);
  2667. mythr->rolling = mythr->cgpu->rolling = 0;
  2668. if (opt_debug)
  2669. applog(LOG_DEBUG, "Popping wakeup ping in gpuminer thread");
  2670. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  2671. applog(LOG_WARNING, "Thread %d being re-enabled\n", thr_id);
  2672. }
  2673. }
  2674. out:
  2675. thread_reportin(mythr);
  2676. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  2677. tq_freeze(mythr->q);
  2678. return NULL;
  2679. }
  2680. #endif /* HAVE_OPENCL */
  2681. static void restart_threads(void)
  2682. {
  2683. int i;
  2684. if (block_changed == BLOCK_DETECT)
  2685. block_changed = BLOCK_NONE;
  2686. /* Discard old queued requests and get new ones */
  2687. flush_requests();
  2688. for (i = 0; i < mining_threads; i++)
  2689. work_restart[i].restart = 1;
  2690. }
  2691. /* Stage another work item from the work returned in a longpoll */
  2692. static void convert_to_work(json_t *val)
  2693. {
  2694. struct work *work;
  2695. bool rc;
  2696. work = calloc(sizeof(*work), 1);
  2697. if (unlikely(!work)) {
  2698. applog(LOG_ERR, "OOM in convert_to_work");
  2699. return;
  2700. }
  2701. rc= work_decode(json_object_get(val, "result"), work);
  2702. if (unlikely(!rc)) {
  2703. applog(LOG_ERR, "Could not convert longpoll data to work");
  2704. return;
  2705. }
  2706. work->pool = current_pool();
  2707. if (opt_debug)
  2708. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  2709. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work)))
  2710. applog(LOG_ERR, "Could not tq_push work in convert_to_work");
  2711. else if (opt_debug)
  2712. applog(LOG_DEBUG, "Converted longpoll data to work");
  2713. }
  2714. static void *longpoll_thread(void *userdata)
  2715. {
  2716. struct thr_info *mythr = userdata;
  2717. CURL *curl = NULL;
  2718. char *copy_start, *hdr_path, *lp_url = NULL;
  2719. bool need_slash = false;
  2720. int failures = 0;
  2721. struct pool *pool = current_pool();
  2722. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2723. curl = curl_easy_init();
  2724. if (unlikely(!curl)) {
  2725. applog(LOG_ERR, "CURL initialisation failed");
  2726. goto out;
  2727. }
  2728. if (opt_debug)
  2729. applog(LOG_DEBUG, "Popping hdr path in longpoll thread");
  2730. hdr_path = tq_pop(mythr->q, NULL);
  2731. if (!hdr_path) {
  2732. applog(LOG_WARNING, "No long-poll found on this server");
  2733. goto out;
  2734. }
  2735. /* full URL */
  2736. if (strstr(hdr_path, "://")) {
  2737. lp_url = hdr_path;
  2738. hdr_path = NULL;
  2739. }
  2740. /* absolute path, on current server */
  2741. else {
  2742. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  2743. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  2744. need_slash = true;
  2745. lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  2746. if (!lp_url)
  2747. goto out;
  2748. sprintf(lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  2749. }
  2750. free(hdr_path);
  2751. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  2752. while (1) {
  2753. struct timeval start, end;
  2754. json_t *val;
  2755. gettimeofday(&start, NULL);
  2756. val = json_rpc_call(curl, lp_url, pool->rpc_userpass, rpc_req,
  2757. false, true, pool);
  2758. if (likely(val)) {
  2759. /* Keep track of who ordered a restart_threads to make
  2760. * sure it's only done once per new block */
  2761. if (block_changed != BLOCK_DETECT) {
  2762. block_changed = BLOCK_LP;
  2763. new_blocks++;
  2764. applog(LOG_WARNING, "LONGPOLL detected new block on network, waiting on fresh work");
  2765. restart_threads();
  2766. } else {
  2767. applog(LOG_WARNING, "LONGPOLL received after new block already detected");
  2768. block_changed = BLOCK_NONE;
  2769. }
  2770. convert_to_work(val);
  2771. failures = 0;
  2772. json_decref(val);
  2773. } else {
  2774. /* Some pools regularly drop the longpoll request so
  2775. * only see this as longpoll failure if it happens
  2776. * immediately and just restart it the rest of the
  2777. * time. */
  2778. gettimeofday(&end, NULL);
  2779. if (end.tv_sec - start.tv_sec > 30)
  2780. continue;
  2781. if (failures++ < 10) {
  2782. sleep(30);
  2783. applog(LOG_WARNING,
  2784. "longpoll failed, sleeping for 30s");
  2785. } else {
  2786. applog(LOG_ERR,
  2787. "longpoll failed, ending thread");
  2788. goto out;
  2789. }
  2790. }
  2791. }
  2792. out:
  2793. free(lp_url);
  2794. tq_freeze(mythr->q);
  2795. if (curl)
  2796. curl_easy_cleanup(curl);
  2797. return NULL;
  2798. }
  2799. static void stop_longpoll(void)
  2800. {
  2801. struct thr_info *thr = &thr_info[longpoll_thr_id];
  2802. tq_freeze(thr->q);
  2803. pthread_cancel(*thr->pth);
  2804. have_longpoll = false;
  2805. }
  2806. static void start_longpoll(void)
  2807. {
  2808. struct thr_info *thr = &thr_info[longpoll_thr_id];
  2809. tq_thaw(thr->q);
  2810. if (unlikely(thr_info_create(thr, NULL, longpoll_thread, thr)))
  2811. quit(1, "longpoll thread create failed");
  2812. pthread_detach(*thr->pth);
  2813. }
  2814. static void restart_longpoll(void)
  2815. {
  2816. stop_longpoll();
  2817. if (want_longpoll)
  2818. start_longpoll();
  2819. }
  2820. static void *reinit_cpu(void *userdata)
  2821. {
  2822. #if 0
  2823. struct cgpu_info *cgpu = (struct cgpu_info *)userdata;
  2824. int cpu = cgpu->cpu_gpu;
  2825. long thr_id = ....(long)userdata;
  2826. struct thr_info *thr = &thr_info[thr_id];
  2827. int cpu = dev_from_id(thr_id);
  2828. cpus[cpu].alive = false;
  2829. thr->rolling = thr->cgpu->rolling = 0;
  2830. tq_freeze(thr->q);
  2831. if (!pthread_cancel(*thr->pth))
  2832. pthread_join(*thr->pth, NULL);
  2833. free(thr->q);
  2834. thr->q = tq_new();
  2835. if (!thr->q)
  2836. quit(1, "Failed to tq_new in reinit_cputhread");
  2837. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  2838. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr))) {
  2839. applog(LOG_ERR, "thread %d create failed", thr_id);
  2840. return NULL;
  2841. }
  2842. tq_push(thr->q, &ping);
  2843. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  2844. #endif
  2845. return NULL;
  2846. }
  2847. #ifdef HAVE_OPENCL
  2848. static void *reinit_gpu(void *userdata)
  2849. {
  2850. struct cgpu_info *cgpu = (struct cgpu_info *)userdata;
  2851. int gpu = cgpu->cpu_gpu;
  2852. struct thr_info *thr;
  2853. char name[256];
  2854. int thr_id;
  2855. gpus[gpu].alive = false;
  2856. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  2857. if (dev_from_id(thr_id) != gpu)
  2858. continue;
  2859. thr = &thr_info[thr_id];
  2860. thr->rolling = thr->cgpu->rolling = 0;
  2861. tq_freeze(thr->q);
  2862. if (!pthread_cancel(*thr->pth)) {
  2863. pthread_join(*thr->pth, NULL);
  2864. free(thr->q);
  2865. free(clStates[thr_id]);
  2866. }
  2867. thr->q = tq_new();
  2868. if (!thr->q)
  2869. quit(1, "Failed to tq_new in reinit_gputhread");
  2870. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  2871. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  2872. if (!clStates[thr_id]) {
  2873. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  2874. return NULL;
  2875. }
  2876. applog(LOG_INFO, "initCl() finished. Found %s", name);
  2877. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr))) {
  2878. applog(LOG_ERR, "thread %d create failed", thr_id);
  2879. return NULL;
  2880. }
  2881. /* Try to re-enable it */
  2882. gpu_devices[gpu] = true;
  2883. if (opt_debug)
  2884. applog(LOG_DEBUG, "Pushing ping to thread %d", thr_id);
  2885. tq_push(thr->q, &ping);
  2886. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  2887. }
  2888. return NULL;
  2889. }
  2890. #else
  2891. static void *reinit_gpu(void *userdata)
  2892. {
  2893. }
  2894. #endif
  2895. static void reinit_device(struct cgpu_info *cgpu)
  2896. {
  2897. pthread_t resus_thread;
  2898. void *reinit;
  2899. if (cgpu->is_gpu)
  2900. reinit = reinit_gpu;
  2901. else
  2902. reinit = reinit_cpu;
  2903. if (unlikely(pthread_create(&resus_thread, NULL, reinit, (void *)cgpu)))
  2904. applog(LOG_ERR, "Failed to create reinit thread");
  2905. }
  2906. /* Determine which are the first threads belonging to a device and if they're
  2907. * active */
  2908. static bool active_device(int thr_id)
  2909. {
  2910. if (thr_id < gpu_threads) {
  2911. if (thr_id >= total_devices)
  2912. return false;
  2913. if (!gpu_devices[dev_from_id(thr_id)])
  2914. return false;
  2915. } else if (thr_id > gpu_threads + num_processors)
  2916. return false;
  2917. return true;
  2918. }
  2919. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  2920. * the screen at regular intervals, and restarts threads if they appear to have
  2921. * died. */
  2922. static void *watchdog_thread(void *userdata)
  2923. {
  2924. const unsigned int interval = opt_log_interval / 2 ? : 1;
  2925. static struct timeval rotate_tv;
  2926. struct timeval zero_tv;
  2927. bool statwin = false;
  2928. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2929. memset(&zero_tv, 0, sizeof(struct timeval));
  2930. gettimeofday(&rotate_tv, NULL);
  2931. while (1) {
  2932. int i;
  2933. struct timeval now;
  2934. sleep(interval);
  2935. if (requests_queued() < opt_queue)
  2936. queue_request();
  2937. hashmeter(-1, &zero_tv, 0);
  2938. if (curses_active) {
  2939. statwin ^= true;
  2940. mutex_lock(&curses_lock);
  2941. for (i = 0; i < mining_threads; i++)
  2942. curses_print_status(i);
  2943. if (statwin)
  2944. redrawwin(statuswin);
  2945. else {
  2946. check_logwinsize();
  2947. redrawwin(logwin);
  2948. }
  2949. mutex_unlock(&curses_lock);
  2950. }
  2951. if (unlikely(work_restart[watchdog_thr_id].restart)) {
  2952. restart_threads();
  2953. work_restart[watchdog_thr_id].restart = 0;
  2954. }
  2955. gettimeofday(&now, NULL);
  2956. for (i = 0; i < total_pools; i++) {
  2957. struct pool *pool = pools[i];
  2958. if (!pool->enabled)
  2959. continue;
  2960. /* Test pool is idle once every minute */
  2961. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  2962. gettimeofday(&pool->tv_idle, NULL);
  2963. if (pool_active(pool) && pool_tclear(pool, &pool->idle))
  2964. pool_resus(pool);
  2965. }
  2966. }
  2967. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  2968. gettimeofday(&rotate_tv, NULL);
  2969. switch_pools(NULL);
  2970. }
  2971. //for (i = 0; i < mining_threads; i++) {
  2972. for (i = 0; i < gpu_threads; i++) {
  2973. struct thr_info *thr = &thr_info[i];
  2974. /* Thread is waiting on getwork or disabled */
  2975. if (thr->getwork || !gpu_devices[i] || !gpus[i].alive)
  2976. continue;
  2977. if (now.tv_sec - thr->last.tv_sec > 60) {
  2978. thr->rolling = thr->cgpu->rolling = 0;
  2979. gpus[i].alive = false;
  2980. applog(LOG_ERR, "Thread %d idle for more than 60 seconds, GPU %d declared DEAD!", i, gpus[i]);
  2981. }
  2982. }
  2983. }
  2984. return NULL;
  2985. }
  2986. static void print_summary(void)
  2987. {
  2988. struct timeval diff;
  2989. int hours, mins, secs, i;
  2990. double utility, efficiency = 0.0;
  2991. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  2992. hours = diff.tv_sec / 3600;
  2993. mins = (diff.tv_sec % 3600) / 60;
  2994. secs = diff.tv_sec % 60;
  2995. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  2996. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  2997. printf("\nSummary of runtime statistics:\n\n");
  2998. printf("Started at %s\n", datestamp);
  2999. printf("Runtime: %d hrs : %d mins : %d secs\n", hours, mins, secs);
  3000. if (total_secs)
  3001. printf("Average hashrate: %.1f Megahash/s\n", total_mhashes_done / total_secs);
  3002. printf("Queued work requests: %d\n", total_getworks);
  3003. printf("Share submissions: %d\n", total_accepted + total_rejected);
  3004. printf("Accepted shares: %d\n", total_accepted);
  3005. printf("Rejected shares: %d\n", total_rejected);
  3006. if (total_accepted || total_rejected)
  3007. printf("Reject ratio: %.1f\n", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  3008. printf("Hardware errors: %d\n", hw_errors);
  3009. printf("Efficiency (accepted / queued): %.0f%%\n", efficiency);
  3010. printf("Utility (accepted shares / min): %.2f/min\n\n", utility);
  3011. printf("Discarded work due to new blocks: %d\n", total_discarded);
  3012. printf("Stale submissions discarded due to new blocks: %d\n", total_stale);
  3013. printf("Unable to get work from server occasions: %d\n", total_lo);
  3014. printf("Work items generated locally: %d\n", local_work);
  3015. printf("Submitting work remotely delay occasions: %d\n", total_ro);
  3016. printf("New blocks detected on network: %d\n\n", new_blocks);
  3017. if (total_pools > 1) {
  3018. for (i = 0; i < total_pools; i++) {
  3019. struct pool *pool = pools[i];
  3020. printf("Pool: %s\n", pool->rpc_url);
  3021. printf(" Queued work requests: %d\n", pool->getwork_requested);
  3022. printf(" Share submissions: %d\n", pool->accepted + pool->rejected);
  3023. printf(" Accepted shares: %d\n", pool->accepted);
  3024. printf(" Rejected shares: %d\n", pool->rejected);
  3025. if (pool->accepted || pool->rejected)
  3026. printf(" Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3027. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3028. printf(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  3029. printf(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  3030. printf(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  3031. printf(" Unable to get work from server occasions: %d\n", pool->localgen_occasions);
  3032. printf(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  3033. }
  3034. }
  3035. printf("Summary of per device statistics:\n\n");
  3036. for (i = 0; i < mining_threads; i++) {
  3037. if (active_device(i))
  3038. print_status(i);
  3039. }
  3040. printf("\n");
  3041. }
  3042. void quit(int status, const char *format, ...)
  3043. {
  3044. va_list ap;
  3045. disable_curses();
  3046. if (format) {
  3047. va_start(ap, format);
  3048. vfprintf(stderr, format, ap);
  3049. va_end(ap);
  3050. }
  3051. fprintf(stderr, "\n");
  3052. fflush(stderr);
  3053. exit(status);
  3054. }
  3055. static char *curses_input(const char *query)
  3056. {
  3057. char *input;
  3058. echo();
  3059. input = malloc(255);
  3060. if (!input)
  3061. quit(1, "Failed to malloc input");
  3062. leaveok(logwin, false);
  3063. wlogprint("%s: ", query);
  3064. wgetnstr(logwin, input, 255);
  3065. leaveok(logwin, true);
  3066. noecho();
  3067. return input;
  3068. }
  3069. static bool input_pool(bool live)
  3070. {
  3071. char *url = NULL, *user = NULL, *pass = NULL;
  3072. struct pool *pool = NULL;
  3073. bool ret = false;
  3074. immedok(logwin, true);
  3075. if (total_pools == MAX_POOLS) {
  3076. wlogprint("Reached maximum number of pools.\n");
  3077. goto out;
  3078. }
  3079. wlogprint("Input server details.\n");
  3080. url = curses_input("URL");
  3081. if (!url)
  3082. goto out;
  3083. if (strncmp(url, "http://", 7) &&
  3084. strncmp(url, "https://", 8)) {
  3085. char *httpinput;
  3086. httpinput = malloc(255);
  3087. if (!httpinput)
  3088. quit(1, "Failed to malloc httpinput");
  3089. strcpy(httpinput, "http://");
  3090. strncat(httpinput, url, 248);
  3091. free(url);
  3092. url = httpinput;
  3093. }
  3094. user = curses_input("Username");
  3095. if (!user)
  3096. goto out;
  3097. pass = curses_input("Password");
  3098. if (!pass)
  3099. goto out;
  3100. pool = calloc(sizeof(struct pool), 1);
  3101. if (!pool)
  3102. quit(1, "Failed to realloc pools in input_pool");
  3103. pool->pool_no = total_pools;
  3104. pool->prio = total_pools;
  3105. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  3106. quit (1, "Failed to pthread_mutex_init in input_pool");
  3107. pool->rpc_url = url;
  3108. pool->rpc_user = user;
  3109. pool->rpc_pass = pass;
  3110. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3111. if (!pool->rpc_userpass)
  3112. quit(1, "Failed to malloc userpass");
  3113. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3114. pool->tv_idle.tv_sec = ~0UL;
  3115. /* Test the pool before we enable it if we're live running, otherwise
  3116. * it will be tested separately */
  3117. ret = true;
  3118. if (live && pool_active(pool))
  3119. pool->enabled = true;
  3120. pools[total_pools++] = pool;
  3121. out:
  3122. immedok(logwin, false);
  3123. if (!ret) {
  3124. if (url)
  3125. free(url);
  3126. if (user)
  3127. free(user);
  3128. if (pass)
  3129. free(pass);
  3130. if (pool)
  3131. free(pool);
  3132. }
  3133. return ret;
  3134. }
  3135. int main (int argc, char *argv[])
  3136. {
  3137. unsigned int i, j = 0, x, y, pools_active = 0;
  3138. struct sigaction handler;
  3139. struct thr_info *thr;
  3140. char name[256];
  3141. /* This dangerous functions tramples random dynamically allocated
  3142. * variables so do it before anything at all */
  3143. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  3144. quit(1, "Failed to curl_global_init");
  3145. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  3146. quit(1, "Failed to pthread_mutex_init");
  3147. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  3148. quit(1, "Failed to pthread_mutex_init");
  3149. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  3150. quit(1, "Failed to pthread_mutex_init");
  3151. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  3152. quit(1, "Failed to pthread_mutex_init");
  3153. if (unlikely(pthread_mutex_init(&control_lock, NULL)))
  3154. quit(1, "Failed to pthread_mutex_init");
  3155. handler.sa_handler = &sighandler;
  3156. sigaction(SIGTERM, &handler, &termhandler);
  3157. sigaction(SIGINT, &handler, &inthandler);
  3158. gettimeofday(&total_tv_start, NULL);
  3159. gettimeofday(&total_tv_end, NULL);
  3160. get_datestamp(datestamp, &total_tv_start);
  3161. for (i = 0; i < 36; i++)
  3162. strcat(current_block, "0");
  3163. #ifdef WIN32
  3164. opt_n_threads = num_processors = 1;
  3165. #else
  3166. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  3167. opt_n_threads = num_processors;
  3168. #endif /* !WIN32 */
  3169. #ifdef HAVE_OPENCL
  3170. for (i = 0; i < 16; i++)
  3171. gpu_devices[i] = false;
  3172. nDevs = clDevicesNum();
  3173. if (nDevs < 0) {
  3174. applog(LOG_ERR, "clDevicesNum returned error, none usable");
  3175. nDevs = 0;
  3176. }
  3177. #endif
  3178. if (nDevs)
  3179. opt_n_threads = 0;
  3180. trpc_url = strdup(DEF_RPC_URL);
  3181. /* parse command line */
  3182. opt_register_table(opt_config_table,
  3183. "Options for both config file and command line");
  3184. opt_register_table(opt_cmdline_table,
  3185. "Options for command line only");
  3186. opt_parse(&argc, argv, applog_and_exit);
  3187. if (argc != 1)
  3188. quit(1, "Unexpected extra commandline arguments");
  3189. if (opt_kernel) {
  3190. if (strcmp(opt_kernel, "poclbm") && strcmp(opt_kernel, "phatk"))
  3191. quit(1, "Invalid kernel name specified - must be poclbm or phatk");
  3192. if (!strcmp(opt_kernel, "poclbm"))
  3193. chosen_kernel = KL_POCLBM;
  3194. else
  3195. chosen_kernel = KL_PHATK;
  3196. } else
  3197. chosen_kernel = KL_NONE;
  3198. gpu_threads = nDevs * opt_g_threads;
  3199. if (total_devices) {
  3200. if (total_devices > nDevs)
  3201. quit(1, "More devices specified than exist");
  3202. for (i = 0; i < 16; i++)
  3203. if (gpu_devices[i] && i + 1 > nDevs)
  3204. quit (1, "Command line options set a device that doesn't exist");
  3205. } else {
  3206. for (i = 0; i < nDevs; i++)
  3207. gpu_devices[i] = true;
  3208. total_devices = nDevs;
  3209. }
  3210. if (!gpu_threads && !forced_n_threads) {
  3211. /* Maybe they turned GPU off; restore default CPU threads. */
  3212. opt_n_threads = num_processors;
  3213. }
  3214. logcursor = 8;
  3215. gpucursor = logcursor;
  3216. cpucursor = gpucursor + nDevs;
  3217. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  3218. logcursor = logstart + 1;
  3219. /* Set up the ncurses interface */
  3220. if (!opt_realquiet && use_curses) {
  3221. mainwin = initscr();
  3222. getmaxyx(mainwin, y, x);
  3223. statuswin = newwin(logstart, x, 0, 0);
  3224. leaveok(statuswin, true);
  3225. logwin = newwin(y - logcursor, 0, logcursor, 0);
  3226. idlok(logwin, true);
  3227. scrollok(logwin, true);
  3228. leaveok(logwin, true);
  3229. cbreak();
  3230. noecho();
  3231. test_and_set(&curses_active);
  3232. }
  3233. if (!total_pools) {
  3234. if (curses_active) {
  3235. if (!input_pool(false))
  3236. quit(1, "Pool setup failed");
  3237. } else
  3238. quit(1, "No server specified");
  3239. }
  3240. for (i = 0; i < total_pools; i++) {
  3241. struct pool *pool = pools[i];
  3242. if (!pool->rpc_userpass) {
  3243. if (!pool->rpc_user || !pool->rpc_pass)
  3244. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  3245. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3246. if (!pool->rpc_userpass)
  3247. quit(1, "Failed to malloc userpass");
  3248. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3249. } else {
  3250. pool->rpc_user = malloc(strlen(pool->rpc_userpass));
  3251. if (!pool->rpc_user)
  3252. quit(1, "Failed to malloc user");
  3253. strcpy(pool->rpc_user, pool->rpc_userpass);
  3254. pool->rpc_user = strtok(pool->rpc_user, ":");
  3255. if (!pool->rpc_user)
  3256. quit(1, "Failed to find colon delimiter in userpass");
  3257. }
  3258. }
  3259. /* Set the currentpool to pool 0 */
  3260. currentpool = pools[0];
  3261. #ifdef HAVE_SYSLOG_H
  3262. if (use_syslog)
  3263. openlog("cpuminer", LOG_PID, LOG_USER);
  3264. #endif
  3265. mining_threads = opt_n_threads + gpu_threads;
  3266. total_threads = mining_threads + 5;
  3267. work_restart = calloc(total_threads, sizeof(*work_restart));
  3268. if (!work_restart)
  3269. quit(1, "Failed to calloc work_restart");
  3270. thr_info = calloc(total_threads, sizeof(*thr));
  3271. if (!thr_info)
  3272. quit(1, "Failed to calloc thr_info");
  3273. /* init workio thread info */
  3274. work_thr_id = mining_threads;
  3275. thr = &thr_info[work_thr_id];
  3276. thr->id = work_thr_id;
  3277. thr->q = tq_new();
  3278. if (!thr->q)
  3279. quit(1, "Failed to tq_new");
  3280. /* start work I/O thread */
  3281. if (thr_info_create(thr, NULL, workio_thread, thr))
  3282. quit(1, "workio thread create failed");
  3283. /* init longpoll thread info */
  3284. longpoll_thr_id = mining_threads + 1;
  3285. thr = &thr_info[longpoll_thr_id];
  3286. thr->id = longpoll_thr_id;
  3287. thr->q = tq_new();
  3288. if (!thr->q)
  3289. quit(1, "Failed to tq_new");
  3290. if (want_longpoll)
  3291. start_longpoll();
  3292. if (opt_n_threads ) {
  3293. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  3294. if (unlikely(!cpus))
  3295. quit(1, "Failed to calloc cpus");
  3296. }
  3297. if (gpu_threads) {
  3298. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  3299. if (unlikely(!gpus))
  3300. quit(1, "Failed to calloc gpus");
  3301. }
  3302. stage_thr_id = mining_threads + 3;
  3303. thr = &thr_info[stage_thr_id];
  3304. thr->q = tq_new();
  3305. if (!thr->q)
  3306. quit(1, "Failed to tq_new");
  3307. /* start stage thread */
  3308. if (thr_info_create(thr, NULL, stage_thread, thr))
  3309. quit(1, "stage thread create failed");
  3310. pthread_detach(*thr->pth);
  3311. /* Create a unique get work queue */
  3312. getq = tq_new();
  3313. if (!getq)
  3314. quit(1, "Failed to create getq");
  3315. /* Test each pool to see if we can retrieve and use work and for what
  3316. * it supports */
  3317. for (i = 0; i < total_pools; i++) {
  3318. struct pool *pool;
  3319. pool = pools[i];
  3320. if (pool_active(pool)) {
  3321. if (!currentpool)
  3322. currentpool = pool;
  3323. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  3324. pools_active++;
  3325. pool->enabled = true;
  3326. } else {
  3327. if (pool == currentpool)
  3328. currentpool = NULL;
  3329. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  3330. }
  3331. }
  3332. if (!pools_active)
  3333. quit(0, "No pools active! Exiting.");
  3334. #ifdef HAVE_OPENCL
  3335. i = 0;
  3336. /* start GPU mining threads */
  3337. for (j = 0; j < nDevs * opt_g_threads; j++) {
  3338. int gpu = j % nDevs;
  3339. gpus[gpu].is_gpu = 1;
  3340. gpus[gpu].cpu_gpu = gpu;
  3341. thr = &thr_info[i];
  3342. thr->id = i;
  3343. thr->cgpu = &gpus[gpu];
  3344. thr->q = tq_new();
  3345. if (!thr->q)
  3346. quit(1, "tq_new failed in starting gpu mining threads");
  3347. /* Enable threads for devices set not to mine but disable
  3348. * their queue in case we wish to enable them later*/
  3349. if (gpu_devices[gpu]) {
  3350. if (opt_debug)
  3351. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  3352. tq_push(thr->q, &ping);
  3353. }
  3354. applog(LOG_INFO, "Init GPU thread %i", i);
  3355. clStates[i] = initCl(gpu, name, sizeof(name));
  3356. if (!clStates[i]) {
  3357. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  3358. gpu_devices[i] = false;
  3359. continue;
  3360. }
  3361. applog(LOG_INFO, "initCl() finished. Found %s", name);
  3362. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr)))
  3363. quit(1, "thread %d create failed", i);
  3364. i++;
  3365. }
  3366. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  3367. #else
  3368. opt_g_threads = 0;
  3369. #endif
  3370. /* start CPU mining threads */
  3371. for (i = gpu_threads; i < mining_threads; i++) {
  3372. int cpu = (i - gpu_threads) % num_processors;
  3373. thr = &thr_info[i];
  3374. thr->id = i;
  3375. cpus[cpu].cpu_gpu = cpu;
  3376. thr->cgpu = &cpus[cpu];
  3377. thr->q = tq_new();
  3378. if (!thr->q)
  3379. quit(1, "tq_new failed in starting cpu mining threads");
  3380. thread_reportin(thr);
  3381. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  3382. quit(1, "thread %d create failed", i);
  3383. }
  3384. applog(LOG_INFO, "%d cpu miner threads started, "
  3385. "using SHA256 '%s' algorithm.",
  3386. opt_n_threads,
  3387. algo_names[opt_algo]);
  3388. watchdog_thr_id = mining_threads + 2;
  3389. thr = &thr_info[watchdog_thr_id];
  3390. /* start wakeup thread */
  3391. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  3392. quit(1, "wakeup thread create failed");
  3393. /* Create curses input thread for keyboard input */
  3394. input_thr_id = mining_threads + 4;
  3395. thr = &thr_info[input_thr_id];
  3396. if (thr_info_create(thr, NULL, input_thread, thr))
  3397. quit(1, "input thread create failed");
  3398. pthread_detach(*thr->pth);
  3399. /* main loop - simply wait for workio thread to exit */
  3400. pthread_join(*thr_info[work_thr_id].pth, NULL);
  3401. applog(LOG_INFO, "workio thread dead, exiting.");
  3402. gettimeofday(&total_tv_end, NULL);
  3403. disable_curses();
  3404. if (!opt_realquiet && successful_connect)
  3405. print_summary();
  3406. if (gpu_threads)
  3407. free(gpus);
  3408. if (opt_n_threads)
  3409. free(cpus);
  3410. curl_global_cleanup();
  3411. return 0;
  3412. }