cgminer.c 117 KB

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