main.c 161 KB

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