cgminer.c 117 KB

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