cgminer.c 143 KB

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