miner.c 154 KB

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