cgminer.c 121 KB

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