cgminer.c 123 KB

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