miner.c 130 KB

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