cgminer.c 160 KB

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