main.c 159 KB

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