cgminer.c 153 KB

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