miner.c 149 KB

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