miner.c 133 KB

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