miner.c 149 KB

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