cgminer.c 153 KB

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