cgminer.c 120 KB

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