cgminer.c 115 KB

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