miner.c 151 KB

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