cgminer.c 158 KB

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