main.c 159 KB

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