miner.c 145 KB

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