main.c 159 KB

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