cgminer.c 132 KB

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