miner.c 138 KB

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