cgminer.c 133 KB

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