cgminer.c 116 KB

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