cgminer.c 126 KB

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