cgminer.c 118 KB

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