cgminer.c 117 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535
  1. /*
  2. * Copyright 2011-2012 Con Kolivas
  3. * Copyright 2011-2012 Luke Dashjr
  4. * Copyright 2010 Jeff Garzik
  5. *
  6. * This program is free software; you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by the Free
  8. * Software Foundation; either version 2 of the License, or (at your option)
  9. * any later version. See COPYING for more details.
  10. */
  11. #include "config.h"
  12. #include <curses.h>
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <stdbool.h>
  17. #include <stdint.h>
  18. #include <unistd.h>
  19. #include <sys/time.h>
  20. #include <time.h>
  21. #include <math.h>
  22. #include <stdarg.h>
  23. #include <assert.h>
  24. #include <signal.h>
  25. #include <sys/stat.h>
  26. #include <sys/types.h>
  27. #ifndef WIN32
  28. #include <sys/resource.h>
  29. #endif
  30. #include <ccan/opt/opt.h>
  31. #include <jansson.h>
  32. #include <curl/curl.h>
  33. #include <libgen.h>
  34. #include <sha2.h>
  35. #include "compat.h"
  36. #include "miner.h"
  37. #include "findnonce.h"
  38. #include "adl.h"
  39. #include "device-cpu.h"
  40. #include "device-gpu.h"
  41. #if defined(unix)
  42. #include <errno.h>
  43. #include <fcntl.h>
  44. #include <sys/wait.h>
  45. #endif
  46. enum workio_commands {
  47. WC_GET_WORK,
  48. WC_SUBMIT_WORK,
  49. };
  50. struct workio_cmd {
  51. enum workio_commands cmd;
  52. struct thr_info *thr;
  53. union {
  54. struct work *work;
  55. } u;
  56. bool lagging;
  57. };
  58. struct strategies strategies[] = {
  59. { "Failover" },
  60. { "Round Robin" },
  61. { "Rotate" },
  62. { "Load Balance" },
  63. };
  64. static char packagename[255];
  65. int gpu_threads;
  66. bool opt_protocol = false;
  67. static bool want_longpoll = true;
  68. static bool have_longpoll = false;
  69. static bool want_per_device_stats = false;
  70. bool use_syslog = false;
  71. static bool opt_quiet = false;
  72. static bool opt_realquiet = false;
  73. bool opt_loginput = false;
  74. const int opt_cutofftemp = 95;
  75. static int opt_retries = -1;
  76. static int opt_fail_pause = 5;
  77. static int fail_pause = 5;
  78. int opt_log_interval = 5;
  79. static int opt_queue = 1;
  80. int opt_vectors;
  81. int opt_worksize;
  82. int opt_scantime = 60;
  83. int opt_expiry = 120;
  84. int opt_bench_algo = -1;
  85. static const bool opt_time = true;
  86. #ifdef HAVE_OPENCL
  87. static bool opt_restart = true;
  88. static bool opt_nogpu;
  89. #endif
  90. struct list_head scan_devices;
  91. int nDevs;
  92. int opt_g_threads = 2;
  93. static signed int devices_enabled = 0;
  94. static bool opt_removedisabled = false;
  95. int total_devices = 0;
  96. struct cgpu_info *devices[MAX_DEVICES];
  97. bool have_opencl = false;
  98. int gpu_threads;
  99. int opt_n_threads = -1;
  100. int mining_threads;
  101. int num_processors;
  102. bool use_curses = true;
  103. static bool opt_submit_stale;
  104. static int opt_shares;
  105. static bool opt_fail_only;
  106. bool opt_autofan;
  107. bool opt_autoengine;
  108. bool opt_noadl;
  109. char *opt_api_allow = NULL;
  110. char *opt_api_description = PACKAGE_STRING;
  111. int opt_api_port = 4028;
  112. bool opt_api_listen = false;
  113. bool opt_api_network = false;
  114. bool opt_delaynet = false;
  115. char *opt_kernel_path;
  116. char *cgminer_path;
  117. #define QUIET (opt_quiet || opt_realquiet)
  118. struct thr_info *thr_info;
  119. static int work_thr_id;
  120. int longpoll_thr_id;
  121. static int stage_thr_id;
  122. static int watchpool_thr_id;
  123. static int watchdog_thr_id;
  124. static int input_thr_id;
  125. int gpur_thr_id;
  126. static int api_thr_id;
  127. static int total_threads;
  128. struct work_restart *work_restart = NULL;
  129. static pthread_mutex_t hash_lock;
  130. static pthread_mutex_t qd_lock;
  131. static pthread_mutex_t *stgd_lock;
  132. static pthread_mutex_t curses_lock;
  133. static pthread_rwlock_t blk_lock;
  134. pthread_rwlock_t netacc_lock;
  135. double total_mhashes_done;
  136. static struct timeval total_tv_start, total_tv_end;
  137. pthread_mutex_t control_lock;
  138. int hw_errors;
  139. int total_accepted, total_rejected;
  140. int total_getworks, total_stale, total_discarded;
  141. static int total_queued;
  142. unsigned int new_blocks;
  143. static unsigned int work_block;
  144. unsigned int found_blocks;
  145. unsigned int local_work;
  146. unsigned int total_go, total_ro;
  147. struct pool *pools[MAX_POOLS];
  148. static struct pool *currentpool = NULL;
  149. int total_pools;
  150. enum pool_strategy pool_strategy = POOL_FAILOVER;
  151. int opt_rotate_period;
  152. static int total_urls, total_users, total_passes, total_userpasses;
  153. static bool curses_active = false;
  154. static char current_block[37];
  155. static char *current_hash;
  156. static char datestamp[40];
  157. static char blocktime[30];
  158. struct block {
  159. char hash[37];
  160. UT_hash_handle hh;
  161. };
  162. static struct block *blocks = NULL;
  163. char *opt_kernel = NULL;
  164. char *opt_socks_proxy = NULL;
  165. static const char def_conf[] = "cgminer.conf";
  166. static bool config_loaded = false;
  167. #if defined(unix)
  168. static char *opt_stderr_cmd = NULL;
  169. #endif // defined(unix)
  170. enum cl_kernels chosen_kernel;
  171. bool ping = true;
  172. struct sigaction termhandler, inthandler;
  173. struct thread_q *getq;
  174. static int total_work;
  175. struct work *staged_work = NULL;
  176. static int staged_clones;
  177. struct schedtime {
  178. bool enable;
  179. struct tm tm;
  180. };
  181. struct schedtime schedstart;
  182. struct schedtime schedstop;
  183. bool sched_paused;
  184. static bool time_before(struct tm *tm1, struct tm *tm2)
  185. {
  186. if (tm1->tm_hour < tm2->tm_hour)
  187. return true;
  188. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  189. return true;
  190. return false;
  191. }
  192. static bool should_run(void)
  193. {
  194. struct timeval tv;
  195. struct tm *tm;
  196. if (!schedstart.enable && !schedstop.enable)
  197. return true;
  198. gettimeofday(&tv, NULL);
  199. tm = localtime(&tv.tv_sec);
  200. if (schedstart.enable) {
  201. if (!schedstop.enable) {
  202. if (time_before(tm, &schedstart.tm))
  203. return false;
  204. /* This is a once off event with no stop time set */
  205. schedstart.enable = false;
  206. return true;
  207. }
  208. if (time_before(&schedstart.tm, &schedstop.tm)) {
  209. if (time_before(tm, &schedstop.tm) && !time_before(tm, &schedstart.tm))
  210. return true;
  211. return false;
  212. } /* Times are reversed */
  213. if (time_before(tm, &schedstart.tm)) {
  214. if (time_before(tm, &schedstop.tm))
  215. return true;
  216. return false;
  217. }
  218. return true;
  219. }
  220. /* only schedstop.enable == true */
  221. if (!time_before(tm, &schedstop.tm))
  222. return false;
  223. return true;
  224. }
  225. void get_datestamp(char *f, struct timeval *tv)
  226. {
  227. struct tm *tm;
  228. tm = localtime(&tv->tv_sec);
  229. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d]",
  230. tm->tm_year + 1900,
  231. tm->tm_mon + 1,
  232. tm->tm_mday,
  233. tm->tm_hour,
  234. tm->tm_min,
  235. tm->tm_sec);
  236. }
  237. void get_timestamp(char *f, struct timeval *tv)
  238. {
  239. struct tm *tm;
  240. tm = localtime(&tv->tv_sec);
  241. sprintf(f, "[%02d:%02d:%02d]",
  242. tm->tm_hour,
  243. tm->tm_min,
  244. tm->tm_sec);
  245. }
  246. static void applog_and_exit(const char *fmt, ...)
  247. {
  248. va_list ap;
  249. va_start(ap, fmt);
  250. vapplog(LOG_ERR, fmt, ap);
  251. va_end(ap);
  252. exit(1);
  253. }
  254. static void add_pool(void)
  255. {
  256. struct pool *pool;
  257. pool = calloc(sizeof(struct pool), 1);
  258. if (!pool) {
  259. applog(LOG_ERR, "Failed to malloc pool in add_pool");
  260. exit (1);
  261. }
  262. pool->pool_no = pool->prio = total_pools;
  263. pools[total_pools++] = pool;
  264. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL))) {
  265. applog(LOG_ERR, "Failed to pthread_mutex_init in add_pool");
  266. exit (1);
  267. }
  268. /* Make sure the pool doesn't think we've been idle since time 0 */
  269. pool->tv_idle.tv_sec = ~0UL;
  270. }
  271. /* Pool variant of test and set */
  272. static bool pool_tset(struct pool *pool, bool *var)
  273. {
  274. bool ret;
  275. mutex_lock(&pool->pool_lock);
  276. ret = *var;
  277. *var = true;
  278. mutex_unlock(&pool->pool_lock);
  279. return ret;
  280. }
  281. static bool pool_tclear(struct pool *pool, bool *var)
  282. {
  283. bool ret;
  284. mutex_lock(&pool->pool_lock);
  285. ret = *var;
  286. *var = false;
  287. mutex_unlock(&pool->pool_lock);
  288. return ret;
  289. }
  290. static bool pool_isset(struct pool *pool, bool *var)
  291. {
  292. bool ret;
  293. mutex_lock(&pool->pool_lock);
  294. ret = *var;
  295. mutex_unlock(&pool->pool_lock);
  296. return ret;
  297. }
  298. static struct pool *current_pool(void)
  299. {
  300. struct pool *pool;
  301. mutex_lock(&control_lock);
  302. pool = currentpool;
  303. mutex_unlock(&control_lock);
  304. return pool;
  305. }
  306. char *set_int_range(const char *arg, int *i, int min, int max)
  307. {
  308. char *err = opt_set_intval(arg, i);
  309. if (err)
  310. return err;
  311. if (*i < min || *i > max)
  312. return "Value out of range";
  313. return NULL;
  314. }
  315. static char *set_int_0_to_9999(const char *arg, int *i)
  316. {
  317. return set_int_range(arg, i, 0, 9999);
  318. }
  319. static char *set_int_1_to_65535(const char *arg, int *i)
  320. {
  321. return set_int_range(arg, i, 1, 65535);
  322. }
  323. static char *set_int_0_to_10(const char *arg, int *i)
  324. {
  325. return set_int_range(arg, i, 0, 10);
  326. }
  327. static char *set_int_1_to_10(const char *arg, int *i)
  328. {
  329. return set_int_range(arg, i, 1, 10);
  330. }
  331. #ifdef USE_BITFORCE
  332. static char *add_serial(char *arg)
  333. {
  334. string_elist_add(arg, &scan_devices);
  335. return NULL;
  336. }
  337. #endif
  338. static char *set_devices(char *arg)
  339. {
  340. int i = strtol(arg, &arg, 0);
  341. if (*arg) {
  342. if (*arg == '?') {
  343. devices_enabled = -1;
  344. return NULL;
  345. }
  346. return "Invalid device number";
  347. }
  348. if (i < 0 || i >= (int)(sizeof(devices_enabled) * 8) - 1)
  349. return "Invalid device number";
  350. devices_enabled |= 1 << i;
  351. return NULL;
  352. }
  353. static char *set_loadbalance(enum pool_strategy *strategy)
  354. {
  355. *strategy = POOL_LOADBALANCE;
  356. return NULL;
  357. }
  358. static char *set_rotate(const char *arg, int *i)
  359. {
  360. pool_strategy = POOL_ROTATE;
  361. return set_int_range(arg, i, 0, 9999);
  362. }
  363. static char *set_rr(enum pool_strategy *strategy)
  364. {
  365. *strategy = POOL_ROUNDROBIN;
  366. return NULL;
  367. }
  368. static char *set_url(char *arg)
  369. {
  370. struct pool *pool;
  371. total_urls++;
  372. if (total_urls > total_pools)
  373. add_pool();
  374. pool = pools[total_urls - 1];
  375. opt_set_charp(arg, &pool->rpc_url);
  376. if (strncmp(arg, "http://", 7) &&
  377. strncmp(arg, "https://", 8)) {
  378. char *httpinput;
  379. httpinput = malloc(255);
  380. if (!httpinput)
  381. quit(1, "Failed to malloc httpinput");
  382. strcpy(httpinput, "http://");
  383. strncat(httpinput, arg, 248);
  384. pool->rpc_url = httpinput;
  385. }
  386. return NULL;
  387. }
  388. static char *set_user(const char *arg)
  389. {
  390. struct pool *pool;
  391. if (total_userpasses)
  392. return "Use only user + pass or userpass, but not both";
  393. total_users++;
  394. if (total_users > total_pools)
  395. add_pool();
  396. pool = pools[total_users - 1];
  397. opt_set_charp(arg, &pool->rpc_user);
  398. return NULL;
  399. }
  400. static char *set_pass(const char *arg)
  401. {
  402. struct pool *pool;
  403. if (total_userpasses)
  404. return "Use only user + pass or userpass, but not both";
  405. total_passes++;
  406. if (total_passes > total_pools)
  407. add_pool();
  408. pool = pools[total_passes - 1];
  409. opt_set_charp(arg, &pool->rpc_pass);
  410. return NULL;
  411. }
  412. static char *set_userpass(const char *arg)
  413. {
  414. struct pool *pool;
  415. if (total_users || total_passes)
  416. return "Use only user + pass or userpass, but not both";
  417. total_userpasses++;
  418. if (total_userpasses > total_pools)
  419. add_pool();
  420. pool = pools[total_userpasses - 1];
  421. opt_set_charp(arg, &pool->rpc_userpass);
  422. return NULL;
  423. }
  424. static char *enable_debug(bool *flag)
  425. {
  426. *flag = true;
  427. /* Turn out verbose output, too. */
  428. opt_log_output = true;
  429. return NULL;
  430. }
  431. static char *set_schedtime(const char *arg, struct schedtime *st)
  432. {
  433. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  434. return "Invalid time set, should be HH:MM";
  435. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  436. return "Invalid time set.";
  437. st->enable = true;
  438. return NULL;
  439. }
  440. static char *temp_cutoff_str = NULL;
  441. char *set_temp_cutoff(char *arg)
  442. {
  443. int val;
  444. if (!(arg && arg[0]))
  445. return "Invalid parameters for set temp cutoff";
  446. val = atoi(arg);
  447. if (val < 0 || val > 200)
  448. return "Invalid value passed to set temp cutoff";
  449. temp_cutoff_str = arg;
  450. return NULL;
  451. }
  452. static void load_temp_cutoffs()
  453. {
  454. int i, val = 0, device = 0;
  455. char *nextptr;
  456. if (temp_cutoff_str) {
  457. for (device = 0, nextptr = strtok(temp_cutoff_str, ","); nextptr; ++device, nextptr = strtok(NULL, ",")) {
  458. if (device >= total_devices)
  459. quit(1, "Too many values passed to set temp cutoff");
  460. val = atoi(nextptr);
  461. if (val < 0 || val > 200)
  462. quit(1, "Invalid value passed to set temp cutoff");
  463. devices[device]->cutofftemp = val;
  464. }
  465. }
  466. else
  467. val = opt_cutofftemp;
  468. if (device <= 1) {
  469. for (i = device; i < total_devices; ++i)
  470. devices[i]->cutofftemp = val;
  471. }
  472. }
  473. static char *set_api_allow(const char *arg)
  474. {
  475. opt_set_charp(arg, &opt_api_allow);
  476. return NULL;
  477. }
  478. static char *set_api_description(const char *arg)
  479. {
  480. opt_set_charp(arg, &opt_api_description);
  481. return NULL;
  482. }
  483. /* These options are available from config file or commandline */
  484. static struct opt_table opt_config_table[] = {
  485. #ifdef WANT_CPUMINE
  486. OPT_WITH_ARG("--algo|-a",
  487. set_algo, show_algo, &opt_algo,
  488. "Specify sha256 implementation for CPU mining:\n"
  489. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  490. "\n\tc\t\tLinux kernel sha256, implemented in C"
  491. #ifdef WANT_SSE2_4WAY
  492. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  493. #endif
  494. #ifdef WANT_VIA_PADLOCK
  495. "\n\tvia\t\tVIA padlock implementation"
  496. #endif
  497. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  498. #ifdef WANT_CRYPTOPP_ASM32
  499. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  500. #endif
  501. #ifdef WANT_X8632_SSE2
  502. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  503. #endif
  504. #ifdef WANT_X8664_SSE2
  505. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  506. #endif
  507. #ifdef WANT_X8664_SSE4
  508. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  509. #endif
  510. #ifdef WANT_ALTIVEC_4WAY
  511. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  512. #endif
  513. ),
  514. #endif
  515. OPT_WITH_ARG("--api-allow",
  516. set_api_allow, NULL, NULL,
  517. "Allow API access only to the given list of IP[/Prefix] addresses[/subnets]"),
  518. OPT_WITH_ARG("--api-description",
  519. set_api_description, NULL, NULL,
  520. "Description placed in the API status header, default: cgminer version"),
  521. OPT_WITHOUT_ARG("--api-listen",
  522. opt_set_bool, &opt_api_listen,
  523. "Enable API, default: disabled"),
  524. OPT_WITHOUT_ARG("--api-network",
  525. opt_set_bool, &opt_api_network,
  526. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  527. OPT_WITH_ARG("--api-port",
  528. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  529. "Port number of miner API"),
  530. #ifdef HAVE_ADL
  531. OPT_WITHOUT_ARG("--auto-fan",
  532. opt_set_bool, &opt_autofan,
  533. "Automatically adjust all GPU fan speeds to maintain a target temperature"),
  534. OPT_WITHOUT_ARG("--auto-gpu",
  535. opt_set_bool, &opt_autoengine,
  536. "Automatically adjust all GPU engine clock speeds to maintain a target temperature"),
  537. #endif
  538. #ifdef WANT_CPUMINE
  539. OPT_WITH_ARG("--bench-algo|-b",
  540. set_int_0_to_9999, opt_show_intval, &opt_bench_algo,
  541. opt_hidden),
  542. OPT_WITH_ARG("--cpu-threads|-t",
  543. force_nthreads_int, opt_show_intval, &opt_n_threads,
  544. "Number of miner CPU threads"),
  545. #endif
  546. OPT_WITHOUT_ARG("--debug|-D",
  547. enable_debug, &opt_debug,
  548. "Enable debug output"),
  549. OPT_WITH_ARG("--device|-d",
  550. set_devices, NULL, NULL,
  551. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  552. #ifdef HAVE_OPENCL
  553. OPT_WITHOUT_ARG("--disable-gpu|-G",
  554. opt_set_bool, &opt_nogpu,
  555. "Disable GPU mining even if suitable devices exist"),
  556. #if defined(WANT_CPUMINE) && (defined(HAVE_OPENCL) || defined(USE_BITFORCE))
  557. OPT_WITHOUT_ARG("--enable-cpu|-C",
  558. opt_set_bool, &opt_usecpu,
  559. "Enable CPU mining with other mining (default: no CPU mining if other devices exist)"),
  560. #endif
  561. #endif
  562. OPT_WITH_ARG("--expiry|-E",
  563. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  564. "Upper bound on how many seconds after getting work we consider a share from it stale"),
  565. OPT_WITHOUT_ARG("--failover-only",
  566. opt_set_bool, &opt_fail_only,
  567. "Don't leak work to backup pools when primary pool is lagging"),
  568. #ifdef HAVE_OPENCL
  569. OPT_WITH_ARG("--gpu-platform",
  570. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  571. "Select OpenCL platform ID to use for GPU mining"),
  572. OPT_WITH_ARG("--gpu-threads|-g",
  573. set_int_1_to_10, opt_show_intval, &opt_g_threads,
  574. "Number of threads per GPU (1 - 10)"),
  575. #ifdef HAVE_ADL
  576. OPT_WITH_ARG("--gpu-engine",
  577. set_gpu_engine, NULL, NULL,
  578. "GPU engine (over)clock range in Mhz - one value, range and/or comma separated list (e.g. 850-900,900,750-850)"),
  579. OPT_WITH_ARG("--gpu-fan",
  580. set_gpu_fan, NULL, NULL,
  581. "GPU fan percentage range - one value, range and/or comma separated list (e.g. 0-85,85,65)"),
  582. OPT_WITH_ARG("--gpu-memclock",
  583. set_gpu_memclock, NULL, NULL,
  584. "Set the GPU memory (over)clock in Mhz - one value for all or separate by commas for per card"),
  585. OPT_WITH_ARG("--gpu-memdiff",
  586. set_gpu_memdiff, NULL, NULL,
  587. "Set a fixed difference in clock speed between the GPU and memory in auto-gpu mode"),
  588. OPT_WITH_ARG("--gpu-powertune",
  589. set_gpu_powertune, NULL, NULL,
  590. "Set the GPU powertune percentage - one value for all or separate by commas for per card"),
  591. OPT_WITHOUT_ARG("--gpu-reorder",
  592. opt_set_bool, &opt_reorder,
  593. "Attempt to reorder GPU devices according to PCI Bus ID"),
  594. OPT_WITH_ARG("--gpu-vddc",
  595. set_gpu_vddc, NULL, NULL,
  596. "Set the GPU voltage in Volts - one value for all or separate by commas for per card"),
  597. #endif
  598. OPT_WITH_ARG("--intensity|-I",
  599. set_intensity, NULL, NULL,
  600. "Intensity of GPU scanning (d or " _MIN_INTENSITY_STR " -> " _MAX_INTENSITY_STR ", default: d to maintain desktop interactivity)"),
  601. OPT_WITH_ARG("--kernel-path|-K",
  602. opt_set_charp, opt_show_charp, &opt_kernel_path,
  603. "Specify a path to where the kernel .cl files are"),
  604. OPT_WITH_ARG("--kernel|-k",
  605. opt_set_charp, NULL, &opt_kernel,
  606. "Select kernel to use (poclbm or phatk - default: auto)"),
  607. #endif
  608. OPT_WITHOUT_ARG("--load-balance",
  609. set_loadbalance, &pool_strategy,
  610. "Change multipool strategy from failover to even load balance"),
  611. OPT_WITH_ARG("--log|-l",
  612. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  613. "Interval in seconds between log output"),
  614. #if defined(unix)
  615. OPT_WITH_ARG("--monitor|-m",
  616. opt_set_charp, NULL, &opt_stderr_cmd,
  617. "Use custom pipe cmd for output messages"),
  618. #endif // defined(unix)
  619. OPT_WITHOUT_ARG("--net-delay",
  620. opt_set_bool, &opt_delaynet,
  621. "Impose small delays in networking to not overload slow routers"),
  622. #ifdef HAVE_ADL
  623. OPT_WITHOUT_ARG("--no-adl",
  624. opt_set_bool, &opt_noadl,
  625. "Disable the ATI display library used for monitoring and setting GPU parameters"),
  626. #endif
  627. OPT_WITHOUT_ARG("--no-longpoll",
  628. opt_set_invbool, &want_longpoll,
  629. "Disable X-Long-Polling support"),
  630. #ifdef HAVE_OPENCL
  631. OPT_WITHOUT_ARG("--no-restart",
  632. opt_set_invbool, &opt_restart,
  633. "Do not attempt to restart GPUs that hang"),
  634. #endif
  635. OPT_WITH_ARG("--pass|-p",
  636. set_pass, NULL, NULL,
  637. "Password for bitcoin JSON-RPC server"),
  638. OPT_WITHOUT_ARG("--per-device-stats",
  639. opt_set_bool, &want_per_device_stats,
  640. "Force verbose mode and output per-device statistics"),
  641. OPT_WITHOUT_ARG("--protocol-dump|-P",
  642. opt_set_bool, &opt_protocol,
  643. "Verbose dump of protocol-level activities"),
  644. OPT_WITH_ARG("--queue|-Q",
  645. set_int_0_to_10, opt_show_intval, &opt_queue,
  646. "Minimum number of work items to have queued (0 - 10)"),
  647. OPT_WITHOUT_ARG("--quiet|-q",
  648. opt_set_bool, &opt_quiet,
  649. "Disable logging output, display status and errors"),
  650. OPT_WITHOUT_ARG("--real-quiet",
  651. opt_set_bool, &opt_realquiet,
  652. "Disable all output"),
  653. OPT_WITHOUT_ARG("--remove-disabled",
  654. opt_set_bool, &opt_removedisabled,
  655. "Remove disabled devices entirely, as if they didn't exist"),
  656. OPT_WITH_ARG("--retries|-r",
  657. opt_set_intval, opt_show_intval, &opt_retries,
  658. "Number of times to retry before giving up, if JSON-RPC call fails (-1 means never)"),
  659. OPT_WITH_ARG("--retry-pause|-R",
  660. set_int_0_to_9999, opt_show_intval, &opt_fail_pause,
  661. "Number of seconds to pause, between retries"),
  662. OPT_WITH_ARG("--rotate",
  663. set_rotate, opt_show_intval, &opt_rotate_period,
  664. "Change multipool strategy from failover to regularly rotate at N minutes"),
  665. OPT_WITHOUT_ARG("--round-robin",
  666. set_rr, &pool_strategy,
  667. "Change multipool strategy from failover to round robin on failure"),
  668. #ifdef USE_BITFORCE
  669. OPT_WITH_ARG("--scan-serial|-S",
  670. add_serial, NULL, NULL,
  671. "Serial port to probe for BitForce device"),
  672. #endif
  673. OPT_WITH_ARG("--scan-time|-s",
  674. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  675. "Upper bound on time spent scanning current work, in seconds"),
  676. OPT_WITH_ARG("--sched-start",
  677. set_schedtime, NULL, &schedstart,
  678. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  679. OPT_WITH_ARG("--sched-stop",
  680. set_schedtime, NULL, &schedstop,
  681. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  682. OPT_WITH_ARG("--shares",
  683. opt_set_intval, NULL, &opt_shares,
  684. "Quit after mining N shares (default: unlimited)"),
  685. OPT_WITH_ARG("--socks-proxy",
  686. opt_set_charp, NULL, &opt_socks_proxy,
  687. "Set socks4 proxy (host:port)"),
  688. OPT_WITHOUT_ARG("--submit-stale",
  689. opt_set_bool, &opt_submit_stale,
  690. "Submit shares even if they would normally be considered stale"),
  691. #ifdef HAVE_SYSLOG_H
  692. OPT_WITHOUT_ARG("--syslog",
  693. opt_set_bool, &use_syslog,
  694. "Use system log for output messages (default: standard error)"),
  695. #endif
  696. #if defined(HAVE_ADL) || defined(USE_BITFORCE)
  697. OPT_WITH_ARG("--temp-cutoff",
  698. set_temp_cutoff, opt_show_intval, &opt_cutofftemp,
  699. "Temperature where a device will be automatically disabled, one value or comma separated list"),
  700. #endif
  701. #ifdef HAVE_ADL
  702. OPT_WITH_ARG("--temp-hysteresis",
  703. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  704. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  705. OPT_WITH_ARG("--temp-overheat",
  706. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  707. "Overheat temperature when automatically managing fan and GPU speeds, one value or comma separated list"),
  708. OPT_WITH_ARG("--temp-target",
  709. set_temp_target, opt_show_intval, &opt_targettemp,
  710. "Target temperature when automatically managing fan and GPU speeds, one value or comma separated list"),
  711. #endif
  712. OPT_WITHOUT_ARG("--text-only|-T",
  713. opt_set_invbool, &use_curses,
  714. "Disable ncurses formatted screen output"),
  715. OPT_WITH_ARG("--url|-o",
  716. set_url, NULL, NULL,
  717. "URL for bitcoin JSON-RPC server"),
  718. OPT_WITH_ARG("--user|-u",
  719. set_user, NULL, NULL,
  720. "Username for bitcoin JSON-RPC server"),
  721. #ifdef HAVE_OPENCL
  722. OPT_WITH_ARG("--vectors|-v",
  723. set_vector, NULL, &opt_vectors,
  724. "Override detected optimal vector width (1, 2 or 4)"),
  725. #endif
  726. OPT_WITHOUT_ARG("--verbose",
  727. opt_set_bool, &opt_log_output,
  728. "Log verbose output to stderr as well as status output"),
  729. #ifdef HAVE_OPENCL
  730. OPT_WITH_ARG("--worksize|-w",
  731. set_int_0_to_9999, opt_show_intval, &opt_worksize,
  732. "Override detected optimal worksize"),
  733. #endif
  734. OPT_WITH_ARG("--userpass|-O",
  735. set_userpass, NULL, NULL,
  736. "Username:Password pair for bitcoin JSON-RPC server"),
  737. OPT_WITH_ARG("--pools",
  738. opt_set_bool, NULL, NULL, opt_hidden),
  739. OPT_ENDTABLE
  740. };
  741. static char *parse_config(json_t *config, bool fileconf)
  742. {
  743. static char err_buf[200];
  744. json_t *val;
  745. struct opt_table *opt;
  746. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  747. char *p, *name;
  748. /* We don't handle subtables. */
  749. assert(!(opt->type & OPT_SUBTABLE));
  750. /* Pull apart the option name(s). */
  751. name = strdup(opt->names);
  752. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  753. char *err = NULL;
  754. /* Ignore short options. */
  755. if (p[1] != '-')
  756. continue;
  757. val = json_object_get(config, p+2);
  758. if (!val)
  759. continue;
  760. if ((opt->type & OPT_HASARG) && json_is_string(val)) {
  761. err = opt->cb_arg(json_string_value(val),
  762. opt->u.arg);
  763. } else if ((opt->type & OPT_HASARG) && json_is_array(val)) {
  764. int n, size = json_array_size(val);
  765. for(n = 0; n < size && !err; n++) {
  766. if (json_is_string(json_array_get(val, n)))
  767. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  768. else if (json_is_object(json_array_get(val, n)))
  769. err = parse_config(json_array_get(val, n), false);
  770. }
  771. } else if ((opt->type&OPT_NOARG) && json_is_true(val)) {
  772. err = opt->cb(opt->u.arg);
  773. } else {
  774. err = "Invalid value";
  775. }
  776. if (err) {
  777. /* Allow invalid values to be in configuration
  778. * file, just skipping over them provided the
  779. * JSON is still valid after that. */
  780. if (fileconf)
  781. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  782. else {
  783. sprintf(err_buf, "Parsing JSON option %s: %s",
  784. p, err);
  785. return err_buf;
  786. }
  787. }
  788. }
  789. free(name);
  790. }
  791. return NULL;
  792. }
  793. static char *load_config(const char *arg, void __maybe_unused *unused)
  794. {
  795. json_error_t err;
  796. json_t *config;
  797. #if JANSSON_MAJOR_VERSION > 1
  798. config = json_load_file(arg, 0, &err);
  799. #else
  800. config = json_load_file(arg, &err);
  801. #endif
  802. if (!json_is_object(config))
  803. return "JSON decode of file failed";
  804. config_loaded = true;
  805. /* Parse the config now, so we can override it. That can keep pointers
  806. * so don't free config object. */
  807. return parse_config(config, true);
  808. }
  809. static void load_default_config(void)
  810. {
  811. char buf[PATH_MAX];
  812. #if defined(unix)
  813. strcpy(buf, getenv("HOME"));
  814. if (*buf)
  815. strcat(buf, "/");
  816. else
  817. strcpy(buf, "");
  818. strcat(buf, ".cgminer/");
  819. #else
  820. strcpy(buf, "");
  821. #endif
  822. strcat(buf, def_conf);
  823. if (!access(buf, R_OK))
  824. load_config(buf, NULL);
  825. }
  826. extern const char *opt_argv0;
  827. static char *opt_verusage_and_exit(const char *extra)
  828. {
  829. printf("%s\nBuilt with "
  830. #ifdef HAVE_OPENCL
  831. "GPU "
  832. #endif
  833. #ifdef WANT_CPUMINE
  834. "CPU "
  835. #endif
  836. #ifdef USE_BITFORCE
  837. "bitforce "
  838. #endif
  839. "mining support.\n"
  840. , packagename);
  841. printf("%s", opt_usage(opt_argv0, extra));
  842. fflush(stdout);
  843. exit(0);
  844. }
  845. /* These options are available from commandline only */
  846. static struct opt_table opt_cmdline_table[] = {
  847. OPT_WITH_ARG("--config|-c",
  848. load_config, NULL, NULL,
  849. "Load a JSON-format configuration file\n"
  850. "See example.conf for an example configuration."),
  851. OPT_WITHOUT_ARG("--help|-h",
  852. opt_verusage_and_exit, NULL,
  853. "Print this message"),
  854. #ifdef HAVE_OPENCL
  855. OPT_WITHOUT_ARG("--ndevs|-n",
  856. print_ndevs_and_exit, &nDevs,
  857. "Display number of detected GPUs, OpenCL platform information, and exit"),
  858. #endif
  859. OPT_WITHOUT_ARG("--version|-V",
  860. opt_version_and_exit, packagename,
  861. "Display version and exit"),
  862. OPT_ENDTABLE
  863. };
  864. static bool jobj_binary(const json_t *obj, const char *key,
  865. void *buf, size_t buflen, bool required)
  866. {
  867. const char *hexstr;
  868. json_t *tmp;
  869. tmp = json_object_get(obj, key);
  870. if (unlikely(!tmp)) {
  871. if (unlikely(required))
  872. applog(LOG_ERR, "JSON key '%s' not found", key);
  873. return false;
  874. }
  875. hexstr = json_string_value(tmp);
  876. if (unlikely(!hexstr)) {
  877. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  878. return false;
  879. }
  880. if (!hex2bin(buf, hexstr, buflen))
  881. return false;
  882. return true;
  883. }
  884. static bool work_decode(const json_t *val, struct work *work)
  885. {
  886. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data), true))) {
  887. applog(LOG_ERR, "JSON inval data");
  888. goto err_out;
  889. }
  890. if (likely(!jobj_binary(val, "midstate",
  891. work->midstate, sizeof(work->midstate), false))) {
  892. // Calculate it ourselves
  893. union {
  894. unsigned char c[64];
  895. uint32_t i[16];
  896. } data;
  897. int swapcounter;
  898. for (swapcounter = 0; swapcounter < 16; swapcounter++)
  899. data.i[swapcounter] = swab32(((uint32_t*) (work->data))[swapcounter]);
  900. sha2_context ctx;
  901. sha2_starts( &ctx, 0 );
  902. sha2_update( &ctx, data.c, 64 );
  903. memcpy(work->midstate, ctx.state, sizeof(work->midstate));
  904. }
  905. if (likely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1), false))) {
  906. // Always the same anyway
  907. memcpy(work->hash1, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x80\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1\0\0", 64);
  908. }
  909. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target), true))) {
  910. applog(LOG_ERR, "JSON inval target");
  911. goto err_out;
  912. }
  913. memset(work->hash, 0, sizeof(work->hash));
  914. #ifdef __BIG_ENDIAN__
  915. int swapcounter = 0;
  916. for (swapcounter = 0; swapcounter < 32; swapcounter++)
  917. (((uint32_t*) (work->data))[swapcounter]) = swab32(((uint32_t*) (work->data))[swapcounter]);
  918. for (swapcounter = 0; swapcounter < 16; swapcounter++)
  919. (((uint32_t*) (work->hash1))[swapcounter]) = swab32(((uint32_t*) (work->hash1))[swapcounter]);
  920. for (swapcounter = 0; swapcounter < 8; swapcounter++)
  921. (((uint32_t*) (work->midstate))[swapcounter]) = swab32(((uint32_t*) (work->midstate))[swapcounter]);
  922. for (swapcounter = 0; swapcounter < 8; swapcounter++)
  923. (((uint32_t*) (work->target))[swapcounter]) = swab32(((uint32_t*) (work->target))[swapcounter]);
  924. #endif
  925. gettimeofday(&work->tv_staged, NULL);
  926. return true;
  927. err_out:
  928. return false;
  929. }
  930. int dev_from_id(int thr_id)
  931. {
  932. return thr_info[thr_id].cgpu->device_id;
  933. }
  934. /* Make the change in the recent value adjust dynamically when the difference
  935. * is large, but damp it when the values are closer together. This allows the
  936. * value to change quickly, but not fluctuate too dramatically when it has
  937. * stabilised. */
  938. void decay_time(double *f, double fadd)
  939. {
  940. double ratio = 0;
  941. if (likely(*f > 0)) {
  942. ratio = fadd / *f;
  943. if (ratio > 1)
  944. ratio = 1 / ratio;
  945. }
  946. if (ratio > 0.9)
  947. *f = (fadd * 0.1 + *f) / 1.1;
  948. else
  949. *f = (fadd + *f * 0.1) / 1.1;
  950. }
  951. static int requests_staged(void)
  952. {
  953. int ret;
  954. mutex_lock(stgd_lock);
  955. ret = HASH_COUNT(staged_work);
  956. mutex_unlock(stgd_lock);
  957. return ret;
  958. }
  959. WINDOW *mainwin, *statuswin, *logwin;
  960. double total_secs = 0.1;
  961. static char statusline[256];
  962. static int devcursor, logstart, logcursor;
  963. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  964. struct cgpu_info *cpus;
  965. static inline void unlock_curses(void)
  966. {
  967. mutex_unlock(&curses_lock);
  968. }
  969. static inline void lock_curses(void)
  970. {
  971. mutex_lock(&curses_lock);
  972. }
  973. static bool curses_active_locked(void)
  974. {
  975. bool ret;
  976. lock_curses();
  977. ret = curses_active;
  978. if (!ret)
  979. unlock_curses();
  980. return ret;
  981. }
  982. void tailsprintf(char *f, const char *fmt, ...)
  983. {
  984. va_list ap;
  985. va_start(ap, fmt);
  986. vsprintf(f + strlen(f), fmt, ap);
  987. va_end(ap);
  988. }
  989. static void get_statline(char *buf, struct cgpu_info *cgpu)
  990. {
  991. sprintf(buf, "%s%d ", cgpu->api->name, cgpu->device_id);
  992. if (cgpu->api->get_statline_before)
  993. cgpu->api->get_statline_before(buf, cgpu);
  994. tailsprintf(buf, "(%ds):%.1f (avg):%.1f Mh/s | A:%d R:%d HW:%d U:%.2f/m",
  995. opt_log_interval,
  996. cgpu->rolling,
  997. cgpu->total_mhashes / total_secs,
  998. cgpu->accepted,
  999. cgpu->rejected,
  1000. cgpu->hw_errors,
  1001. cgpu->utility);
  1002. if (cgpu->api->get_statline)
  1003. cgpu->api->get_statline(buf, cgpu);
  1004. }
  1005. static void text_print_status(int thr_id)
  1006. {
  1007. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1008. char logline[255];
  1009. if (cgpu) {
  1010. get_statline(logline, cgpu);
  1011. printf("%s\n", logline);
  1012. }
  1013. }
  1014. /* Must be called with curses mutex lock held and curses_active */
  1015. static void curses_print_status(void)
  1016. {
  1017. struct pool *pool = current_pool();
  1018. wattron(statuswin, A_BOLD);
  1019. mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  1020. #ifdef WANT_CPUMINE
  1021. if (opt_n_threads)
  1022. wprintw(statuswin, " CPU Algo: %s", algo_names[opt_algo]);
  1023. #endif
  1024. wattroff(statuswin, A_BOLD);
  1025. mvwhline(statuswin, 1, 0, '-', 80);
  1026. mvwprintw(statuswin, 2, 0, " %s", statusline);
  1027. wclrtoeol(statuswin);
  1028. mvwprintw(statuswin, 3, 0, " TQ: %d ST: %d SS: %d DW: %d NB: %d LW: %d GF: %d RF: %d",
  1029. total_queued, requests_staged(), total_stale, total_discarded, new_blocks,
  1030. local_work, total_go, total_ro);
  1031. wclrtoeol(statuswin);
  1032. if (pool_strategy == POOL_LOADBALANCE && total_pools > 1)
  1033. mvwprintw(statuswin, 4, 0, " Connected to multiple pools with%s LP",
  1034. have_longpoll ? "": "out");
  1035. else
  1036. mvwprintw(statuswin, 4, 0, " Connected to %s with%s LP as user %s",
  1037. pool->rpc_url, have_longpoll ? "": "out", pool->rpc_user);
  1038. wclrtoeol(statuswin);
  1039. mvwprintw(statuswin, 5, 0, " Block: %s... Started: %s", current_hash, blocktime);
  1040. mvwhline(statuswin, 6, 0, '-', 80);
  1041. mvwhline(statuswin, logstart - 1, 0, '-', 80);
  1042. mvwprintw(statuswin, devcursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
  1043. have_opencl ? "[G]PU management " : "");
  1044. /* The window will be updated once we're done with all the devices */
  1045. wnoutrefresh(statuswin);
  1046. }
  1047. static void adj_width(int var, int *length)
  1048. {
  1049. if ((int)(log10(var) + 1) > *length)
  1050. (*length)++;
  1051. }
  1052. static void curses_print_devstatus(int thr_id)
  1053. {
  1054. static int awidth = 1, rwidth = 1, hwwidth = 1, uwidth = 1;
  1055. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1056. char logline[255];
  1057. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1058. mvwprintw(statuswin, devcursor + cgpu->cgminer_id, 0, " %s %d: ", cgpu->api->name, cgpu->device_id);
  1059. if (cgpu->api->get_statline_before) {
  1060. logline[0] = '\0';
  1061. cgpu->api->get_statline_before(logline, cgpu);
  1062. wprintw(statuswin, "%s", logline);
  1063. }
  1064. if (cgpu->status == LIFE_DEAD)
  1065. wprintw(statuswin, "DEAD ");
  1066. else if (cgpu->status == LIFE_SICK)
  1067. wprintw(statuswin, "SICK ");
  1068. else if (!cgpu->enabled)
  1069. wprintw(statuswin, "OFF ");
  1070. else
  1071. wprintw(statuswin, "%5.1f", cgpu->rolling);
  1072. adj_width(cgpu->accepted, &awidth);
  1073. adj_width(cgpu->rejected, &rwidth);
  1074. adj_width(cgpu->hw_errors, &hwwidth);
  1075. adj_width(cgpu->utility, &uwidth);
  1076. wprintw(statuswin, "/%5.1fMh/s | A:%*d R:%*d HW:%*d U:%*.2f/m",
  1077. cgpu->total_mhashes / total_secs,
  1078. awidth, cgpu->accepted,
  1079. rwidth, cgpu->rejected,
  1080. hwwidth, cgpu->hw_errors,
  1081. uwidth + 3, cgpu->utility);
  1082. if (cgpu->api->get_statline) {
  1083. logline[0] = '\0';
  1084. cgpu->api->get_statline(logline, cgpu);
  1085. wprintw(statuswin, "%s", logline);
  1086. }
  1087. wclrtoeol(statuswin);
  1088. wnoutrefresh(statuswin);
  1089. }
  1090. static void print_status(int thr_id)
  1091. {
  1092. if (!curses_active)
  1093. text_print_status(thr_id);
  1094. }
  1095. /* Check for window resize. Called with curses mutex locked */
  1096. static inline bool change_logwinsize(void)
  1097. {
  1098. int x, y, logx, logy;
  1099. getmaxyx(mainwin, y, x);
  1100. getmaxyx(logwin, logy, logx);
  1101. y -= logcursor;
  1102. /* Detect screen size change */
  1103. if ((x != logx || y != logy) && x >= 80 && y >= 25) {
  1104. wresize(logwin, y, x);
  1105. return true;
  1106. }
  1107. return false;
  1108. }
  1109. /* For mandatory printing when mutex is already locked */
  1110. void wlog(const char *f, ...)
  1111. {
  1112. va_list ap;
  1113. va_start(ap, f);
  1114. vw_printw(logwin, f, ap);
  1115. va_end(ap);
  1116. }
  1117. /* Mandatory printing */
  1118. void wlogprint(const char *f, ...)
  1119. {
  1120. va_list ap;
  1121. if (curses_active_locked()) {
  1122. va_start(ap, f);
  1123. vw_printw(logwin, f, ap);
  1124. va_end(ap);
  1125. wrefresh(logwin);
  1126. unlock_curses();
  1127. }
  1128. }
  1129. void log_curses(int prio, const char *f, va_list ap)
  1130. {
  1131. if (opt_quiet && prio != LOG_ERR)
  1132. return;
  1133. if (curses_active_locked()) {
  1134. if (!opt_loginput || prio == LOG_ERR || prio == LOG_WARNING) {
  1135. vw_printw(logwin, f, ap);
  1136. wrefresh(logwin);
  1137. }
  1138. unlock_curses();
  1139. } else
  1140. vprintf(f, ap);
  1141. }
  1142. void clear_logwin(void)
  1143. {
  1144. if (curses_active_locked()) {
  1145. wclear(logwin);
  1146. wrefresh(logwin);
  1147. unlock_curses();
  1148. }
  1149. }
  1150. /* regenerate the full work->hash value and also return true if it's a block */
  1151. bool regeneratehash(const struct work *work)
  1152. {
  1153. uint32_t *data32 = (uint32_t *)(work->data);
  1154. unsigned char swap[128];
  1155. uint32_t *swap32 = (uint32_t *)swap;
  1156. unsigned char hash1[32];
  1157. uint32_t *hash32 = (uint32_t *)(work->hash);
  1158. uint32_t difficulty = 0;
  1159. uint32_t diffbytes = 0;
  1160. uint32_t diffvalue = 0;
  1161. uint32_t diffcmp[8];
  1162. int diffshift = 0;
  1163. int i;
  1164. for (i = 0; i < 80 / 4; i++)
  1165. swap32[i] = swab32(data32[i]);
  1166. sha2(swap, 80, hash1, false);
  1167. sha2(hash1, 32, (unsigned char *)(work->hash), false);
  1168. difficulty = swab32(*((uint32_t *)(work->data + 72)));
  1169. diffbytes = ((difficulty >> 24) & 0xff) - 3;
  1170. diffvalue = difficulty & 0x00ffffff;
  1171. diffshift = (diffbytes % 4) * 8;
  1172. if (diffshift == 0) {
  1173. diffshift = 32;
  1174. diffbytes--;
  1175. }
  1176. memset(diffcmp, 0, 32);
  1177. diffcmp[(diffbytes >> 2) + 1] = diffvalue >> (32 - diffshift);
  1178. diffcmp[diffbytes >> 2] = diffvalue << diffshift;
  1179. for (i = 7; i >= 0; i--) {
  1180. if (hash32[i] > diffcmp[i])
  1181. return false;
  1182. if (hash32[i] < diffcmp[i])
  1183. return true;
  1184. }
  1185. // https://en.bitcoin.it/wiki/Block says: "numerically below"
  1186. // https://en.bitcoin.it/wiki/Target says: "lower than or equal to"
  1187. // code in bitcoind 0.3.24 main.cpp CheckWork() says: if (hash > hashTarget) return false;
  1188. if (hash32[0] == diffcmp[0])
  1189. return true;
  1190. else
  1191. return false;
  1192. }
  1193. static bool submit_upstream_work(const struct work *work)
  1194. {
  1195. char *hexstr = NULL;
  1196. json_t *val, *res;
  1197. char s[345], sd[345];
  1198. bool rc = false;
  1199. int thr_id = work->thr_id;
  1200. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1201. CURL *curl = curl_easy_init();
  1202. struct pool *pool = work->pool;
  1203. bool rolltime;
  1204. uint32_t *hash32;
  1205. char hashshow[64+1] = "";
  1206. bool isblock;
  1207. if (unlikely(!curl)) {
  1208. applog(LOG_ERR, "CURL initialisation failed");
  1209. return rc;
  1210. }
  1211. #ifdef __BIG_ENDIAN__
  1212. int swapcounter = 0;
  1213. for (swapcounter = 0; swapcounter < 32; swapcounter++)
  1214. (((uint32_t*) (work->data))[swapcounter]) = swab32(((uint32_t*) (work->data))[swapcounter]);
  1215. #endif
  1216. /* build hex string */
  1217. hexstr = bin2hex(work->data, sizeof(work->data));
  1218. if (unlikely(!hexstr)) {
  1219. applog(LOG_ERR, "submit_upstream_work OOM");
  1220. goto out_nofree;
  1221. }
  1222. /* build JSON-RPC request */
  1223. sprintf(s,
  1224. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  1225. hexstr);
  1226. sprintf(sd,
  1227. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}",
  1228. hexstr);
  1229. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  1230. /* Force a fresh connection in case there are dead persistent
  1231. * connections to this pool */
  1232. if (pool_isset(pool, &pool->submit_fail))
  1233. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1234. /* issue JSON-RPC request */
  1235. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool, true);
  1236. if (unlikely(!val)) {
  1237. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  1238. if (!pool_tset(pool, &pool->submit_fail)) {
  1239. total_ro++;
  1240. pool->remotefail_occasions++;
  1241. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  1242. }
  1243. goto out;
  1244. } else if (pool_tclear(pool, &pool->submit_fail))
  1245. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  1246. res = json_object_get(val, "result");
  1247. if (!QUIET) {
  1248. isblock = regeneratehash(work);
  1249. if (isblock)
  1250. found_blocks++;
  1251. hash32 = (uint32_t *)(work->hash);
  1252. sprintf(hashshow, "%08lx.%08lx.%08lx%s",
  1253. (unsigned long)(hash32[7]), (unsigned long)(hash32[6]), (unsigned long)(hash32[5]),
  1254. isblock ? " BLOCK!" : "");
  1255. }
  1256. /* Theoretically threads could race when modifying accepted and
  1257. * rejected values but the chance of two submits completing at the
  1258. * same time is zero so there is no point adding extra locking */
  1259. if (json_is_true(res)) {
  1260. cgpu->accepted++;
  1261. total_accepted++;
  1262. pool->accepted++;
  1263. cgpu->last_share_pool = pool->pool_no;
  1264. cgpu->last_share_pool_time = time(NULL);
  1265. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  1266. if (!QUIET) {
  1267. if (total_pools > 1)
  1268. applog(LOG_NOTICE, "Accepted %s %s %d thread %d pool %d",
  1269. hashshow, cgpu->api->name, cgpu->device_id, thr_id, work->pool->pool_no);
  1270. else
  1271. applog(LOG_NOTICE, "Accepted %s %s %d thread %d",
  1272. hashshow, cgpu->api->name, cgpu->device_id, thr_id);
  1273. }
  1274. if (opt_shares && total_accepted >= opt_shares) {
  1275. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  1276. kill_work();
  1277. goto out;
  1278. }
  1279. } else {
  1280. cgpu->rejected++;
  1281. total_rejected++;
  1282. pool->rejected++;
  1283. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  1284. if (!QUIET) {
  1285. char where[17];
  1286. char reason[32];
  1287. if (total_pools > 1)
  1288. sprintf(where, " pool %d", work->pool->pool_no);
  1289. else
  1290. strcpy(where, "");
  1291. res = json_object_get(val, "reject-reason");
  1292. if (res) {
  1293. const char *reasontmp = json_string_value(res);
  1294. size_t reasonLen = strlen(reasontmp);
  1295. if (reasonLen > 28)
  1296. reasonLen = 28;
  1297. reason[0] = ' '; reason[1] = '(';
  1298. memcpy(2 + reason, reasontmp, reasonLen);
  1299. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  1300. } else
  1301. strcpy(reason, "");
  1302. applog(LOG_NOTICE, "Rejected %s %s %d thread %d%s%s",
  1303. hashshow, cgpu->api->name, cgpu->device_id, thr_id, where, reason);
  1304. }
  1305. }
  1306. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1307. if (!opt_realquiet)
  1308. print_status(thr_id);
  1309. if (!want_per_device_stats) {
  1310. char logline[255];
  1311. get_statline(logline, cgpu);
  1312. applog(LOG_INFO, "%s", logline);
  1313. }
  1314. json_decref(val);
  1315. rc = true;
  1316. out:
  1317. free(hexstr);
  1318. out_nofree:
  1319. curl_easy_cleanup(curl);
  1320. return rc;
  1321. }
  1322. static const char *rpc_req =
  1323. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  1324. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  1325. static inline struct pool *select_pool(bool lagging)
  1326. {
  1327. static int rotating_pool = 0;
  1328. struct pool *pool, *cp;
  1329. cp = current_pool();
  1330. if (pool_strategy != POOL_LOADBALANCE && !lagging)
  1331. pool = cp;
  1332. else
  1333. pool = NULL;
  1334. while (!pool) {
  1335. if (++rotating_pool >= total_pools)
  1336. rotating_pool = 0;
  1337. pool = pools[rotating_pool];
  1338. if ((!pool->idle && pool->enabled) || pool == cp)
  1339. break;
  1340. pool = NULL;
  1341. }
  1342. return pool;
  1343. }
  1344. static bool get_upstream_work(struct work *work, bool lagging)
  1345. {
  1346. struct pool *pool;
  1347. json_t *val = NULL;
  1348. bool rc = false;
  1349. int retries = 0;
  1350. CURL *curl;
  1351. curl = curl_easy_init();
  1352. if (unlikely(!curl)) {
  1353. applog(LOG_ERR, "CURL initialisation failed");
  1354. return rc;
  1355. }
  1356. pool = select_pool(lagging);
  1357. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  1358. retry:
  1359. /* A single failure response here might be reported as a dead pool and
  1360. * there may be temporary denied messages etc. falsely reporting
  1361. * failure so retry a few times before giving up */
  1362. while (!val && retries++ < 3) {
  1363. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  1364. false, false, &work->rolltime, pool, false);
  1365. }
  1366. if (unlikely(!val)) {
  1367. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  1368. goto out;
  1369. }
  1370. rc = work_decode(json_object_get(val, "result"), work);
  1371. if (!rc && retries < 3) {
  1372. /* Force a fresh connection in case there are dead persistent
  1373. * connections */
  1374. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1375. goto retry;
  1376. }
  1377. work->pool = pool;
  1378. total_getworks++;
  1379. pool->getwork_requested++;
  1380. json_decref(val);
  1381. out:
  1382. curl_easy_cleanup(curl);
  1383. return rc;
  1384. }
  1385. static struct work *make_work(void)
  1386. {
  1387. struct work *work = calloc(1, sizeof(struct work));
  1388. if (unlikely(!work))
  1389. quit(1, "Failed to calloc work in make_work");
  1390. work->id = total_work++;
  1391. return work;
  1392. }
  1393. static void free_work(struct work *work)
  1394. {
  1395. free(work);
  1396. }
  1397. static void workio_cmd_free(struct workio_cmd *wc)
  1398. {
  1399. if (!wc)
  1400. return;
  1401. switch (wc->cmd) {
  1402. case WC_SUBMIT_WORK:
  1403. free_work(wc->u.work);
  1404. break;
  1405. default: /* do nothing */
  1406. break;
  1407. }
  1408. memset(wc, 0, sizeof(*wc)); /* poison */
  1409. free(wc);
  1410. }
  1411. static void disable_curses(void)
  1412. {
  1413. if (curses_active_locked()) {
  1414. curses_active = false;
  1415. leaveok(logwin, false);
  1416. leaveok(statuswin, false);
  1417. leaveok(mainwin, false);
  1418. nocbreak();
  1419. echo();
  1420. delwin(logwin);
  1421. delwin(statuswin);
  1422. delwin(mainwin);
  1423. endwin();
  1424. refresh();
  1425. #ifdef WIN32
  1426. // Move the cursor to after curses output.
  1427. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  1428. CONSOLE_SCREEN_BUFFER_INFO csbi;
  1429. COORD coord;
  1430. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  1431. coord.X = 0;
  1432. coord.Y = csbi.dwSize.Y - 1;
  1433. SetConsoleCursorPosition(hout, coord);
  1434. }
  1435. #endif
  1436. unlock_curses();
  1437. }
  1438. }
  1439. static void print_summary(void);
  1440. /* This should be the common exit path */
  1441. void kill_work(void)
  1442. {
  1443. struct thr_info *thr;
  1444. int i;
  1445. disable_curses();
  1446. applog(LOG_INFO, "Received kill message");
  1447. applog(LOG_DEBUG, "Killing off watchpool thread");
  1448. /* Kill the watchpool thread */
  1449. thr = &thr_info[watchpool_thr_id];
  1450. thr_info_cancel(thr);
  1451. applog(LOG_DEBUG, "Killing off watchdog thread");
  1452. /* Kill the watchdog thread */
  1453. thr = &thr_info[watchdog_thr_id];
  1454. thr_info_cancel(thr);
  1455. applog(LOG_DEBUG, "Killing off mining threads");
  1456. /* Stop the mining threads*/
  1457. for (i = 0; i < mining_threads; i++) {
  1458. thr = &thr_info[i];
  1459. thr_info_cancel(thr);
  1460. }
  1461. applog(LOG_DEBUG, "Killing off stage thread");
  1462. /* Stop the others */
  1463. thr = &thr_info[stage_thr_id];
  1464. thr_info_cancel(thr);
  1465. applog(LOG_DEBUG, "Killing off longpoll thread");
  1466. thr = &thr_info[longpoll_thr_id];
  1467. if (have_longpoll)
  1468. thr_info_cancel(thr);
  1469. applog(LOG_DEBUG, "Killing off API thread");
  1470. thr = &thr_info[api_thr_id];
  1471. thr_info_cancel(thr);
  1472. quit(0, "Shutdown signal received.");
  1473. }
  1474. void quit(int status, const char *format, ...);
  1475. static void sighandler(int __maybe_unused sig)
  1476. {
  1477. /* Restore signal handlers so we can still quit if kill_work fails */
  1478. sigaction(SIGTERM, &termhandler, NULL);
  1479. sigaction(SIGINT, &inthandler, NULL);
  1480. kill_work();
  1481. }
  1482. static void *get_work_thread(void *userdata)
  1483. {
  1484. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1485. struct work *ret_work;
  1486. int failures = 0;
  1487. pthread_detach(pthread_self());
  1488. ret_work = make_work();
  1489. if (wc->thr)
  1490. ret_work->thr = wc->thr;
  1491. else
  1492. ret_work->thr = NULL;
  1493. /* obtain new work from bitcoin via JSON-RPC */
  1494. while (!get_upstream_work(ret_work, wc->lagging)) {
  1495. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1496. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  1497. free_work(ret_work);
  1498. kill_work();
  1499. goto out;
  1500. }
  1501. /* pause, then restart work-request loop */
  1502. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  1503. fail_pause);
  1504. sleep(fail_pause);
  1505. fail_pause += opt_fail_pause;
  1506. }
  1507. fail_pause = opt_fail_pause;
  1508. applog(LOG_DEBUG, "Pushing work to requesting thread");
  1509. /* send work to requesting thread */
  1510. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  1511. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  1512. kill_work();
  1513. free_work(ret_work);
  1514. }
  1515. out:
  1516. workio_cmd_free(wc);
  1517. return NULL;
  1518. }
  1519. static bool workio_get_work(struct workio_cmd *wc)
  1520. {
  1521. pthread_t get_thread;
  1522. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  1523. applog(LOG_ERR, "Failed to create get_work_thread");
  1524. return false;
  1525. }
  1526. return true;
  1527. }
  1528. static bool stale_work(struct work *work, bool share)
  1529. {
  1530. struct timeval now;
  1531. gettimeofday(&now, NULL);
  1532. if (share) {
  1533. if ((now.tv_sec - work->tv_staged.tv_sec) >= opt_expiry)
  1534. return true;
  1535. } else if ((now.tv_sec - work->tv_staged.tv_sec) >= opt_scantime)
  1536. return true;
  1537. if (work->work_block != work_block)
  1538. return true;
  1539. if (opt_fail_only && !share && work->pool != current_pool())
  1540. return true;
  1541. return false;
  1542. }
  1543. static void *submit_work_thread(void *userdata)
  1544. {
  1545. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1546. struct work *work = wc->u.work;
  1547. struct pool *pool = work->pool;
  1548. int failures = 0;
  1549. pthread_detach(pthread_self());
  1550. if (stale_work(work, true)) {
  1551. total_stale++;
  1552. pool->stale_shares++;
  1553. if (!opt_submit_stale && !pool->submit_old) {
  1554. applog(LOG_NOTICE, "Stale share detected, discarding");
  1555. goto out;
  1556. }
  1557. if (opt_submit_stale)
  1558. applog(LOG_NOTICE, "Stale share detected, submitting as user requested");
  1559. else if (pool->submit_old)
  1560. applog(LOG_NOTICE, "Stale share detected, submitting as pool requested");
  1561. }
  1562. /* submit solution to bitcoin via JSON-RPC */
  1563. while (!submit_upstream_work(work)) {
  1564. if (!opt_submit_stale && stale_work(work, true)) {
  1565. applog(LOG_NOTICE, "Stale share detected, discarding");
  1566. total_stale++;
  1567. pool->stale_shares++;
  1568. break;
  1569. }
  1570. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1571. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  1572. kill_work();
  1573. break;
  1574. }
  1575. /* pause, then restart work-request loop */
  1576. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  1577. fail_pause);
  1578. sleep(fail_pause);
  1579. fail_pause += opt_fail_pause;
  1580. }
  1581. fail_pause = opt_fail_pause;
  1582. out:
  1583. workio_cmd_free(wc);
  1584. return NULL;
  1585. }
  1586. static bool workio_submit_work(struct workio_cmd *wc)
  1587. {
  1588. pthread_t submit_thread;
  1589. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  1590. applog(LOG_ERR, "Failed to create submit_work_thread");
  1591. return false;
  1592. }
  1593. return true;
  1594. }
  1595. /* Find the pool that currently has the highest priority */
  1596. static struct pool *priority_pool(int choice)
  1597. {
  1598. struct pool *ret = NULL;
  1599. int i;
  1600. for (i = 0; i < total_pools; i++) {
  1601. struct pool *pool = pools[i];
  1602. if (pool->prio == choice) {
  1603. ret = pool;
  1604. break;
  1605. }
  1606. }
  1607. if (unlikely(!ret)) {
  1608. applog(LOG_ERR, "WTF No pool %d found!", choice);
  1609. return pools[choice];
  1610. }
  1611. return ret;
  1612. }
  1613. void switch_pools(struct pool *selected)
  1614. {
  1615. struct pool *pool, *last_pool;
  1616. int i, pool_no;
  1617. mutex_lock(&control_lock);
  1618. last_pool = currentpool;
  1619. pool_no = currentpool->pool_no;
  1620. /* Switch selected to pool number 0 and move the rest down */
  1621. if (selected) {
  1622. if (selected->prio != 0) {
  1623. for (i = 0; i < total_pools; i++) {
  1624. pool = pools[i];
  1625. if (pool->prio < selected->prio)
  1626. pool->prio++;
  1627. }
  1628. selected->prio = 0;
  1629. }
  1630. }
  1631. switch (pool_strategy) {
  1632. /* Both of these set to the master pool */
  1633. case POOL_FAILOVER:
  1634. case POOL_LOADBALANCE:
  1635. for (i = 0; i < total_pools; i++) {
  1636. pool = priority_pool(i);
  1637. if (!pool->idle && pool->enabled) {
  1638. pool_no = pool->pool_no;
  1639. break;
  1640. }
  1641. }
  1642. break;
  1643. /* Both of these simply increment and cycle */
  1644. case POOL_ROUNDROBIN:
  1645. case POOL_ROTATE:
  1646. if (selected) {
  1647. pool_no = selected->pool_no;
  1648. break;
  1649. }
  1650. pool_no++;
  1651. if (pool_no >= total_pools)
  1652. pool_no = 0;
  1653. break;
  1654. default:
  1655. break;
  1656. }
  1657. currentpool = pools[pool_no];
  1658. pool = currentpool;
  1659. mutex_unlock(&control_lock);
  1660. if (pool != last_pool)
  1661. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  1662. /* Reset the queued amount to allow more to be queued for the new pool */
  1663. mutex_lock(&qd_lock);
  1664. total_queued = 0;
  1665. mutex_unlock(&qd_lock);
  1666. }
  1667. static void discard_work(struct work *work)
  1668. {
  1669. if (!work->clone && !work->rolls && !work->mined) {
  1670. if (work->pool)
  1671. work->pool->discarded_work++;
  1672. total_discarded++;
  1673. applog(LOG_DEBUG, "Discarded work");
  1674. } else
  1675. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  1676. free_work(work);
  1677. }
  1678. /* This is overkill, but at least we'll know accurately how much work is
  1679. * queued to prevent ever being left without work */
  1680. static void inc_queued(void)
  1681. {
  1682. mutex_lock(&qd_lock);
  1683. total_queued++;
  1684. mutex_unlock(&qd_lock);
  1685. }
  1686. static void dec_queued(void)
  1687. {
  1688. mutex_lock(&qd_lock);
  1689. if (total_queued > 0)
  1690. total_queued--;
  1691. mutex_unlock(&qd_lock);
  1692. }
  1693. static int requests_queued(void)
  1694. {
  1695. int ret;
  1696. mutex_lock(&qd_lock);
  1697. ret = total_queued;
  1698. mutex_unlock(&qd_lock);
  1699. return ret;
  1700. }
  1701. static int discard_stale(void)
  1702. {
  1703. struct work *work, *tmp;
  1704. int i, stale = 0;
  1705. mutex_lock(stgd_lock);
  1706. HASH_ITER(hh, staged_work, work, tmp) {
  1707. if (stale_work(work, false)) {
  1708. HASH_DEL(staged_work, work);
  1709. if (work->clone)
  1710. --staged_clones;
  1711. discard_work(work);
  1712. stale++;
  1713. }
  1714. }
  1715. mutex_unlock(stgd_lock);
  1716. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  1717. /* Dec queued outside the loop to not have recursive locks */
  1718. for (i = 0; i < stale; i++)
  1719. dec_queued();
  1720. return stale;
  1721. }
  1722. static bool queue_request(struct thr_info *thr, bool needed);
  1723. static void restart_threads(void)
  1724. {
  1725. int i, stale;
  1726. /* Discard staged work that is now stale */
  1727. stale = discard_stale();
  1728. for (i = 0; i < stale; i++)
  1729. queue_request(NULL, true);
  1730. for (i = 0; i < mining_threads; i++)
  1731. work_restart[i].restart = 1;
  1732. }
  1733. static void set_curblock(char *hexstr, unsigned char *hash)
  1734. {
  1735. unsigned char hash_swap[32];
  1736. char *old_hash = NULL;
  1737. struct timeval tv_now;
  1738. /* Don't free current_hash directly to avoid dereferencing it when
  1739. * we might be accessing its data elsewhere */
  1740. if (current_hash)
  1741. old_hash = current_hash;
  1742. strcpy(current_block, hexstr);
  1743. gettimeofday(&tv_now, NULL);
  1744. get_timestamp(blocktime, &tv_now);
  1745. swap256(hash_swap, hash);
  1746. current_hash = bin2hex(hash_swap, 16);
  1747. if (unlikely(!current_hash))
  1748. quit (1, "set_curblock OOM");
  1749. if (old_hash)
  1750. free(old_hash);
  1751. }
  1752. /* Search to see if this string is from a block that has been seen before */
  1753. static bool block_exists(char *hexstr)
  1754. {
  1755. struct block *s;
  1756. rd_lock(&blk_lock);
  1757. HASH_FIND_STR(blocks, hexstr, s);
  1758. rd_unlock(&blk_lock);
  1759. if (s)
  1760. return true;
  1761. return false;
  1762. }
  1763. /* Tests if this work is from a block that has been seen before */
  1764. static inline bool from_existing_block(struct work *work)
  1765. {
  1766. char *hexstr = bin2hex(work->data, 18);
  1767. bool ret;
  1768. if (unlikely(!hexstr)) {
  1769. applog(LOG_ERR, "from_existing_block OOM");
  1770. return true;
  1771. }
  1772. ret = block_exists(hexstr);
  1773. free(hexstr);
  1774. return ret;
  1775. }
  1776. static void test_work_current(struct work *work, bool longpoll)
  1777. {
  1778. char *hexstr;
  1779. hexstr = bin2hex(work->data, 18);
  1780. if (unlikely(!hexstr)) {
  1781. applog(LOG_ERR, "stage_thread OOM");
  1782. return;
  1783. }
  1784. /* Search to see if this block exists yet and if not, consider it a
  1785. * new block and set the current block details to this one */
  1786. if (!block_exists(hexstr)) {
  1787. struct block *s = calloc(sizeof(struct block), 1);
  1788. if (unlikely(!s))
  1789. quit (1, "test_work_current OOM");
  1790. strcpy(s->hash, hexstr);
  1791. wr_lock(&blk_lock);
  1792. HASH_ADD_STR(blocks, hash, s);
  1793. wr_unlock(&blk_lock);
  1794. set_curblock(hexstr, work->data);
  1795. if (unlikely(++new_blocks == 1))
  1796. goto out_free;
  1797. work_block++;
  1798. if (longpoll)
  1799. applog(LOG_NOTICE, "LONGPOLL detected new block on network, waiting on fresh work");
  1800. else if (have_longpoll)
  1801. applog(LOG_NOTICE, "New block detected on network before longpoll, waiting on fresh work");
  1802. else
  1803. applog(LOG_NOTICE, "New block detected on network, waiting on fresh work");
  1804. restart_threads();
  1805. } else if (longpoll) {
  1806. applog(LOG_NOTICE, "LONGPOLL requested work restart, waiting on fresh work");
  1807. work_block++;
  1808. restart_threads();
  1809. }
  1810. out_free:
  1811. free(hexstr);
  1812. }
  1813. static int tv_sort(struct work *worka, struct work *workb)
  1814. {
  1815. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  1816. }
  1817. static bool hash_push(struct work *work)
  1818. {
  1819. bool rc = true;
  1820. mutex_lock(stgd_lock);
  1821. if (likely(!getq->frozen)) {
  1822. HASH_ADD_INT(staged_work, id, work);
  1823. HASH_SORT(staged_work, tv_sort);
  1824. if (work->clone)
  1825. ++staged_clones;
  1826. } else
  1827. rc = false;
  1828. pthread_cond_signal(&getq->cond);
  1829. mutex_unlock(stgd_lock);
  1830. return rc;
  1831. }
  1832. static void *stage_thread(void *userdata)
  1833. {
  1834. struct thr_info *mythr = userdata;
  1835. bool ok = true;
  1836. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1837. while (ok) {
  1838. struct work *work = NULL;
  1839. applog(LOG_DEBUG, "Popping work to stage thread");
  1840. work = tq_pop(mythr->q, NULL);
  1841. if (unlikely(!work)) {
  1842. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  1843. ok = false;
  1844. break;
  1845. }
  1846. work->work_block = work_block;
  1847. test_work_current(work, false);
  1848. applog(LOG_DEBUG, "Pushing work to getwork queue");
  1849. if (unlikely(!hash_push(work))) {
  1850. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  1851. continue;
  1852. }
  1853. }
  1854. tq_freeze(mythr->q);
  1855. return NULL;
  1856. }
  1857. static bool stage_work(struct work *work)
  1858. {
  1859. applog(LOG_DEBUG, "Pushing work to stage thread");
  1860. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work))) {
  1861. applog(LOG_ERR, "Could not tq_push work in stage_work");
  1862. return false;
  1863. }
  1864. return true;
  1865. }
  1866. int curses_int(const char *query)
  1867. {
  1868. int ret;
  1869. char *cvar;
  1870. cvar = curses_input(query);
  1871. ret = atoi(cvar);
  1872. free(cvar);
  1873. return ret;
  1874. }
  1875. static bool input_pool(bool live);
  1876. static int active_pools(void)
  1877. {
  1878. int ret = 0;
  1879. int i;
  1880. for (i = 0; i < total_pools; i++) {
  1881. if ((pools[i])->enabled)
  1882. ret++;
  1883. }
  1884. return ret;
  1885. }
  1886. static void display_pool_summary(struct pool *pool)
  1887. {
  1888. double efficiency = 0.0;
  1889. if (curses_active_locked()) {
  1890. wlog("Pool: %s\n", pool->rpc_url);
  1891. wlog("%s long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  1892. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  1893. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  1894. wlog(" Accepted shares: %d\n", pool->accepted);
  1895. wlog(" Rejected shares: %d\n", pool->rejected);
  1896. if (pool->accepted || pool->rejected)
  1897. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  1898. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  1899. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  1900. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  1901. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  1902. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  1903. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  1904. wrefresh(logwin);
  1905. unlock_curses();
  1906. }
  1907. }
  1908. /* We can't remove the memory used for this struct pool because there may
  1909. * still be work referencing it. We just remove it from the pools list */
  1910. static void remove_pool(struct pool *pool)
  1911. {
  1912. int i, last_pool = total_pools - 1;
  1913. struct pool *other;
  1914. /* Boost priority of any lower prio than this one */
  1915. for (i = 0; i < total_pools; i++) {
  1916. other = pools[i];
  1917. if (other->prio > pool->prio)
  1918. other->prio--;
  1919. }
  1920. if (pool->pool_no < last_pool) {
  1921. /* Swap the last pool for this one */
  1922. (pools[last_pool])->pool_no = pool->pool_no;
  1923. pools[pool->pool_no] = pools[last_pool];
  1924. }
  1925. /* Give it an invalid number */
  1926. pool->pool_no = total_pools;
  1927. total_pools--;
  1928. }
  1929. void write_config(FILE *fcfg)
  1930. {
  1931. int i;
  1932. /* Write pool values */
  1933. fputs("{\n\"pools\" : [", fcfg);
  1934. for(i = 0; i < total_pools; i++) {
  1935. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "", pools[i]->rpc_url);
  1936. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", pools[i]->rpc_user);
  1937. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", pools[i]->rpc_pass);
  1938. }
  1939. fputs("\n],\n\n", fcfg);
  1940. if (nDevs) {
  1941. /* Write GPU device values */
  1942. fputs("\"intensity\" : \"", fcfg);
  1943. for(i = 0; i < nDevs; i++)
  1944. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  1945. #ifdef HAVE_ADL
  1946. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  1947. for(i = 0; i < nDevs; i++)
  1948. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  1949. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  1950. for(i = 0; i < nDevs; i++)
  1951. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  1952. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  1953. for(i = 0; i < nDevs; i++)
  1954. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  1955. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  1956. for(i = 0; i < nDevs; i++)
  1957. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  1958. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  1959. for(i = 0; i < nDevs; i++)
  1960. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  1961. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  1962. for(i = 0; i < nDevs; i++)
  1963. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  1964. fputs("\",\n\"temp-cutoff\" : \"", fcfg);
  1965. for(i = 0; i < nDevs; i++)
  1966. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].cutofftemp);
  1967. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  1968. for(i = 0; i < nDevs; i++)
  1969. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  1970. fputs("\",\n\"temp-target\" : \"", fcfg);
  1971. for(i = 0; i < nDevs; i++)
  1972. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.targettemp);
  1973. #endif
  1974. fputs("\"", fcfg);
  1975. #ifdef WANT_CPUMINE
  1976. fputs(",\n", fcfg);
  1977. #endif
  1978. }
  1979. #ifdef HAVE_ADL
  1980. if (opt_reorder)
  1981. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  1982. #endif
  1983. #ifdef WANT_CPUMINE
  1984. fprintf(fcfg, "\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  1985. #endif
  1986. /* Simple bool and int options */
  1987. struct opt_table *opt;
  1988. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  1989. char *p, *name = strdup(opt->names);
  1990. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  1991. if (p[1] != '-')
  1992. continue;
  1993. if (opt->type & OPT_NOARG &&
  1994. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  1995. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  1996. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  1997. if (opt->type & OPT_HASARG &&
  1998. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  1999. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  2000. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  2001. (void *)opt->cb_arg == (void *)set_int_1_to_10) && opt->desc != opt_hidden)
  2002. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  2003. }
  2004. }
  2005. /* Special case options */
  2006. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  2007. if (pool_strategy == POOL_LOADBALANCE)
  2008. fputs(",\n\"load-balance\" : true", fcfg);
  2009. if (pool_strategy == POOL_ROUNDROBIN)
  2010. fputs(",\n\"round-robin\" : true", fcfg);
  2011. if (pool_strategy == POOL_ROTATE)
  2012. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  2013. #if defined(unix)
  2014. if (opt_stderr_cmd && *opt_stderr_cmd)
  2015. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", opt_stderr_cmd);
  2016. #endif // defined(unix)
  2017. if (opt_kernel && *opt_kernel)
  2018. fprintf(fcfg, ",\n\"kernel\" : \"%s\"", opt_kernel);
  2019. if (opt_kernel_path && *opt_kernel_path) {
  2020. char *kpath = strdup(opt_kernel_path);
  2021. if (kpath[strlen(kpath)-1] == '/')
  2022. kpath[strlen(kpath)-1] = 0;
  2023. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", kpath);
  2024. }
  2025. if (schedstart.enable)
  2026. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  2027. if (schedstop.enable)
  2028. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  2029. if (opt_socks_proxy && *opt_socks_proxy)
  2030. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", opt_socks_proxy);
  2031. for(i = 0; i < nDevs; i++)
  2032. if (!gpus[i].enabled)
  2033. break;
  2034. if (i < nDevs)
  2035. for (i = 0; i < nDevs; i++)
  2036. if (gpus[i].enabled)
  2037. fprintf(fcfg, ",\n\"device\" : \"%d\"", i);
  2038. if (opt_api_allow != NULL)
  2039. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", opt_api_allow);
  2040. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  2041. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", opt_api_description);
  2042. fputs("\n}", fcfg);
  2043. }
  2044. static void display_pools(void)
  2045. {
  2046. struct pool *pool;
  2047. int selected, i;
  2048. char input;
  2049. opt_loginput = true;
  2050. immedok(logwin, true);
  2051. clear_logwin();
  2052. updated:
  2053. for (i = 0; i < total_pools; i++) {
  2054. pool = pools[i];
  2055. if (pool == current_pool())
  2056. wattron(logwin, A_BOLD);
  2057. if (!pool->enabled)
  2058. wattron(logwin, A_DIM);
  2059. wlogprint("%d: %s %s Priority %d: %s User:%s\n",
  2060. pool->pool_no,
  2061. pool->enabled? "Enabled" : "Disabled",
  2062. pool->idle? "Dead" : "Alive",
  2063. pool->prio,
  2064. pool->rpc_url, pool->rpc_user);
  2065. wattroff(logwin, A_BOLD | A_DIM);
  2066. }
  2067. retry:
  2068. wlogprint("\nCurrent pool management strategy: %s\n",
  2069. strategies[pool_strategy]);
  2070. if (pool_strategy == POOL_ROTATE)
  2071. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  2072. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  2073. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  2074. wlogprint("Or press any other key to continue\n");
  2075. input = getch();
  2076. if (!strncasecmp(&input, "a", 1)) {
  2077. input_pool(true);
  2078. goto updated;
  2079. } else if (!strncasecmp(&input, "r", 1)) {
  2080. if (total_pools <= 1) {
  2081. wlogprint("Cannot remove last pool");
  2082. goto retry;
  2083. }
  2084. selected = curses_int("Select pool number");
  2085. if (selected < 0 || selected >= total_pools) {
  2086. wlogprint("Invalid selection\n");
  2087. goto retry;
  2088. }
  2089. pool = pools[selected];
  2090. if (pool == current_pool())
  2091. switch_pools(NULL);
  2092. if (pool == current_pool()) {
  2093. wlogprint("Unable to remove pool due to activity\n");
  2094. goto retry;
  2095. }
  2096. pool->enabled = false;
  2097. remove_pool(pool);
  2098. goto updated;
  2099. } else if (!strncasecmp(&input, "s", 1)) {
  2100. selected = curses_int("Select pool number");
  2101. if (selected < 0 || selected >= total_pools) {
  2102. wlogprint("Invalid selection\n");
  2103. goto retry;
  2104. }
  2105. pool = pools[selected];
  2106. pool->enabled = true;
  2107. switch_pools(pool);
  2108. goto updated;
  2109. } else if (!strncasecmp(&input, "d", 1)) {
  2110. if (active_pools() <= 1) {
  2111. wlogprint("Cannot disable last pool");
  2112. goto retry;
  2113. }
  2114. selected = curses_int("Select pool number");
  2115. if (selected < 0 || selected >= total_pools) {
  2116. wlogprint("Invalid selection\n");
  2117. goto retry;
  2118. }
  2119. pool = pools[selected];
  2120. pool->enabled = false;
  2121. if (pool == current_pool())
  2122. switch_pools(NULL);
  2123. goto updated;
  2124. } else if (!strncasecmp(&input, "e", 1)) {
  2125. selected = curses_int("Select pool number");
  2126. if (selected < 0 || selected >= total_pools) {
  2127. wlogprint("Invalid selection\n");
  2128. goto retry;
  2129. }
  2130. pool = pools[selected];
  2131. pool->enabled = true;
  2132. if (pool->prio < current_pool()->prio)
  2133. switch_pools(pool);
  2134. goto updated;
  2135. } else if (!strncasecmp(&input, "c", 1)) {
  2136. for (i = 0; i <= TOP_STRATEGY; i++)
  2137. wlogprint("%d: %s\n", i, strategies[i]);
  2138. selected = curses_int("Select strategy number type");
  2139. if (selected < 0 || selected > TOP_STRATEGY) {
  2140. wlogprint("Invalid selection\n");
  2141. goto retry;
  2142. }
  2143. if (selected == POOL_ROTATE) {
  2144. opt_rotate_period = curses_int("Select interval in minutes");
  2145. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  2146. opt_rotate_period = 0;
  2147. wlogprint("Invalid selection\n");
  2148. goto retry;
  2149. }
  2150. }
  2151. pool_strategy = selected;
  2152. switch_pools(NULL);
  2153. goto updated;
  2154. } else if (!strncasecmp(&input, "i", 1)) {
  2155. selected = curses_int("Select pool number");
  2156. if (selected < 0 || selected >= total_pools) {
  2157. wlogprint("Invalid selection\n");
  2158. goto retry;
  2159. }
  2160. pool = pools[selected];
  2161. display_pool_summary(pool);
  2162. goto retry;
  2163. } else
  2164. clear_logwin();
  2165. immedok(logwin, false);
  2166. opt_loginput = false;
  2167. }
  2168. static void display_options(void)
  2169. {
  2170. int selected;
  2171. char input;
  2172. opt_loginput = true;
  2173. immedok(logwin, true);
  2174. clear_logwin();
  2175. retry:
  2176. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  2177. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n[R]PC debug:%s\n[L]og interval:%d\n",
  2178. opt_debug ? "on" : "off",
  2179. want_per_device_stats? "on" : "off",
  2180. opt_quiet ? "on" : "off",
  2181. opt_log_output ? "on" : "off",
  2182. opt_protocol ? "on" : "off",
  2183. opt_log_interval);
  2184. wlogprint("Select an option or any other key to return\n");
  2185. input = getch();
  2186. if (!strncasecmp(&input, "q", 1)) {
  2187. opt_quiet ^= true;
  2188. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  2189. goto retry;
  2190. } else if (!strncasecmp(&input, "v", 1)) {
  2191. opt_log_output ^= true;
  2192. if (opt_log_output)
  2193. opt_quiet = false;
  2194. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  2195. goto retry;
  2196. } else if (!strncasecmp(&input, "n", 1)) {
  2197. opt_log_output = false;
  2198. opt_debug = false;
  2199. opt_quiet = false;
  2200. opt_protocol = false;
  2201. want_per_device_stats = false;
  2202. wlogprint("Output mode reset to normal\n");
  2203. goto retry;
  2204. } else if (!strncasecmp(&input, "d", 1)) {
  2205. opt_debug ^= true;
  2206. opt_log_output = opt_debug;
  2207. if (opt_debug)
  2208. opt_quiet = false;
  2209. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  2210. goto retry;
  2211. } else if (!strncasecmp(&input, "p", 1)) {
  2212. want_per_device_stats ^= true;
  2213. opt_log_output = want_per_device_stats;
  2214. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  2215. goto retry;
  2216. } else if (!strncasecmp(&input, "r", 1)) {
  2217. opt_protocol ^= true;
  2218. if (opt_protocol)
  2219. opt_quiet = false;
  2220. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  2221. goto retry;
  2222. } else if (!strncasecmp(&input, "c", 1))
  2223. clear_logwin();
  2224. else if (!strncasecmp(&input, "l", 1)) {
  2225. selected = curses_int("Interval in seconds");
  2226. if (selected < 0 || selected > 9999) {
  2227. wlogprint("Invalid selection\n");
  2228. goto retry;
  2229. }
  2230. opt_log_interval = selected;
  2231. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  2232. goto retry;
  2233. } else if (!strncasecmp(&input, "s", 1)) {
  2234. opt_realquiet = true;
  2235. } else
  2236. clear_logwin();
  2237. immedok(logwin, false);
  2238. opt_loginput = false;
  2239. }
  2240. static void start_longpoll(void);
  2241. static void stop_longpoll(void);
  2242. static void set_options(void)
  2243. {
  2244. int selected;
  2245. char input;
  2246. opt_loginput = true;
  2247. immedok(logwin, true);
  2248. clear_logwin();
  2249. retry:
  2250. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  2251. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n[P]ause: %d\n[W]rite config file\n",
  2252. opt_queue, opt_scantime, opt_expiry, opt_retries, opt_fail_pause);
  2253. wlogprint("Select an option or any other key to return\n");
  2254. input = getch();
  2255. if (!strncasecmp(&input, "q", 1)) {
  2256. selected = curses_int("Extra work items to queue");
  2257. if (selected < 0 || selected > 9999) {
  2258. wlogprint("Invalid selection\n");
  2259. goto retry;
  2260. }
  2261. opt_queue = selected;
  2262. goto retry;
  2263. } else if (!strncasecmp(&input, "l", 1)) {
  2264. want_longpoll ^= true;
  2265. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  2266. if (!want_longpoll) {
  2267. if (have_longpoll)
  2268. stop_longpoll();
  2269. } else
  2270. start_longpoll();
  2271. goto retry;
  2272. } else if (!strncasecmp(&input, "s", 1)) {
  2273. selected = curses_int("Set scantime in seconds");
  2274. if (selected < 0 || selected > 9999) {
  2275. wlogprint("Invalid selection\n");
  2276. goto retry;
  2277. }
  2278. opt_scantime = selected;
  2279. goto retry;
  2280. } else if (!strncasecmp(&input, "e", 1)) {
  2281. selected = curses_int("Set expiry time in seconds");
  2282. if (selected < 0 || selected > 9999) {
  2283. wlogprint("Invalid selection\n");
  2284. goto retry;
  2285. }
  2286. opt_expiry = selected;
  2287. goto retry;
  2288. } else if (!strncasecmp(&input, "r", 1)) {
  2289. selected = curses_int("Retries before failing (-1 infinite)");
  2290. if (selected < -1 || selected > 9999) {
  2291. wlogprint("Invalid selection\n");
  2292. goto retry;
  2293. }
  2294. opt_retries = selected;
  2295. goto retry;
  2296. } else if (!strncasecmp(&input, "p", 1)) {
  2297. selected = curses_int("Seconds to pause before network retries");
  2298. if (selected < 1 || selected > 9999) {
  2299. wlogprint("Invalid selection\n");
  2300. goto retry;
  2301. }
  2302. opt_fail_pause = selected;
  2303. goto retry;
  2304. } else if (!strncasecmp(&input, "w", 1)) {
  2305. FILE *fcfg;
  2306. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  2307. #if defined(unix)
  2308. strcpy(filename, getenv("HOME"));
  2309. if (*filename)
  2310. strcat(filename, "/");
  2311. else
  2312. strcpy(filename, "");
  2313. strcat(filename, ".cgminer/");
  2314. mkdir(filename, 0777);
  2315. #else
  2316. strcpy(filename, "");
  2317. #endif
  2318. strcat(filename, def_conf);
  2319. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  2320. str = curses_input(prompt);
  2321. if (strcmp(str, "-1")) {
  2322. struct stat statbuf;
  2323. strcpy(filename, str);
  2324. if (!stat(filename, &statbuf)) {
  2325. wlogprint("File exists, overwrite?\n");
  2326. input = getch();
  2327. if (strncasecmp(&input, "y", 1))
  2328. goto retry;
  2329. }
  2330. }
  2331. fcfg = fopen(filename, "w");
  2332. if (!fcfg) {
  2333. wlogprint("Cannot open or create file\n");
  2334. goto retry;
  2335. }
  2336. write_config(fcfg);
  2337. fclose(fcfg);
  2338. goto retry;
  2339. } else
  2340. clear_logwin();
  2341. immedok(logwin, false);
  2342. opt_loginput = false;
  2343. }
  2344. static void *input_thread(void __maybe_unused *userdata)
  2345. {
  2346. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2347. if (!curses_active)
  2348. return NULL;
  2349. while (1) {
  2350. char input;
  2351. input = getch();
  2352. if (!strncasecmp(&input, "q", 1)) {
  2353. kill_work();
  2354. return NULL;
  2355. } else if (!strncasecmp(&input, "d", 1))
  2356. display_options();
  2357. else if (!strncasecmp(&input, "p", 1))
  2358. display_pools();
  2359. else if (!strncasecmp(&input, "s", 1))
  2360. set_options();
  2361. else if (have_opencl && !strncasecmp(&input, "g", 1))
  2362. manage_gpu();
  2363. if (opt_realquiet) {
  2364. disable_curses();
  2365. break;
  2366. }
  2367. }
  2368. return NULL;
  2369. }
  2370. /* This thread should not be shut down unless a problem occurs */
  2371. static void *workio_thread(void *userdata)
  2372. {
  2373. struct thr_info *mythr = userdata;
  2374. bool ok = true;
  2375. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2376. while (ok) {
  2377. struct workio_cmd *wc;
  2378. applog(LOG_DEBUG, "Popping work to work thread");
  2379. /* wait for workio_cmd sent to us, on our queue */
  2380. wc = tq_pop(mythr->q, NULL);
  2381. if (unlikely(!wc)) {
  2382. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  2383. ok = false;
  2384. break;
  2385. }
  2386. /* process workio_cmd */
  2387. switch (wc->cmd) {
  2388. case WC_GET_WORK:
  2389. ok = workio_get_work(wc);
  2390. break;
  2391. case WC_SUBMIT_WORK:
  2392. ok = workio_submit_work(wc);
  2393. break;
  2394. default:
  2395. ok = false;
  2396. break;
  2397. }
  2398. }
  2399. tq_freeze(mythr->q);
  2400. return NULL;
  2401. }
  2402. static void *api_thread(void *userdata)
  2403. {
  2404. struct thr_info *mythr = userdata;
  2405. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2406. api();
  2407. PTH(mythr) = 0L;
  2408. return NULL;
  2409. }
  2410. void thread_reportin(struct thr_info *thr)
  2411. {
  2412. gettimeofday(&thr->last, NULL);
  2413. thr->cgpu->status = LIFE_WELL;
  2414. thr->getwork = false;
  2415. }
  2416. static inline void thread_reportout(struct thr_info *thr)
  2417. {
  2418. thr->getwork = true;
  2419. }
  2420. static void hashmeter(int thr_id, struct timeval *diff,
  2421. unsigned long hashes_done)
  2422. {
  2423. struct timeval temp_tv_end, total_diff;
  2424. double secs;
  2425. double local_secs;
  2426. double utility, efficiency = 0.0;
  2427. static double local_mhashes_done = 0;
  2428. static double rolling = 0;
  2429. double local_mhashes = (double)hashes_done / 1000000.0;
  2430. bool showlog = false;
  2431. /* Update the last time this thread reported in */
  2432. if (thr_id >= 0)
  2433. gettimeofday(&thr_info[thr_id].last, NULL);
  2434. /* Don't bother calculating anything if we're not displaying it */
  2435. if (opt_realquiet || !opt_log_interval)
  2436. return;
  2437. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  2438. /* So we can call hashmeter from a non worker thread */
  2439. if (thr_id >= 0) {
  2440. struct thr_info *thr = &thr_info[thr_id];
  2441. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  2442. double thread_rolling = 0.0;
  2443. int i;
  2444. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  2445. thr_id, hashes_done, hashes_done / secs);
  2446. /* Rolling average for each thread and each device */
  2447. decay_time(&thr->rolling, local_mhashes / secs);
  2448. for (i = 0; i < mining_threads; i++) {
  2449. struct thr_info *th = &thr_info[i];
  2450. if (th->cgpu == cgpu)
  2451. thread_rolling += th->rolling;
  2452. }
  2453. decay_time(&cgpu->rolling, thread_rolling);
  2454. cgpu->total_mhashes += local_mhashes;
  2455. // If needed, output detailed, per-device stats
  2456. if (want_per_device_stats) {
  2457. struct timeval now;
  2458. struct timeval elapsed;
  2459. gettimeofday(&now, NULL);
  2460. timeval_subtract(&elapsed, &now, &thr->cgpu->last_message_tv);
  2461. if (opt_log_interval <= elapsed.tv_sec) {
  2462. struct cgpu_info *cgpu = thr->cgpu;
  2463. char logline[255];
  2464. cgpu->last_message_tv = now;
  2465. get_statline(logline, cgpu);
  2466. if (!curses_active) {
  2467. printf("%s \r", logline);
  2468. fflush(stdout);
  2469. } else
  2470. applog(LOG_INFO, "%s", logline);
  2471. }
  2472. }
  2473. }
  2474. /* Totals are updated by all threads so can race without locking */
  2475. mutex_lock(&hash_lock);
  2476. gettimeofday(&temp_tv_end, NULL);
  2477. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  2478. total_mhashes_done += local_mhashes;
  2479. local_mhashes_done += local_mhashes;
  2480. if (total_diff.tv_sec < opt_log_interval)
  2481. /* Only update the total every opt_log_interval seconds */
  2482. goto out_unlock;
  2483. showlog = true;
  2484. gettimeofday(&total_tv_end, NULL);
  2485. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  2486. decay_time(&rolling, local_mhashes_done / local_secs);
  2487. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  2488. total_secs = (double)total_diff.tv_sec +
  2489. ((double)total_diff.tv_usec / 1000000.0);
  2490. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  2491. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  2492. sprintf(statusline, "%s(%ds):%.1f (avg):%.1f Mh/s | Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  2493. want_per_device_stats ? "ALL " : "",
  2494. opt_log_interval, rolling, total_mhashes_done / total_secs,
  2495. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  2496. local_mhashes_done = 0;
  2497. out_unlock:
  2498. mutex_unlock(&hash_lock);
  2499. if (showlog) {
  2500. if (!curses_active) {
  2501. printf("%s \r", statusline);
  2502. fflush(stdout);
  2503. } else
  2504. applog(LOG_INFO, "%s", statusline);
  2505. }
  2506. }
  2507. static bool pool_active(struct pool *pool, bool pinging)
  2508. {
  2509. bool ret = false;
  2510. json_t *val;
  2511. CURL *curl;
  2512. bool rolltime;
  2513. curl = curl_easy_init();
  2514. if (unlikely(!curl)) {
  2515. applog(LOG_ERR, "CURL initialisation failed");
  2516. return false;
  2517. }
  2518. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  2519. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  2520. true, false, &rolltime, pool, false);
  2521. if (val) {
  2522. struct work *work = make_work();
  2523. bool rc;
  2524. rc = work_decode(json_object_get(val, "result"), work);
  2525. if (rc) {
  2526. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  2527. pool->pool_no, pool->rpc_url);
  2528. work->pool = pool;
  2529. work->rolltime = rolltime;
  2530. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  2531. tq_push(thr_info[stage_thr_id].q, work);
  2532. total_getworks++;
  2533. pool->getwork_requested++;
  2534. inc_queued();
  2535. ret = true;
  2536. gettimeofday(&pool->tv_idle, NULL);
  2537. } else {
  2538. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  2539. pool->pool_no, pool->rpc_url);
  2540. free_work(work);
  2541. }
  2542. json_decref(val);
  2543. } else {
  2544. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  2545. pool->pool_no, pool->rpc_url);
  2546. if (!pinging)
  2547. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  2548. }
  2549. curl_easy_cleanup(curl);
  2550. return ret;
  2551. }
  2552. static void pool_died(struct pool *pool)
  2553. {
  2554. if (!pool_tset(pool, &pool->idle)) {
  2555. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  2556. gettimeofday(&pool->tv_idle, NULL);
  2557. switch_pools(NULL);
  2558. }
  2559. }
  2560. static inline int cp_prio(void)
  2561. {
  2562. int prio;
  2563. mutex_lock(&control_lock);
  2564. prio = currentpool->prio;
  2565. mutex_unlock(&control_lock);
  2566. return prio;
  2567. }
  2568. static void pool_resus(struct pool *pool)
  2569. {
  2570. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  2571. if (pool->prio < cp_prio() && pool_strategy == POOL_FAILOVER)
  2572. switch_pools(NULL);
  2573. }
  2574. static long requested_tv_sec;
  2575. static bool queue_request(struct thr_info *thr, bool needed)
  2576. {
  2577. int rq = requests_queued();
  2578. struct workio_cmd *wc;
  2579. struct timeval now;
  2580. gettimeofday(&now, NULL);
  2581. /* Space out retrieval of extra work according to the number of mining
  2582. * threads */
  2583. if (rq >= mining_threads + staged_clones &&
  2584. (now.tv_sec - requested_tv_sec) < opt_scantime / (mining_threads + 1))
  2585. return true;
  2586. /* fill out work request message */
  2587. wc = calloc(1, sizeof(*wc));
  2588. if (unlikely(!wc)) {
  2589. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  2590. return false;
  2591. }
  2592. wc->cmd = WC_GET_WORK;
  2593. if (thr)
  2594. wc->thr = thr;
  2595. else
  2596. wc->thr = NULL;
  2597. /* If we're queueing work faster than we can stage it, consider the
  2598. * system lagging and allow work to be gathered from another pool if
  2599. * possible */
  2600. if (rq && needed && !requests_staged() && !opt_fail_only)
  2601. wc->lagging = true;
  2602. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  2603. /* send work request to workio thread */
  2604. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2605. applog(LOG_ERR, "Failed to tq_push in queue_request");
  2606. workio_cmd_free(wc);
  2607. return false;
  2608. }
  2609. requested_tv_sec = now.tv_sec;
  2610. inc_queued();
  2611. return true;
  2612. }
  2613. static struct work *hash_pop(const struct timespec *abstime)
  2614. {
  2615. struct work *work = NULL;
  2616. int rc = 0;
  2617. mutex_lock(stgd_lock);
  2618. while (!getq->frozen && !HASH_COUNT(staged_work) && !rc)
  2619. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, abstime);
  2620. if (HASH_COUNT(staged_work)) {
  2621. work = staged_work;
  2622. HASH_DEL(staged_work, work);
  2623. if (work->clone)
  2624. --staged_clones;
  2625. }
  2626. mutex_unlock(stgd_lock);
  2627. return work;
  2628. }
  2629. static inline bool should_roll(struct work *work)
  2630. {
  2631. if (work->pool == current_pool() || pool_strategy == POOL_LOADBALANCE)
  2632. return true;
  2633. return false;
  2634. }
  2635. static inline bool can_roll(struct work *work)
  2636. {
  2637. return (work->pool && !stale_work(work, false) && work->rolltime &&
  2638. work->rolls < 11 && !work->clone);
  2639. }
  2640. static void roll_work(struct work *work)
  2641. {
  2642. uint32_t *work_ntime;
  2643. uint32_t ntime;
  2644. work_ntime = (uint32_t *)(work->data + 68);
  2645. ntime = be32toh(*work_ntime);
  2646. ntime++;
  2647. *work_ntime = htobe32(ntime);
  2648. local_work++;
  2649. work->rolls++;
  2650. work->blk.nonce = 0;
  2651. applog(LOG_DEBUG, "Successfully rolled work");
  2652. /* This is now a different work item so it needs a different ID for the
  2653. * hashtable */
  2654. work->id = total_work++;
  2655. }
  2656. static bool reuse_work(struct work *work)
  2657. {
  2658. if (can_roll(work) && should_roll(work)) {
  2659. roll_work(work);
  2660. return true;
  2661. }
  2662. return false;
  2663. }
  2664. static bool get_work(struct work *work, bool requested, struct thr_info *thr,
  2665. const int thr_id)
  2666. {
  2667. bool newreq = false, ret = false;
  2668. struct timespec abstime = {0, 0};
  2669. struct timeval now;
  2670. struct work *work_heap;
  2671. struct pool *pool;
  2672. int failures = 0;
  2673. /* Tell the watchdog thread this thread is waiting on getwork and
  2674. * should not be restarted */
  2675. thread_reportout(thr);
  2676. retry:
  2677. pool = current_pool();
  2678. if (!requested || requests_queued() < opt_queue) {
  2679. if (unlikely(!queue_request(thr, true))) {
  2680. applog(LOG_WARNING, "Failed to queue_request in get_work");
  2681. goto out;
  2682. }
  2683. newreq = true;
  2684. }
  2685. if (reuse_work(work)) {
  2686. ret = true;
  2687. goto out;
  2688. }
  2689. if (requested && !newreq && !requests_staged() && requests_queued() >= mining_threads &&
  2690. !pool_tset(pool, &pool->lagging)) {
  2691. applog(LOG_WARNING, "Pool %d not providing work fast enough", pool->pool_no);
  2692. pool->getfail_occasions++;
  2693. total_go++;
  2694. }
  2695. newreq = requested = false;
  2696. gettimeofday(&now, NULL);
  2697. abstime.tv_sec = now.tv_sec + 60;
  2698. applog(LOG_DEBUG, "Popping work from get queue to get work");
  2699. /* wait for 1st response, or get cached response */
  2700. work_heap = hash_pop(&abstime);
  2701. if (unlikely(!work_heap)) {
  2702. /* Attempt to switch pools if this one times out */
  2703. pool_died(pool);
  2704. goto retry;
  2705. }
  2706. if (stale_work(work_heap, false)) {
  2707. dec_queued();
  2708. discard_work(work_heap);
  2709. goto retry;
  2710. }
  2711. pool = work_heap->pool;
  2712. /* If we make it here we have succeeded in getting fresh work */
  2713. if (!work_heap->mined) {
  2714. pool_tclear(pool, &pool->lagging);
  2715. if (pool_tclear(pool, &pool->idle))
  2716. pool_resus(pool);
  2717. }
  2718. memcpy(work, work_heap, sizeof(*work));
  2719. /* Hand out a clone if we can roll this work item */
  2720. if (reuse_work(work_heap)) {
  2721. applog(LOG_DEBUG, "Pushing divided work to get queue head");
  2722. stage_work(work_heap);
  2723. work->clone = true;
  2724. } else {
  2725. dec_queued();
  2726. free_work(work_heap);
  2727. }
  2728. ret = true;
  2729. out:
  2730. if (unlikely(ret == false)) {
  2731. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  2732. applog(LOG_ERR, "Failed %d times to get_work");
  2733. return ret;
  2734. }
  2735. applog(LOG_DEBUG, "Retrying after %d seconds", fail_pause);
  2736. sleep(fail_pause);
  2737. fail_pause += opt_fail_pause;
  2738. goto retry;
  2739. }
  2740. fail_pause = opt_fail_pause;
  2741. work->thr_id = thr_id;
  2742. thread_reportin(thr);
  2743. if (ret)
  2744. work->mined = true;
  2745. return ret;
  2746. }
  2747. bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  2748. {
  2749. struct workio_cmd *wc;
  2750. /* fill out work request message */
  2751. wc = calloc(1, sizeof(*wc));
  2752. if (unlikely(!wc)) {
  2753. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  2754. return false;
  2755. }
  2756. wc->u.work = make_work();
  2757. wc->cmd = WC_SUBMIT_WORK;
  2758. wc->thr = thr;
  2759. memcpy(wc->u.work, work_in, sizeof(*work_in));
  2760. applog(LOG_DEBUG, "Pushing submit work to work thread");
  2761. /* send solution to workio thread */
  2762. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2763. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  2764. goto err_out;
  2765. }
  2766. return true;
  2767. err_out:
  2768. workio_cmd_free(wc);
  2769. return false;
  2770. }
  2771. bool hashtest(const struct work *work)
  2772. {
  2773. uint32_t *data32 = (uint32_t *)(work->data);
  2774. unsigned char swap[128];
  2775. uint32_t *swap32 = (uint32_t *)swap;
  2776. unsigned char hash1[32];
  2777. unsigned char hash2[32];
  2778. uint32_t *hash2_32 = (uint32_t *)hash2;
  2779. int i;
  2780. for (i = 0; i < 80 / 4; i++)
  2781. swap32[i] = swab32(data32[i]);
  2782. sha2(swap, 80, hash1, false);
  2783. sha2(hash1, 32, hash2, false);
  2784. for (i = 0; i < 32 / 4; i++)
  2785. hash2_32[i] = swab32(hash2_32[i]);
  2786. memcpy((void*)work->hash, hash2, 32);
  2787. return fulltest(work->hash, work->target);
  2788. }
  2789. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  2790. {
  2791. work->data[64 + 12 + 0] = (nonce >> 0) & 0xff;
  2792. work->data[64 + 12 + 1] = (nonce >> 8) & 0xff;
  2793. work->data[64 + 12 + 2] = (nonce >> 16) & 0xff;
  2794. work->data[64 + 12 + 3] = (nonce >> 24) & 0xff;
  2795. /* Do one last check before attempting to submit the work */
  2796. if (!hashtest(work)) {
  2797. applog(LOG_INFO, "Share below target");
  2798. return true;
  2799. }
  2800. return submit_work_sync(thr, work);
  2801. }
  2802. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  2803. {
  2804. if (wdiff->tv_sec > opt_scantime ||
  2805. work->blk.nonce >= MAXTHREADS - hashes ||
  2806. hashes >= 0xfffffffe ||
  2807. stale_work(work, false))
  2808. return true;
  2809. return false;
  2810. }
  2811. void *miner_thread(void *userdata)
  2812. {
  2813. struct thr_info *mythr = userdata;
  2814. const int thr_id = mythr->id;
  2815. struct cgpu_info *cgpu = mythr->cgpu;
  2816. struct device_api *api = cgpu->api;
  2817. /* Try to cycle approximately 5 times before each log update */
  2818. const unsigned long def_cycle = opt_log_interval / 5 ? : 1;
  2819. long cycle;
  2820. struct timeval tv_start, tv_end, tv_workstart, tv_lastupdate;
  2821. struct timeval diff, sdiff, wdiff;
  2822. uint32_t max_nonce = api->can_limit_work ? api->can_limit_work(mythr) : 0xffffffff;
  2823. uint32_t hashes_done = 0;
  2824. uint32_t hashes;
  2825. struct work *work = make_work();
  2826. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  2827. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  2828. bool requested = false;
  2829. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2830. if (api->thread_init && !api->thread_init(mythr))
  2831. goto out;
  2832. applog(LOG_DEBUG, "Popping ping in miner thread");
  2833. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  2834. sdiff.tv_sec = sdiff.tv_usec = 0;
  2835. gettimeofday(&tv_lastupdate, NULL);
  2836. while (1) {
  2837. work_restart[thr_id].restart = 0;
  2838. if (api->free_work && likely(work->pool))
  2839. api->free_work(mythr, work);
  2840. if (unlikely(!get_work(work, requested, mythr, thr_id))) {
  2841. applog(LOG_ERR, "work retrieval failed, exiting "
  2842. "mining thread %d", thr_id);
  2843. break;
  2844. }
  2845. requested = false;
  2846. cycle = (can_roll(work) && should_roll(work)) ? 1 : def_cycle;
  2847. gettimeofday(&tv_workstart, NULL);
  2848. work->blk.nonce = 0;
  2849. if (api->prepare_work && !api->prepare_work(mythr, work)) {
  2850. applog(LOG_ERR, "work prepare failed, exiting "
  2851. "mining thread %d", thr_id);
  2852. break;
  2853. }
  2854. do {
  2855. gettimeofday(&tv_start, NULL);
  2856. hashes = api->scanhash(mythr, work, work->blk.nonce + max_nonce);
  2857. if (unlikely(work_restart[thr_id].restart)) {
  2858. /* Apart from device_thread 0, we stagger the
  2859. * starting of every next thread to try and get
  2860. * all devices busy before worrying about
  2861. * getting work for their extra threads */
  2862. if (mythr->device_thread) {
  2863. struct timespec rgtp;
  2864. rgtp.tv_sec = 0;
  2865. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  2866. nanosleep(&rgtp, NULL);
  2867. }
  2868. break;
  2869. }
  2870. if (unlikely(!hashes))
  2871. goto out;
  2872. hashes_done += hashes;
  2873. gettimeofday(&tv_end, NULL);
  2874. timeval_subtract(&diff, &tv_end, &tv_start);
  2875. sdiff.tv_sec += diff.tv_sec;
  2876. sdiff.tv_usec += diff.tv_usec;
  2877. if (sdiff.tv_usec > 1000000) {
  2878. ++sdiff.tv_sec;
  2879. sdiff.tv_usec -= 1000000;
  2880. }
  2881. timeval_subtract(&wdiff, &tv_end, &tv_workstart);
  2882. if (!requested) {
  2883. if (wdiff.tv_sec > request_interval || work->blk.nonce > request_nonce) {
  2884. thread_reportout(mythr);
  2885. if (unlikely(!queue_request(mythr, false))) {
  2886. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  2887. goto out;
  2888. }
  2889. thread_reportin(mythr);
  2890. requested = true;
  2891. }
  2892. }
  2893. if (unlikely(sdiff.tv_sec < cycle)) {
  2894. if (likely(!api->can_limit_work || max_nonce == 0xffffffff))
  2895. continue;
  2896. {
  2897. int mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  2898. mult *= cycle;
  2899. if (max_nonce > (0xffffffff * 0x400) / mult)
  2900. max_nonce = 0xffffffff;
  2901. else
  2902. max_nonce = (max_nonce * mult) / 0x400;
  2903. }
  2904. } else if (unlikely(sdiff.tv_sec > cycle) && api->can_limit_work) {
  2905. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  2906. } else if (unlikely(sdiff.tv_usec > 100000) && api->can_limit_work) {
  2907. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  2908. }
  2909. timeval_subtract(&diff, &tv_end, &tv_lastupdate);
  2910. if (diff.tv_sec >= opt_log_interval) {
  2911. hashmeter(thr_id, &diff, hashes_done);
  2912. hashes_done = 0;
  2913. tv_lastupdate = tv_end;
  2914. }
  2915. if (unlikely(mythr->pause || !cgpu->enabled)) {
  2916. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  2917. mythr->rolling = mythr->cgpu->rolling = 0;
  2918. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  2919. thread_reportout(mythr);
  2920. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  2921. thread_reportin(mythr);
  2922. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  2923. }
  2924. sdiff.tv_sec = sdiff.tv_usec = 0;
  2925. } while (!abandon_work(work, &wdiff, hashes));
  2926. }
  2927. out:
  2928. if (api->thread_shutdown)
  2929. api->thread_shutdown(mythr);
  2930. thread_reportin(mythr);
  2931. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  2932. tq_freeze(mythr->q);
  2933. return NULL;
  2934. }
  2935. enum {
  2936. STAT_SLEEP_INTERVAL = 1,
  2937. STAT_CTR_INTERVAL = 10000000,
  2938. FAILURE_INTERVAL = 30,
  2939. };
  2940. /* Stage another work item from the work returned in a longpoll */
  2941. static void convert_to_work(json_t *val, bool rolltime, struct pool *pool)
  2942. {
  2943. struct work *work, *work_clone;
  2944. bool rc;
  2945. work = make_work();
  2946. rc= work_decode(json_object_get(val, "result"), work);
  2947. if (unlikely(!rc)) {
  2948. applog(LOG_ERR, "Could not convert longpoll data to work");
  2949. return;
  2950. }
  2951. work->pool = pool;
  2952. work->rolltime = rolltime;
  2953. /* We'll be checking this work item twice, but we already know it's
  2954. * from a new block so explicitly force the new block detection now
  2955. * rather than waiting for it to hit the stage thread. This also
  2956. * allows testwork to know whether LP discovered the block or not. */
  2957. test_work_current(work, true);
  2958. work_clone = make_work();
  2959. memcpy(work_clone, work, sizeof(struct work));
  2960. while (reuse_work(work)) {
  2961. work_clone->clone = true;
  2962. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  2963. if (unlikely(!stage_work(work_clone)))
  2964. break;
  2965. work_clone = make_work();
  2966. memcpy(work_clone, work, sizeof(struct work));
  2967. }
  2968. free_work(work_clone);
  2969. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  2970. if (unlikely(!stage_work(work)))
  2971. free_work(work);
  2972. else
  2973. applog(LOG_DEBUG, "Converted longpoll data to work");
  2974. }
  2975. /* If we want longpoll, enable it for the chosen default pool, or, if
  2976. * the pool does not support longpoll, find the first one that does
  2977. * and use its longpoll support */
  2978. static struct pool *select_longpoll_pool(void)
  2979. {
  2980. struct pool *cp = current_pool();
  2981. int i;
  2982. if (cp->hdr_path)
  2983. return cp;
  2984. for (i = 0; i < total_pools; i++) {
  2985. struct pool *pool = pools[i];
  2986. if (pool->hdr_path)
  2987. return pool;
  2988. }
  2989. return NULL;
  2990. }
  2991. static void *longpoll_thread(void *userdata)
  2992. {
  2993. char *copy_start, *hdr_path, *lp_url = NULL;
  2994. struct thr_info *mythr = userdata;
  2995. struct timeval start, end;
  2996. bool need_slash = false;
  2997. struct pool *sp, *pool;
  2998. CURL *curl = NULL;
  2999. int failures = 0;
  3000. bool rolltime;
  3001. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3002. pthread_detach(pthread_self());
  3003. curl = curl_easy_init();
  3004. if (unlikely(!curl)) {
  3005. applog(LOG_ERR, "CURL initialisation failed");
  3006. goto out;
  3007. }
  3008. tq_pop(mythr->q, NULL);
  3009. pool = select_longpoll_pool();
  3010. new_longpoll:
  3011. if (!pool) {
  3012. applog(LOG_WARNING, "No long-poll found on any pool server");
  3013. goto out;
  3014. }
  3015. hdr_path = pool->hdr_path;
  3016. /* full URL */
  3017. if (strstr(hdr_path, "://")) {
  3018. lp_url = hdr_path;
  3019. hdr_path = NULL;
  3020. } else {
  3021. /* absolute path, on current server */
  3022. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  3023. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  3024. need_slash = true;
  3025. lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  3026. if (!lp_url)
  3027. goto out;
  3028. sprintf(lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  3029. }
  3030. have_longpoll = true;
  3031. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  3032. while (1) {
  3033. json_t *val, *soval;
  3034. gettimeofday(&start, NULL);
  3035. val = json_rpc_call(curl, lp_url, pool->rpc_userpass, rpc_req,
  3036. false, true, &rolltime, pool, false);
  3037. if (likely(val)) {
  3038. soval = json_object_get(json_object_get(val, "result"), "submitold");
  3039. if (soval)
  3040. pool->submit_old = json_is_true(soval);
  3041. else
  3042. pool->submit_old = false;
  3043. convert_to_work(val, rolltime, pool);
  3044. failures = 0;
  3045. json_decref(val);
  3046. } else {
  3047. /* Some pools regularly drop the longpoll request so
  3048. * only see this as longpoll failure if it happens
  3049. * immediately and just restart it the rest of the
  3050. * time. */
  3051. gettimeofday(&end, NULL);
  3052. if (end.tv_sec - start.tv_sec > 30)
  3053. continue;
  3054. if (opt_retries == -1 || failures++ < opt_retries) {
  3055. applog(LOG_WARNING,
  3056. "longpoll failed for %s, sleeping for 30s", lp_url);
  3057. sleep(30);
  3058. } else {
  3059. applog(LOG_ERR,
  3060. "longpoll failed for %s, ending thread", lp_url);
  3061. goto out;
  3062. }
  3063. }
  3064. sp = select_longpoll_pool();
  3065. if (sp != pool) {
  3066. if (likely(lp_url))
  3067. free(lp_url);
  3068. pool = sp;
  3069. goto new_longpoll;
  3070. }
  3071. }
  3072. out:
  3073. if (curl)
  3074. curl_easy_cleanup(curl);
  3075. tq_freeze(mythr->q);
  3076. return NULL;
  3077. }
  3078. static void stop_longpoll(void)
  3079. {
  3080. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3081. thr_info_cancel(thr);
  3082. have_longpoll = false;
  3083. tq_freeze(thr->q);
  3084. }
  3085. static void start_longpoll(void)
  3086. {
  3087. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3088. tq_thaw(thr->q);
  3089. if (unlikely(thr_info_create(thr, NULL, longpoll_thread, thr)))
  3090. quit(1, "longpoll thread create failed");
  3091. applog(LOG_DEBUG, "Pushing ping to longpoll thread");
  3092. tq_push(thr_info[longpoll_thr_id].q, &ping);
  3093. }
  3094. void reinit_device(struct cgpu_info *cgpu)
  3095. {
  3096. if (cgpu->api->reinit_device)
  3097. cgpu->api->reinit_device(cgpu);
  3098. }
  3099. static struct timeval rotate_tv;
  3100. static void *watchpool_thread(void __maybe_unused *userdata)
  3101. {
  3102. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3103. while (42) {
  3104. struct timeval now;
  3105. int i;
  3106. gettimeofday(&now, NULL);
  3107. for (i = 0; i < total_pools; i++) {
  3108. struct pool *pool = pools[i];
  3109. if (!pool->enabled)
  3110. continue;
  3111. /* Test pool is idle once every minute */
  3112. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  3113. gettimeofday(&pool->tv_idle, NULL);
  3114. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  3115. pool_resus(pool);
  3116. }
  3117. }
  3118. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  3119. gettimeofday(&rotate_tv, NULL);
  3120. switch_pools(NULL);
  3121. }
  3122. sleep(10);
  3123. }
  3124. return NULL;
  3125. }
  3126. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  3127. * the screen at regular intervals, and restarts threads if they appear to have
  3128. * died. */
  3129. static void *watchdog_thread(void __maybe_unused *userdata)
  3130. {
  3131. const unsigned int interval = 3;
  3132. struct timeval zero_tv;
  3133. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3134. memset(&zero_tv, 0, sizeof(struct timeval));
  3135. gettimeofday(&rotate_tv, NULL);
  3136. while (1) {
  3137. int i;
  3138. struct timeval now;
  3139. sleep(interval);
  3140. if (requests_queued() < opt_queue)
  3141. queue_request(NULL, false);
  3142. hashmeter(-1, &zero_tv, 0);
  3143. if (curses_active_locked()) {
  3144. change_logwinsize();
  3145. curses_print_status();
  3146. for (i = 0; i < mining_threads; i++)
  3147. curses_print_devstatus(i);
  3148. clearok(statuswin, true);
  3149. doupdate();
  3150. unlock_curses();
  3151. }
  3152. gettimeofday(&now, NULL);
  3153. if (!sched_paused && !should_run()) {
  3154. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  3155. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3156. if (!schedstart.enable) {
  3157. quit(0, "Terminating execution as planned");
  3158. break;
  3159. }
  3160. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  3161. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3162. sched_paused = true;
  3163. for (i = 0; i < mining_threads; i++) {
  3164. struct thr_info *thr;
  3165. thr = &thr_info[i];
  3166. thr->pause = true;
  3167. }
  3168. } else if (sched_paused && should_run()) {
  3169. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  3170. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3171. if (schedstop.enable)
  3172. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  3173. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3174. sched_paused = false;
  3175. for (i = 0; i < mining_threads; i++) {
  3176. struct thr_info *thr;
  3177. thr = &thr_info[i];
  3178. /* Don't touch disabled devices */
  3179. if (!thr->cgpu->enabled)
  3180. continue;
  3181. thr->pause = false;
  3182. tq_push(thr->q, &ping);
  3183. }
  3184. }
  3185. #ifdef HAVE_OPENCL
  3186. for (i = 0; i < total_devices; ++i) {
  3187. struct cgpu_info *cgpu = devices[i];
  3188. struct thr_info *thr = cgpu->thread;
  3189. bool *enable;
  3190. int gpu;
  3191. if (cgpu->api != &opencl_api)
  3192. continue;
  3193. /* Use only one thread per device to determine if the GPU is healthy */
  3194. if (i >= nDevs)
  3195. break;
  3196. gpu = thr->cgpu->device_id;
  3197. enable = &cgpu->enabled;
  3198. #ifdef HAVE_ADL
  3199. if (adl_active && gpus[gpu].has_adl)
  3200. gpu_autotune(gpu, enable);
  3201. if (opt_debug && gpus[gpu].has_adl) {
  3202. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  3203. float temp = 0, vddc = 0;
  3204. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  3205. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  3206. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  3207. }
  3208. #endif
  3209. /* Thread is waiting on getwork or disabled */
  3210. if (thr->getwork || !*enable)
  3211. continue;
  3212. if (gpus[gpu].status != LIFE_WELL && now.tv_sec - thr->last.tv_sec < 60) {
  3213. applog(LOG_ERR, "Device %d recovered, GPU %d declared WELL!", i, gpu);
  3214. gpus[gpu].status = LIFE_WELL;
  3215. } else if (now.tv_sec - thr->last.tv_sec > 60 && gpus[gpu].status == LIFE_WELL) {
  3216. thr->rolling = thr->cgpu->rolling = 0;
  3217. gpus[gpu].status = LIFE_SICK;
  3218. applog(LOG_ERR, "Device %d idle for more than 60 seconds, GPU %d declared SICK!", i, gpu);
  3219. gettimeofday(&thr->sick, NULL);
  3220. #ifdef HAVE_ADL
  3221. if (adl_active && gpus[gpu].has_adl && gpu_activity(gpu) > 50) {
  3222. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  3223. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  3224. } else
  3225. #endif
  3226. if (opt_restart) {
  3227. applog(LOG_ERR, "Attempting to restart GPU");
  3228. reinit_device(thr->cgpu);
  3229. }
  3230. } else if (now.tv_sec - thr->last.tv_sec > 600 && gpus[i].status == LIFE_SICK) {
  3231. gpus[gpu].status = LIFE_DEAD;
  3232. applog(LOG_ERR, "Device %d not responding for more than 10 minutes, GPU %d declared DEAD!", i, gpu);
  3233. gettimeofday(&thr->sick, NULL);
  3234. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  3235. (gpus[i].status == LIFE_SICK || gpus[i].status == LIFE_DEAD)) {
  3236. /* Attempt to restart a GPU that's sick or dead once every minute */
  3237. gettimeofday(&thr->sick, NULL);
  3238. #ifdef HAVE_ADL
  3239. if (adl_active && gpus[gpu].has_adl && gpu_activity(gpu) > 50) {
  3240. /* Again do not attempt to restart a device that may have hard hung */
  3241. } else
  3242. #endif
  3243. if (opt_restart)
  3244. reinit_device(thr->cgpu);
  3245. }
  3246. }
  3247. #endif
  3248. }
  3249. return NULL;
  3250. }
  3251. static void log_print_status(struct cgpu_info *cgpu)
  3252. {
  3253. char logline[255];
  3254. get_statline(logline, cgpu);
  3255. applog(LOG_WARNING, "%s", logline);
  3256. }
  3257. static void print_summary(void)
  3258. {
  3259. struct timeval diff;
  3260. int hours, mins, secs, i;
  3261. double utility, efficiency = 0.0;
  3262. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  3263. hours = diff.tv_sec / 3600;
  3264. mins = (diff.tv_sec % 3600) / 60;
  3265. secs = diff.tv_sec % 60;
  3266. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  3267. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  3268. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  3269. applog(LOG_WARNING, "Started at %s", datestamp);
  3270. if (total_pools == 1)
  3271. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  3272. #ifdef WANT_CPUMINE
  3273. if (opt_n_threads)
  3274. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  3275. #endif
  3276. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  3277. if (total_secs)
  3278. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  3279. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  3280. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  3281. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  3282. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  3283. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  3284. if (total_accepted || total_rejected)
  3285. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  3286. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  3287. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  3288. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  3289. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  3290. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  3291. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  3292. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  3293. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  3294. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  3295. if (total_pools > 1) {
  3296. for (i = 0; i < total_pools; i++) {
  3297. struct pool *pool = pools[i];
  3298. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  3299. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  3300. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  3301. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  3302. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  3303. if (pool->accepted || pool->rejected)
  3304. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3305. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3306. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  3307. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  3308. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  3309. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  3310. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  3311. }
  3312. }
  3313. applog(LOG_WARNING, "Summary of per device statistics:\n");
  3314. for (i = 0; i < total_devices; ++i) {
  3315. if (devices[i]->enabled)
  3316. log_print_status(devices[i]);
  3317. }
  3318. if (opt_shares)
  3319. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  3320. fflush(stdout);
  3321. fflush(stderr);
  3322. if (opt_shares > total_accepted)
  3323. quit(1, "Did not successfully mine as many shares as were requested.");
  3324. }
  3325. static void clean_up(void)
  3326. {
  3327. gettimeofday(&total_tv_end, NULL);
  3328. disable_curses();
  3329. if (!opt_realquiet && successful_connect)
  3330. print_summary();
  3331. #ifdef HAVE_OPENCL
  3332. clear_adl(nDevs);
  3333. #endif
  3334. if (opt_n_threads)
  3335. free(cpus);
  3336. curl_global_cleanup();
  3337. }
  3338. void quit(int status, const char *format, ...)
  3339. {
  3340. va_list ap;
  3341. clean_up();
  3342. if (format) {
  3343. va_start(ap, format);
  3344. vfprintf(stderr, format, ap);
  3345. va_end(ap);
  3346. }
  3347. fprintf(stderr, "\n");
  3348. fflush(stderr);
  3349. exit(status);
  3350. }
  3351. char *curses_input(const char *query)
  3352. {
  3353. char *input;
  3354. echo();
  3355. input = malloc(255);
  3356. if (!input)
  3357. quit(1, "Failed to malloc input");
  3358. leaveok(logwin, false);
  3359. wlogprint("%s:\n", query);
  3360. wgetnstr(logwin, input, 255);
  3361. if (!strlen(input))
  3362. strcpy(input, "-1");
  3363. leaveok(logwin, true);
  3364. noecho();
  3365. return input;
  3366. }
  3367. static bool input_pool(bool live)
  3368. {
  3369. char *url = NULL, *user = NULL, *pass = NULL;
  3370. struct pool *pool = NULL;
  3371. bool ret = false;
  3372. immedok(logwin, true);
  3373. if (total_pools == MAX_POOLS) {
  3374. wlogprint("Reached maximum number of pools.\n");
  3375. goto out;
  3376. }
  3377. wlogprint("Input server details.\n");
  3378. url = curses_input("URL");
  3379. if (!url)
  3380. goto out;
  3381. if (strncmp(url, "http://", 7) &&
  3382. strncmp(url, "https://", 8)) {
  3383. char *httpinput;
  3384. httpinput = malloc(255);
  3385. if (!httpinput)
  3386. quit(1, "Failed to malloc httpinput");
  3387. strcpy(httpinput, "http://");
  3388. strncat(httpinput, url, 248);
  3389. free(url);
  3390. url = httpinput;
  3391. }
  3392. user = curses_input("Username");
  3393. if (!user)
  3394. goto out;
  3395. pass = curses_input("Password");
  3396. if (!pass)
  3397. goto out;
  3398. pool = calloc(sizeof(struct pool), 1);
  3399. if (!pool)
  3400. quit(1, "Failed to realloc pools in input_pool");
  3401. pool->pool_no = total_pools;
  3402. pool->prio = total_pools;
  3403. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  3404. quit (1, "Failed to pthread_mutex_init in input_pool");
  3405. pool->rpc_url = url;
  3406. pool->rpc_user = user;
  3407. pool->rpc_pass = pass;
  3408. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3409. if (!pool->rpc_userpass)
  3410. quit(1, "Failed to malloc userpass");
  3411. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3412. pool->tv_idle.tv_sec = ~0UL;
  3413. /* Test the pool is not idle if we're live running, otherwise
  3414. * it will be tested separately */
  3415. ret = true;
  3416. pool->enabled = true;
  3417. if (live && !pool_active(pool, false))
  3418. pool->idle = true;
  3419. pools[total_pools++] = pool;
  3420. out:
  3421. immedok(logwin, false);
  3422. if (!ret) {
  3423. if (url)
  3424. free(url);
  3425. if (user)
  3426. free(user);
  3427. if (pass)
  3428. free(pass);
  3429. if (pool)
  3430. free(pool);
  3431. }
  3432. return ret;
  3433. }
  3434. #if defined(unix)
  3435. static void fork_monitor()
  3436. {
  3437. // Make a pipe: [readFD, writeFD]
  3438. int pfd[2];
  3439. int r = pipe(pfd);
  3440. if (r<0) {
  3441. perror("pipe - failed to create pipe for --monitor");
  3442. exit(1);
  3443. }
  3444. // Make stderr write end of pipe
  3445. fflush(stderr);
  3446. r = dup2(pfd[1], 2);
  3447. if (r<0) {
  3448. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  3449. exit(1);
  3450. }
  3451. r = close(pfd[1]);
  3452. if (r<0) {
  3453. perror("close - failed to close write end of pipe for --monitor");
  3454. exit(1);
  3455. }
  3456. // Don't allow a dying monitor to kill the main process
  3457. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  3458. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  3459. if (SIG_ERR==sr0 || SIG_ERR==sr1) {
  3460. perror("signal - failed to edit signal mask for --monitor");
  3461. exit(1);
  3462. }
  3463. // Fork a child process
  3464. r = fork();
  3465. if (r<0) {
  3466. perror("fork - failed to fork child process for --monitor");
  3467. exit(1);
  3468. }
  3469. // Child: launch monitor command
  3470. if (0==r) {
  3471. // Make stdin read end of pipe
  3472. r = dup2(pfd[0], 0);
  3473. if (r<0) {
  3474. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  3475. exit(1);
  3476. }
  3477. close(pfd[0]);
  3478. if (r<0) {
  3479. perror("close - in child, failed to close read end of pipe for --monitor");
  3480. exit(1);
  3481. }
  3482. // Launch user specified command
  3483. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  3484. perror("execl - in child failed to exec user specified command for --monitor");
  3485. exit(1);
  3486. }
  3487. // Parent: clean up unused fds and bail
  3488. r = close(pfd[0]);
  3489. if (r<0) {
  3490. perror("close - failed to close read end of pipe for --monitor");
  3491. exit(1);
  3492. }
  3493. }
  3494. #endif // defined(unix)
  3495. void enable_curses(void) {
  3496. int x,y;
  3497. lock_curses();
  3498. if (curses_active) {
  3499. unlock_curses();
  3500. return;
  3501. }
  3502. mainwin = initscr();
  3503. getmaxyx(mainwin, y, x);
  3504. statuswin = newwin(logstart, x, 0, 0);
  3505. leaveok(statuswin, true);
  3506. logwin = newwin(y - logcursor, 0, logcursor, 0);
  3507. idlok(logwin, true);
  3508. scrollok(logwin, true);
  3509. leaveok(logwin, true);
  3510. cbreak();
  3511. noecho();
  3512. curses_active = true;
  3513. unlock_curses();
  3514. }
  3515. /* TODO: fix need a dummy CPU device_api even if no support for CPU mining */
  3516. #ifndef WANT_CPUMINE
  3517. struct device_api cpu_api;
  3518. struct device_api cpu_api = {
  3519. .name = "CPU",
  3520. };
  3521. #endif
  3522. #ifdef USE_BITFORCE
  3523. extern struct device_api bitforce_api;
  3524. #endif
  3525. static int cgminer_id_count = 0;
  3526. void enable_device(struct cgpu_info *cgpu)
  3527. {
  3528. cgpu->enabled = true;
  3529. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  3530. mining_threads += cgpu->threads;
  3531. #ifdef HAVE_OPENCL
  3532. if (cgpu->api == &opencl_api) {
  3533. gpu_threads += cgpu->threads;
  3534. }
  3535. #endif
  3536. }
  3537. int main (int argc, char *argv[])
  3538. {
  3539. struct block *block, *tmpblock;
  3540. struct work *work, *tmpwork;
  3541. bool pools_active = false;
  3542. struct sigaction handler;
  3543. struct thr_info *thr;
  3544. unsigned int k;
  3545. int i, j;
  3546. /* This dangerous functions tramples random dynamically allocated
  3547. * variables so do it before anything at all */
  3548. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  3549. quit(1, "Failed to curl_global_init");
  3550. mutex_init(&hash_lock);
  3551. mutex_init(&qd_lock);
  3552. mutex_init(&curses_lock);
  3553. mutex_init(&control_lock);
  3554. rwlock_init(&blk_lock);
  3555. rwlock_init(&netacc_lock);
  3556. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  3557. #ifdef WANT_CPUMINE
  3558. init_max_name_len();
  3559. #endif
  3560. handler.sa_handler = &sighandler;
  3561. handler.sa_flags = 0;
  3562. sigemptyset(&handler.sa_mask);
  3563. sigaction(SIGTERM, &handler, &termhandler);
  3564. sigaction(SIGINT, &handler, &inthandler);
  3565. opt_kernel_path = alloca(PATH_MAX);
  3566. strcpy(opt_kernel_path, CGMINER_PREFIX);
  3567. cgminer_path = alloca(PATH_MAX);
  3568. strcpy(cgminer_path, dirname(argv[0]));
  3569. strcat(cgminer_path, "/");
  3570. #ifdef WANT_CPUMINE
  3571. // Hack to make cgminer silent when called recursively on WIN32
  3572. int skip_to_bench = 0;
  3573. #if defined(WIN32)
  3574. char buf[32];
  3575. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  3576. skip_to_bench = 1;
  3577. #endif // defined(WIN32)
  3578. #endif
  3579. block = calloc(sizeof(struct block), 1);
  3580. if (unlikely(!block))
  3581. quit (1, "main OOM");
  3582. for (i = 0; i < 36; i++)
  3583. strcat(block->hash, "0");
  3584. HASH_ADD_STR(blocks, hash, block);
  3585. strcpy(current_block, block->hash);
  3586. INIT_LIST_HEAD(&scan_devices);
  3587. memset(gpus, 0, sizeof(gpus));
  3588. for (i = 0; i < MAX_GPUDEVICES; i++)
  3589. gpus[i].dynamic = true;
  3590. memset(devices, 0, sizeof(devices));
  3591. /* parse command line */
  3592. opt_register_table(opt_config_table,
  3593. "Options for both config file and command line");
  3594. opt_register_table(opt_cmdline_table,
  3595. "Options for command line only");
  3596. if (!config_loaded)
  3597. load_default_config();
  3598. opt_parse(&argc, argv, applog_and_exit);
  3599. if (argc != 1)
  3600. quit(1, "Unexpected extra commandline arguments");
  3601. applog(LOG_WARNING, "Started %s", packagename);
  3602. strcat(opt_kernel_path, "/");
  3603. if (want_per_device_stats)
  3604. opt_log_output = true;
  3605. #ifdef WANT_CPUMINE
  3606. if (0<=opt_bench_algo) {
  3607. double rate = bench_algo_stage3(opt_bench_algo);
  3608. if (!skip_to_bench) {
  3609. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  3610. } else {
  3611. // Write result to shared memory for parent
  3612. #if defined(WIN32)
  3613. char unique_name[64];
  3614. if (GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  3615. HANDLE map_handle = CreateFileMapping(
  3616. INVALID_HANDLE_VALUE, // use paging file
  3617. NULL, // default security attributes
  3618. PAGE_READWRITE, // read/write access
  3619. 0, // size: high 32-bits
  3620. 4096, // size: low 32-bits
  3621. unique_name // name of map object
  3622. );
  3623. if (NULL!=map_handle) {
  3624. void *shared_mem = MapViewOfFile(
  3625. map_handle, // object to map view of
  3626. FILE_MAP_WRITE, // read/write access
  3627. 0, // high offset: map from
  3628. 0, // low offset: beginning
  3629. 0 // default: map entire file
  3630. );
  3631. if (NULL!=shared_mem)
  3632. CopyMemory(shared_mem, &rate, sizeof(rate));
  3633. (void)UnmapViewOfFile(shared_mem);
  3634. }
  3635. (void)CloseHandle(map_handle);
  3636. }
  3637. #endif
  3638. }
  3639. exit(0);
  3640. }
  3641. #endif
  3642. #ifdef HAVE_OPENCL
  3643. if (!opt_nogpu)
  3644. opencl_api.api_detect();
  3645. #endif
  3646. #ifdef USE_BITFORCE
  3647. bitforce_api.api_detect();
  3648. #endif
  3649. #ifdef WANT_CPUMINE
  3650. cpu_api.api_detect();
  3651. #endif
  3652. if (devices_enabled == -1) {
  3653. applog(LOG_ERR, "Devices detected:");
  3654. for (i = 0; i < total_devices; ++i) {
  3655. applog(LOG_ERR, " %2d. %s%d", i, devices[i]->api->name, devices[i]->device_id);
  3656. }
  3657. quit(0, "%d devices listed", total_devices);
  3658. }
  3659. mining_threads = 0;
  3660. gpu_threads = 0;
  3661. if (devices_enabled) {
  3662. for (i = 0; i < (int)(sizeof(devices_enabled) * 8) - 1; ++i) {
  3663. if (devices_enabled & (1 << i)) {
  3664. if (i >= total_devices)
  3665. quit (1, "Command line options set a device that doesn't exist");
  3666. enable_device(devices[i]);
  3667. } else if (i < total_devices) {
  3668. if (opt_removedisabled) {
  3669. if (devices[i]->api == &cpu_api)
  3670. --opt_n_threads;
  3671. } else {
  3672. enable_device(devices[i]);
  3673. }
  3674. devices[i]->enabled = false;
  3675. }
  3676. }
  3677. total_devices = cgminer_id_count;
  3678. } else {
  3679. for (i = 0; i < total_devices; ++i)
  3680. enable_device(devices[i]);
  3681. }
  3682. if (!total_devices)
  3683. quit(1, "All devices disabled, cannot mine!");
  3684. load_temp_cutoffs();
  3685. devcursor = 8;
  3686. logstart = devcursor + total_devices + 1;
  3687. logcursor = logstart + 1;
  3688. if (opt_realquiet)
  3689. use_curses = false;
  3690. if (!total_pools) {
  3691. if (use_curses)
  3692. enable_curses();
  3693. applog(LOG_WARNING, "Need to specify at least one pool server.");
  3694. if (!use_curses || (use_curses && !input_pool(false)))
  3695. quit(1, "Pool setup failed");
  3696. }
  3697. for (i = 0; i < total_pools; i++) {
  3698. struct pool *pool = pools[i];
  3699. if (!pool->rpc_userpass) {
  3700. if (!pool->rpc_user || !pool->rpc_pass)
  3701. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  3702. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3703. if (!pool->rpc_userpass)
  3704. quit(1, "Failed to malloc userpass");
  3705. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3706. } else {
  3707. pool->rpc_user = malloc(strlen(pool->rpc_userpass) + 1);
  3708. if (!pool->rpc_user)
  3709. quit(1, "Failed to malloc user");
  3710. strcpy(pool->rpc_user, pool->rpc_userpass);
  3711. pool->rpc_user = strtok(pool->rpc_user, ":");
  3712. if (!pool->rpc_user)
  3713. quit(1, "Failed to find colon delimiter in userpass");
  3714. }
  3715. }
  3716. /* Set the currentpool to pool 0 */
  3717. currentpool = pools[0];
  3718. #ifdef HAVE_SYSLOG_H
  3719. if (use_syslog)
  3720. openlog(PACKAGE, LOG_PID, LOG_USER);
  3721. #endif
  3722. #if defined(unix)
  3723. if (opt_stderr_cmd)
  3724. fork_monitor();
  3725. #endif // defined(unix)
  3726. total_threads = mining_threads + 8;
  3727. work_restart = calloc(total_threads, sizeof(*work_restart));
  3728. if (!work_restart)
  3729. quit(1, "Failed to calloc work_restart");
  3730. thr_info = calloc(total_threads, sizeof(*thr));
  3731. if (!thr_info)
  3732. quit(1, "Failed to calloc thr_info");
  3733. /* init workio thread info */
  3734. work_thr_id = mining_threads;
  3735. thr = &thr_info[work_thr_id];
  3736. thr->id = work_thr_id;
  3737. thr->q = tq_new();
  3738. if (!thr->q)
  3739. quit(1, "Failed to tq_new");
  3740. /* start work I/O thread */
  3741. if (thr_info_create(thr, NULL, workio_thread, thr))
  3742. quit(1, "workio thread create failed");
  3743. /* init longpoll thread info */
  3744. longpoll_thr_id = mining_threads + 1;
  3745. thr = &thr_info[longpoll_thr_id];
  3746. thr->id = longpoll_thr_id;
  3747. thr->q = tq_new();
  3748. if (!thr->q)
  3749. quit(1, "Failed to tq_new");
  3750. stage_thr_id = mining_threads + 2;
  3751. thr = &thr_info[stage_thr_id];
  3752. thr->q = tq_new();
  3753. if (!thr->q)
  3754. quit(1, "Failed to tq_new");
  3755. /* start stage thread */
  3756. if (thr_info_create(thr, NULL, stage_thread, thr))
  3757. quit(1, "stage thread create failed");
  3758. pthread_detach(thr->pth);
  3759. /* Create a unique get work queue */
  3760. getq = tq_new();
  3761. if (!getq)
  3762. quit(1, "Failed to create getq");
  3763. /* We use the getq mutex as the staged lock */
  3764. stgd_lock = &getq->mutex;
  3765. for (i = 0; i < total_pools; i++) {
  3766. struct pool *pool = pools[i];
  3767. pool->enabled = true;
  3768. pool->idle = true;
  3769. }
  3770. applog(LOG_NOTICE, "Probing for an alive pool");
  3771. do {
  3772. /* Look for at least one active pool before starting */
  3773. for (i = 0; i < total_pools; i++) {
  3774. struct pool *pool = pools[i];
  3775. if (pool_active(pool, false)) {
  3776. if (!currentpool)
  3777. currentpool = pool;
  3778. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  3779. pools_active = true;
  3780. break;
  3781. } else {
  3782. if (pool == currentpool)
  3783. currentpool = NULL;
  3784. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  3785. }
  3786. }
  3787. if (!pools_active) {
  3788. if (use_curses)
  3789. enable_curses();
  3790. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  3791. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  3792. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  3793. for (i = 0; i < total_pools; i++) {
  3794. struct pool *pool;
  3795. pool = pools[i];
  3796. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  3797. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  3798. }
  3799. if (use_curses) {
  3800. halfdelay(150);
  3801. applog(LOG_ERR, "Press any key to exit, or cgminer will try again in 15s.");
  3802. if (getch() != ERR)
  3803. quit(0, "No servers could be used! Exiting.");
  3804. nocbreak();
  3805. } else
  3806. quit(0, "No servers could be used! Exiting.");
  3807. }
  3808. } while (!pools_active);
  3809. if (want_longpoll)
  3810. start_longpoll();
  3811. gettimeofday(&total_tv_start, NULL);
  3812. gettimeofday(&total_tv_end, NULL);
  3813. get_datestamp(datestamp, &total_tv_start);
  3814. #ifndef HAVE_OPENCL
  3815. opt_g_threads = 0;
  3816. #endif
  3817. // Start threads
  3818. k = 0;
  3819. for (i = 0; i < total_devices; ++i) {
  3820. struct cgpu_info *cgpu = devices[i];
  3821. for (j = 0; j < cgpu->threads; ++j, ++k) {
  3822. thr = &thr_info[k];
  3823. thr->id = k;
  3824. thr->cgpu = cgpu;
  3825. thr->device_thread = j;
  3826. thr->q = tq_new();
  3827. if (!thr->q)
  3828. quit(1, "tq_new failed in starting %s%d mining thread (#%d)", cgpu->api->name, cgpu->device_id, i);
  3829. /* Enable threads for devices set not to mine but disable
  3830. * their queue in case we wish to enable them later */
  3831. if (cgpu->enabled) {
  3832. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  3833. tq_push(thr->q, &ping);
  3834. }
  3835. if (cgpu->api->thread_prepare && !cgpu->api->thread_prepare(thr))
  3836. continue;
  3837. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  3838. quit(1, "thread %d create failed", thr->id);
  3839. cgpu->thread = thr;
  3840. }
  3841. }
  3842. #ifdef HAVE_OPENCL
  3843. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  3844. for (i = 0; i < nDevs; i++)
  3845. pause_dynamic_threads(i);
  3846. #endif
  3847. #ifdef WANT_CPUMINE
  3848. applog(LOG_INFO, "%d cpu miner threads started, "
  3849. "using SHA256 '%s' algorithm.",
  3850. opt_n_threads,
  3851. algo_names[opt_algo]);
  3852. #endif
  3853. if (use_curses)
  3854. enable_curses();
  3855. watchpool_thr_id = mining_threads + 3;
  3856. thr = &thr_info[watchpool_thr_id];
  3857. /* start watchpool thread */
  3858. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  3859. quit(1, "watchpool thread create failed");
  3860. pthread_detach(thr->pth);
  3861. watchdog_thr_id = mining_threads + 4;
  3862. thr = &thr_info[watchdog_thr_id];
  3863. /* start watchdog thread */
  3864. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  3865. quit(1, "watchdog thread create failed");
  3866. pthread_detach(thr->pth);
  3867. /* Create reinit gpu thread */
  3868. gpur_thr_id = mining_threads + 5;
  3869. thr = &thr_info[gpur_thr_id];
  3870. thr->q = tq_new();
  3871. if (!thr->q)
  3872. quit(1, "tq_new failed for gpur_thr_id");
  3873. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  3874. quit(1, "reinit_gpu thread create failed");
  3875. /* Create API socket thread */
  3876. api_thr_id = mining_threads + 6;
  3877. thr = &thr_info[api_thr_id];
  3878. if (thr_info_create(thr, NULL, api_thread, thr))
  3879. quit(1, "API thread create failed");
  3880. pthread_detach(thr->pth);
  3881. /* Create curses input thread for keyboard input. Create this last so
  3882. * that we know all threads are created since this can call kill_work
  3883. * to try and shut down ll previous threads. */
  3884. input_thr_id = mining_threads + 7;
  3885. thr = &thr_info[input_thr_id];
  3886. if (thr_info_create(thr, NULL, input_thread, thr))
  3887. quit(1, "input thread create failed");
  3888. pthread_detach(thr->pth);
  3889. /* main loop - simply wait for workio thread to exit. This is not the
  3890. * normal exit path and only occurs should the workio_thread die
  3891. * unexpectedly */
  3892. pthread_join(thr_info[work_thr_id].pth, NULL);
  3893. applog(LOG_INFO, "workio thread dead, exiting.");
  3894. clean_up();
  3895. /* Not really necessary, but let's clean this up too anyway */
  3896. HASH_ITER(hh, staged_work, work, tmpwork) {
  3897. HASH_DEL(staged_work, work);
  3898. free_work(work);
  3899. }
  3900. HASH_ITER(hh, blocks, block, tmpblock) {
  3901. HASH_DEL(blocks, block);
  3902. free(block);
  3903. }
  3904. return 0;
  3905. }