main.c 159 KB

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