cgminer.c 120 KB

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