cgminer.c 123 KB

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