cgminer.c 128 KB

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