cgminer.c 149 KB

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