miner.c 159 KB

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