cgminer.c 118 KB

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