cgminer.c 123 KB

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