cgminer.c 117 KB

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