main.c 152 KB

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