main.c 159 KB

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