cgminer.c 120 KB

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