cgminer.c 123 KB

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