miner.c 219 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449
  1. /*
  2. * Copyright 2011-2012 Con Kolivas
  3. * Copyright 2011-2013 Luke Dashjr
  4. * Copyright 2012-2013 Andrew Smith
  5. * Copyright 2010 Jeff Garzik
  6. *
  7. * This program is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by the Free
  9. * Software Foundation; either version 3 of the License, or (at your option)
  10. * any later version. See COPYING for more details.
  11. */
  12. #include "config.h"
  13. #ifdef HAVE_CURSES
  14. #include <curses.h>
  15. #endif
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <stdbool.h>
  20. #include <stdint.h>
  21. #include <unistd.h>
  22. #include <sys/time.h>
  23. #include <time.h>
  24. #include <math.h>
  25. #include <stdarg.h>
  26. #include <assert.h>
  27. #include <signal.h>
  28. #include <sys/stat.h>
  29. #include <sys/types.h>
  30. #include <dirent.h>
  31. #ifndef WIN32
  32. #include <sys/resource.h>
  33. #include <sys/socket.h>
  34. #else
  35. #include <winsock2.h>
  36. #endif
  37. #include <ccan/opt/opt.h>
  38. #include <jansson.h>
  39. #include <curl/curl.h>
  40. #include <libgen.h>
  41. #include <sha2.h>
  42. #include <blkmaker.h>
  43. #include <blkmaker_jansson.h>
  44. #include <blktemplate.h>
  45. #include "compat.h"
  46. #include "deviceapi.h"
  47. #include "miner.h"
  48. #include "findnonce.h"
  49. #include "adl.h"
  50. #include "driver-cpu.h"
  51. #include "driver-opencl.h"
  52. #include "bench_block.h"
  53. #include "scrypt.h"
  54. #ifdef USE_X6500
  55. #include "ft232r.h"
  56. #endif
  57. #if defined(unix)
  58. #include <errno.h>
  59. #include <fcntl.h>
  60. #include <sys/wait.h>
  61. #endif
  62. #ifdef USE_SCRYPT
  63. #include "scrypt.h"
  64. #endif
  65. #if defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  66. # define USE_FPGA
  67. # define USE_FPGA_SERIAL
  68. #endif
  69. struct strategies strategies[] = {
  70. { "Failover" },
  71. { "Round Robin" },
  72. { "Rotate" },
  73. { "Load Balance" },
  74. { "Balance" },
  75. };
  76. static char packagename[256];
  77. bool opt_protocol;
  78. static bool opt_benchmark;
  79. static bool want_longpoll = true;
  80. static bool want_gbt = true;
  81. static bool want_getwork = true;
  82. #if BLKMAKER_VERSION > 1
  83. struct _cbscript_t {
  84. char *data;
  85. size_t sz;
  86. };
  87. static struct _cbscript_t opt_coinbase_script;
  88. static uint32_t template_nonce;
  89. #endif
  90. #if BLKMAKER_VERSION < 1
  91. const
  92. #endif
  93. char *opt_coinbase_sig;
  94. char *request_target_str;
  95. float request_pdiff = 1.0;
  96. double request_bdiff;
  97. static bool want_stratum = true;
  98. bool have_longpoll;
  99. int opt_skip_checks;
  100. bool want_per_device_stats;
  101. bool use_syslog;
  102. bool opt_quiet_work_updates;
  103. bool opt_quiet;
  104. bool opt_realquiet;
  105. bool opt_loginput;
  106. bool opt_compact;
  107. bool opt_show_procs;
  108. const int opt_cutofftemp = 95;
  109. int opt_hysteresis = 3;
  110. static int opt_retries = -1;
  111. int opt_fail_pause = 5;
  112. int opt_log_interval = 5;
  113. int opt_queue = 1;
  114. int opt_scantime = 60;
  115. int opt_expiry = 120;
  116. int opt_expiry_lp = 3600;
  117. int opt_bench_algo = -1;
  118. static const bool opt_time = true;
  119. unsigned long long global_hashrate;
  120. #ifdef HAVE_OPENCL
  121. int opt_dynamic_interval = 7;
  122. int nDevs;
  123. int opt_g_threads = 2;
  124. int gpu_threads;
  125. #endif
  126. #ifdef USE_SCRYPT
  127. static char detect_algo = 1;
  128. bool opt_scrypt;
  129. #else
  130. static char detect_algo;
  131. #endif
  132. bool opt_restart = true;
  133. static bool opt_nogpu;
  134. struct list_head scan_devices;
  135. bool opt_force_dev_init;
  136. static signed int devices_enabled;
  137. static bool opt_removedisabled;
  138. int total_devices;
  139. struct cgpu_info **devices;
  140. bool have_opencl;
  141. int opt_n_threads = -1;
  142. int mining_threads;
  143. int num_processors;
  144. #ifdef HAVE_CURSES
  145. bool use_curses = true;
  146. #else
  147. bool use_curses;
  148. #endif
  149. static bool opt_submit_stale = true;
  150. static int opt_shares;
  151. static int opt_submit_threads = 0x40;
  152. bool opt_fail_only;
  153. bool opt_autofan;
  154. bool opt_autoengine;
  155. bool opt_noadl;
  156. char *opt_api_allow = NULL;
  157. char *opt_api_groups;
  158. char *opt_api_description = PACKAGE_STRING;
  159. int opt_api_port = 4028;
  160. bool opt_api_listen;
  161. bool opt_api_network;
  162. bool opt_delaynet;
  163. bool opt_disable_pool;
  164. char *opt_icarus_options = NULL;
  165. char *opt_icarus_timing = NULL;
  166. bool opt_worktime;
  167. char *opt_kernel_path;
  168. char *cgminer_path;
  169. #if defined(USE_BITFORCE)
  170. bool opt_bfl_noncerange;
  171. #endif
  172. #define QUIET (opt_quiet || opt_realquiet)
  173. struct thr_info *thr_info;
  174. static int gwsched_thr_id;
  175. static int stage_thr_id;
  176. static int watchpool_thr_id;
  177. static int watchdog_thr_id;
  178. #ifdef HAVE_CURSES
  179. static int input_thr_id;
  180. #endif
  181. int gpur_thr_id;
  182. static int api_thr_id;
  183. static int total_threads;
  184. pthread_mutex_t hash_lock;
  185. static pthread_mutex_t qd_lock;
  186. static pthread_mutex_t *stgd_lock;
  187. pthread_mutex_t console_lock;
  188. pthread_mutex_t ch_lock;
  189. static pthread_rwlock_t blk_lock;
  190. static pthread_mutex_t sshare_lock;
  191. pthread_rwlock_t netacc_lock;
  192. static pthread_mutex_t lp_lock;
  193. static pthread_cond_t lp_cond;
  194. pthread_cond_t gws_cond;
  195. bool shutting_down;
  196. double total_mhashes_done;
  197. static struct timeval total_tv_start, total_tv_end;
  198. static struct timeval miner_started;
  199. pthread_mutex_t control_lock;
  200. pthread_mutex_t stats_lock;
  201. static pthread_mutex_t submitting_lock;
  202. static int total_submitting;
  203. static struct list_head submit_waiting;
  204. notifier_t submit_waiting_notifier;
  205. int hw_errors;
  206. int total_accepted, total_rejected, total_diff1;
  207. int total_getworks, total_stale, total_discarded;
  208. uint64_t total_bytes_xfer;
  209. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  210. static int staged_rollable;
  211. unsigned int new_blocks;
  212. unsigned int found_blocks;
  213. unsigned int local_work;
  214. unsigned int total_go, total_ro;
  215. struct pool **pools;
  216. static struct pool *currentpool = NULL;
  217. int total_pools, enabled_pools;
  218. enum pool_strategy pool_strategy = POOL_FAILOVER;
  219. int opt_rotate_period;
  220. static int total_urls, total_users, total_passes;
  221. static
  222. #ifndef HAVE_CURSES
  223. const
  224. #endif
  225. bool curses_active;
  226. static char current_block[40];
  227. static char *current_hash;
  228. static uint32_t current_block_id;
  229. char *current_fullhash;
  230. static char datestamp[40];
  231. static char blocktime[32];
  232. struct timeval block_timeval;
  233. static char best_share[8] = "0";
  234. static char block_diff[8];
  235. uint64_t best_diff = 0;
  236. static bool known_blkheight_current;
  237. static uint32_t known_blkheight;
  238. static uint32_t known_blkheight_blkid;
  239. struct block {
  240. char hash[40];
  241. UT_hash_handle hh;
  242. int block_no;
  243. };
  244. static struct block *blocks = NULL;
  245. int swork_id;
  246. /* For creating a hash database of stratum shares submitted that have not had
  247. * a response yet */
  248. struct stratum_share {
  249. UT_hash_handle hh;
  250. bool block;
  251. struct work *work;
  252. int id;
  253. time_t sshare_time;
  254. };
  255. static struct stratum_share *stratum_shares = NULL;
  256. char *opt_socks_proxy = NULL;
  257. static const char def_conf[] = "bfgminer.conf";
  258. static bool config_loaded;
  259. static int include_count;
  260. #define JSON_INCLUDE_CONF "include"
  261. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  262. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  263. #define JSON_MAX_DEPTH 10
  264. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  265. #if defined(unix)
  266. static char *opt_stderr_cmd = NULL;
  267. static int forkpid;
  268. #endif // defined(unix)
  269. struct sigaction termhandler, inthandler;
  270. struct thread_q *getq;
  271. static int total_work;
  272. struct work *staged_work = NULL;
  273. struct schedtime {
  274. bool enable;
  275. struct tm tm;
  276. };
  277. struct schedtime schedstart;
  278. struct schedtime schedstop;
  279. bool sched_paused;
  280. static bool time_before(struct tm *tm1, struct tm *tm2)
  281. {
  282. if (tm1->tm_hour < tm2->tm_hour)
  283. return true;
  284. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  285. return true;
  286. return false;
  287. }
  288. static bool should_run(void)
  289. {
  290. struct timeval tv;
  291. struct tm tm;
  292. bool within_range;
  293. if (!schedstart.enable && !schedstop.enable)
  294. return true;
  295. gettimeofday(&tv, NULL);
  296. localtime_r(&tv.tv_sec, &tm);
  297. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  298. if (time_before(&schedstop.tm, &schedstart.tm))
  299. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  300. else
  301. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  302. if (within_range && !schedstop.enable)
  303. /* This is a once off event with no stop time set */
  304. schedstart.enable = false;
  305. return within_range;
  306. }
  307. void get_datestamp(char *f, struct timeval *tv)
  308. {
  309. struct tm _tm;
  310. struct tm *tm = &_tm;
  311. localtime_r(&tv->tv_sec, tm);
  312. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d]",
  313. tm->tm_year + 1900,
  314. tm->tm_mon + 1,
  315. tm->tm_mday,
  316. tm->tm_hour,
  317. tm->tm_min,
  318. tm->tm_sec);
  319. }
  320. void get_timestamp(char *f, struct timeval *tv)
  321. {
  322. struct tm _tm;
  323. struct tm *tm = &_tm;
  324. localtime_r(&tv->tv_sec, tm);
  325. sprintf(f, "[%02d:%02d:%02d]",
  326. tm->tm_hour,
  327. tm->tm_min,
  328. tm->tm_sec);
  329. }
  330. static void applog_and_exit(const char *fmt, ...)
  331. {
  332. va_list ap;
  333. va_start(ap, fmt);
  334. vapplog(LOG_ERR, fmt, ap);
  335. va_end(ap);
  336. exit(1);
  337. }
  338. static pthread_mutex_t sharelog_lock;
  339. static FILE *sharelog_file = NULL;
  340. static void sharelog(const char*disposition, const struct work*work)
  341. {
  342. char *target, *hash, *data;
  343. struct cgpu_info *cgpu;
  344. unsigned long int t;
  345. struct pool *pool;
  346. int thr_id, rv;
  347. char s[1024];
  348. size_t ret;
  349. if (!sharelog_file)
  350. return;
  351. thr_id = work->thr_id;
  352. cgpu = thr_info[thr_id].cgpu;
  353. pool = work->pool;
  354. t = (unsigned long int)(work->tv_work_found.tv_sec);
  355. target = bin2hex(work->target, sizeof(work->target));
  356. hash = bin2hex(work->hash, sizeof(work->hash));
  357. data = bin2hex(work->data, sizeof(work->data));
  358. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  359. rv = snprintf(s, sizeof(s), "%lu,%s,%s,%s,%s,%u,%s,%s\n", t, disposition, target, pool->rpc_url, cgpu->proc_repr_ns, thr_id, hash, data);
  360. free(target);
  361. free(hash);
  362. free(data);
  363. if (rv >= (int)(sizeof(s)))
  364. s[sizeof(s) - 1] = '\0';
  365. else if (rv < 0) {
  366. applog(LOG_ERR, "sharelog printf error");
  367. return;
  368. }
  369. mutex_lock(&sharelog_lock);
  370. ret = fwrite(s, rv, 1, sharelog_file);
  371. fflush(sharelog_file);
  372. mutex_unlock(&sharelog_lock);
  373. if (ret != 1)
  374. applog(LOG_ERR, "sharelog fwrite error");
  375. }
  376. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  377. /* Return value is ignored if not called from add_pool_details */
  378. struct pool *add_pool(void)
  379. {
  380. struct pool *pool;
  381. pool = calloc(sizeof(struct pool), 1);
  382. if (!pool)
  383. quit(1, "Failed to malloc pool in add_pool");
  384. pool->pool_no = pool->prio = total_pools;
  385. mutex_init(&pool->last_work_lock);
  386. mutex_init(&pool->pool_lock);
  387. if (unlikely(pthread_cond_init(&pool->cr_cond, NULL)))
  388. quit(1, "Failed to pthread_cond_init in add_pool");
  389. mutex_init(&pool->stratum_lock);
  390. INIT_LIST_HEAD(&pool->curlring);
  391. pool->swork.transparency_time = (time_t)-1;
  392. /* Make sure the pool doesn't think we've been idle since time 0 */
  393. pool->tv_idle.tv_sec = ~0UL;
  394. pool->rpc_proxy = NULL;
  395. pool->sock = INVSOCK;
  396. pool->lp_socket = CURL_SOCKET_BAD;
  397. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  398. pools[total_pools++] = pool;
  399. return pool;
  400. }
  401. /* Pool variant of test and set */
  402. static bool pool_tset(struct pool *pool, bool *var)
  403. {
  404. bool ret;
  405. mutex_lock(&pool->pool_lock);
  406. ret = *var;
  407. *var = true;
  408. mutex_unlock(&pool->pool_lock);
  409. return ret;
  410. }
  411. bool pool_tclear(struct pool *pool, bool *var)
  412. {
  413. bool ret;
  414. mutex_lock(&pool->pool_lock);
  415. ret = *var;
  416. *var = false;
  417. mutex_unlock(&pool->pool_lock);
  418. return ret;
  419. }
  420. struct pool *current_pool(void)
  421. {
  422. struct pool *pool;
  423. mutex_lock(&control_lock);
  424. pool = currentpool;
  425. mutex_unlock(&control_lock);
  426. return pool;
  427. }
  428. char *set_int_range(const char *arg, int *i, int min, int max)
  429. {
  430. char *err = opt_set_intval(arg, i);
  431. if (err)
  432. return err;
  433. if (*i < min || *i > max)
  434. return "Value out of range";
  435. return NULL;
  436. }
  437. static char *set_int_0_to_9999(const char *arg, int *i)
  438. {
  439. return set_int_range(arg, i, 0, 9999);
  440. }
  441. static char *set_int_1_to_65535(const char *arg, int *i)
  442. {
  443. return set_int_range(arg, i, 1, 65535);
  444. }
  445. static char *set_int_0_to_10(const char *arg, int *i)
  446. {
  447. return set_int_range(arg, i, 0, 10);
  448. }
  449. static char *set_int_1_to_10(const char *arg, int *i)
  450. {
  451. return set_int_range(arg, i, 1, 10);
  452. }
  453. char *set_strdup(const char *arg, char **p)
  454. {
  455. *p = strdup((char *)arg);
  456. return NULL;
  457. }
  458. #if BLKMAKER_VERSION > 1
  459. static char *set_b58addr(const char *arg, struct _cbscript_t *p)
  460. {
  461. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  462. if (!scriptsz)
  463. return "Invalid address";
  464. char *script = malloc(scriptsz);
  465. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  466. free(script);
  467. return "Failed to convert address to script";
  468. }
  469. p->data = script;
  470. p->sz = scriptsz;
  471. return NULL;
  472. }
  473. #endif
  474. static void bdiff_target_leadzero(unsigned char *target, double diff);
  475. char *set_request_diff(const char *arg, float *p)
  476. {
  477. unsigned char target[32];
  478. char *e = opt_set_floatval(arg, p);
  479. if (e)
  480. return e;
  481. request_bdiff = (double)*p * 0.9999847412109375;
  482. bdiff_target_leadzero(target, request_bdiff);
  483. request_target_str = bin2hex(target, 32);
  484. return NULL;
  485. }
  486. #ifdef HAVE_LIBUDEV
  487. #include <libudev.h>
  488. #endif
  489. static
  490. char* add_serial_all(char*arg, char*p) {
  491. #ifdef HAVE_LIBUDEV
  492. struct udev *udev = udev_new();
  493. struct udev_enumerate *enumerate = udev_enumerate_new(udev);
  494. struct udev_list_entry *list_entry;
  495. udev_enumerate_add_match_subsystem(enumerate, "tty");
  496. udev_enumerate_add_match_property(enumerate, "ID_SERIAL", "*");
  497. udev_enumerate_scan_devices(enumerate);
  498. udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
  499. struct udev_device *device = udev_device_new_from_syspath(
  500. udev_enumerate_get_udev(enumerate),
  501. udev_list_entry_get_name(list_entry)
  502. );
  503. if (!device)
  504. continue;
  505. const char *devpath = udev_device_get_devnode(device);
  506. if (devpath) {
  507. size_t pLen = p - arg;
  508. size_t dLen = strlen(devpath) + 1;
  509. char dev[dLen + pLen];
  510. memcpy(dev, arg, pLen);
  511. memcpy(&dev[pLen], devpath, dLen);
  512. applog(LOG_DEBUG, "scan-serial: libudev all-adding %s", dev);
  513. string_elist_add(dev, &scan_devices);
  514. }
  515. udev_device_unref(device);
  516. }
  517. udev_enumerate_unref(enumerate);
  518. udev_unref(udev);
  519. return NULL;
  520. #elif defined(WIN32)
  521. size_t bufLen = 0x10; // temp!
  522. tryagain: ;
  523. char buf[bufLen];
  524. if (!QueryDosDevice(NULL, buf, bufLen)) {
  525. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  526. bufLen *= 2;
  527. applog(LOG_DEBUG, "scan-serial: QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  528. goto tryagain;
  529. }
  530. return "scan-serial: Error occurred trying to enumerate COM ports with QueryDosDevice";
  531. }
  532. size_t tLen = p - arg;
  533. char dev[12 + tLen];
  534. memcpy(dev, arg, tLen);
  535. memcpy(&dev[tLen], "\\\\.\\", 4);
  536. char *devp = &dev[tLen + 4];
  537. for (char *t = buf; *t; t += tLen) {
  538. tLen = strlen(t) + 1;
  539. if (strncmp("COM", t, 3))
  540. continue;
  541. memcpy(devp, t, tLen);
  542. applog(LOG_DEBUG, "scan-serial: QueryDosDevice all-adding %s", dev);
  543. string_elist_add(dev, &scan_devices);
  544. }
  545. return NULL;
  546. #else
  547. DIR *D;
  548. struct dirent *de;
  549. const char devdir[] = "/dev";
  550. const size_t devdirlen = sizeof(devdir) - 1;
  551. char devpath[sizeof(devdir) + NAME_MAX];
  552. char *devfile = devpath + devdirlen + 1;
  553. D = opendir(devdir);
  554. if (!D)
  555. return "scan-serial 'all' is not supported on this platform";
  556. memcpy(devpath, devdir, devdirlen);
  557. devpath[devdirlen] = '/';
  558. while ( (de = readdir(D)) ) {
  559. if (strncmp(de->d_name, "tty", 3))
  560. continue;
  561. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  562. continue;
  563. strcpy(devfile, de->d_name);
  564. applog(LOG_DEBUG, "scan-serial: /dev glob all-adding %s", devpath);
  565. string_elist_add(devpath, &scan_devices);
  566. }
  567. closedir(D);
  568. #endif
  569. }
  570. #ifdef USE_FPGA_SERIAL
  571. static char *add_serial(char *arg)
  572. {
  573. char *p = strchr(arg, ':');
  574. if (p)
  575. ++p;
  576. else
  577. p = arg;
  578. if (!strcasecmp(p, "all")) {
  579. return add_serial_all(arg, p);
  580. }
  581. string_elist_add(arg, &scan_devices);
  582. return NULL;
  583. }
  584. #endif
  585. static char *set_devices(char *arg)
  586. {
  587. int i = strtol(arg, &arg, 0);
  588. if (*arg) {
  589. if (*arg == '?') {
  590. devices_enabled = -1;
  591. return NULL;
  592. }
  593. return "Invalid device number";
  594. }
  595. if (i < 0 || i >= (int)(sizeof(devices_enabled) * 8) - 1)
  596. return "Invalid device number";
  597. devices_enabled |= 1 << i;
  598. return NULL;
  599. }
  600. static char *set_balance(enum pool_strategy *strategy)
  601. {
  602. *strategy = POOL_BALANCE;
  603. return NULL;
  604. }
  605. static char *set_loadbalance(enum pool_strategy *strategy)
  606. {
  607. *strategy = POOL_LOADBALANCE;
  608. return NULL;
  609. }
  610. static char *set_rotate(const char *arg, int *i)
  611. {
  612. pool_strategy = POOL_ROTATE;
  613. return set_int_range(arg, i, 0, 9999);
  614. }
  615. static char *set_rr(enum pool_strategy *strategy)
  616. {
  617. *strategy = POOL_ROUNDROBIN;
  618. return NULL;
  619. }
  620. /* Detect that url is for a stratum protocol either via the presence of
  621. * stratum+tcp or by detecting a stratum server response */
  622. bool detect_stratum(struct pool *pool, char *url)
  623. {
  624. if (!extract_sockaddr(pool, url))
  625. return false;
  626. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  627. pool->rpc_url = strdup(url);
  628. pool->has_stratum = true;
  629. pool->stratum_url = pool->sockaddr_url;
  630. return true;
  631. }
  632. return false;
  633. }
  634. static char *set_url(char *arg)
  635. {
  636. struct pool *pool;
  637. total_urls++;
  638. if (total_urls > total_pools)
  639. add_pool();
  640. pool = pools[total_urls - 1];
  641. if (detect_stratum(pool, arg))
  642. return NULL;
  643. opt_set_charp(arg, &pool->rpc_url);
  644. if (strncmp(arg, "http://", 7) &&
  645. strncmp(arg, "https://", 8)) {
  646. char *httpinput;
  647. httpinput = malloc(255);
  648. if (!httpinput)
  649. quit(1, "Failed to malloc httpinput");
  650. strcpy(httpinput, "http://");
  651. strncat(httpinput, arg, 248);
  652. pool->rpc_url = httpinput;
  653. }
  654. return NULL;
  655. }
  656. static char *set_user(const char *arg)
  657. {
  658. struct pool *pool;
  659. total_users++;
  660. if (total_users > total_pools)
  661. add_pool();
  662. pool = pools[total_users - 1];
  663. opt_set_charp(arg, &pool->rpc_user);
  664. return NULL;
  665. }
  666. static char *set_pass(const char *arg)
  667. {
  668. struct pool *pool;
  669. total_passes++;
  670. if (total_passes > total_pools)
  671. add_pool();
  672. pool = pools[total_passes - 1];
  673. opt_set_charp(arg, &pool->rpc_pass);
  674. return NULL;
  675. }
  676. static char *set_userpass(const char *arg)
  677. {
  678. struct pool *pool;
  679. char *updup;
  680. if (total_users != total_passes)
  681. return "User + pass options must be balanced before userpass";
  682. ++total_users;
  683. ++total_passes;
  684. if (total_users > total_pools)
  685. add_pool();
  686. pool = pools[total_users - 1];
  687. updup = strdup(arg);
  688. opt_set_charp(arg, &pool->rpc_userpass);
  689. pool->rpc_user = strtok(updup, ":");
  690. if (!pool->rpc_user)
  691. return "Failed to find : delimited user info";
  692. pool->rpc_pass = strtok(NULL, ":");
  693. if (!pool->rpc_pass)
  694. pool->rpc_pass = "";
  695. return NULL;
  696. }
  697. static char *set_pool_priority(const char *arg)
  698. {
  699. struct pool *pool;
  700. if (!total_pools)
  701. return "Usage of --pool-priority before pools are defined does not make sense";
  702. pool = pools[total_pools - 1];
  703. opt_set_intval(arg, &pool->prio);
  704. return NULL;
  705. }
  706. static char *set_pool_proxy(const char *arg)
  707. {
  708. struct pool *pool;
  709. if (!total_pools)
  710. return "Usage of --pool-proxy before pools are defined does not make sense";
  711. if (!our_curl_supports_proxy_uris())
  712. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  713. pool = pools[total_pools - 1];
  714. opt_set_charp(arg, &pool->rpc_proxy);
  715. return NULL;
  716. }
  717. static char *set_pool_force_rollntime(const char *arg)
  718. {
  719. struct pool *pool;
  720. if (!total_pools)
  721. return "Usage of --force-rollntime before pools are defined does not make sense";
  722. pool = pools[total_pools - 1];
  723. opt_set_intval(arg, &pool->force_rollntime);
  724. return NULL;
  725. }
  726. static char *enable_debug(bool *flag)
  727. {
  728. *flag = true;
  729. opt_debug_console = true;
  730. /* Turn on verbose output, too. */
  731. opt_log_output = true;
  732. return NULL;
  733. }
  734. static char *set_schedtime(const char *arg, struct schedtime *st)
  735. {
  736. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  737. {
  738. if (strcasecmp(arg, "now"))
  739. return "Invalid time set, should be HH:MM";
  740. } else
  741. schedstop.tm.tm_sec = 0;
  742. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  743. return "Invalid time set.";
  744. st->enable = true;
  745. return NULL;
  746. }
  747. static char* set_sharelog(char *arg)
  748. {
  749. char *r = "";
  750. long int i = strtol(arg, &r, 10);
  751. if ((!*r) && i >= 0 && i <= INT_MAX) {
  752. sharelog_file = fdopen((int)i, "a");
  753. if (!sharelog_file)
  754. applog(LOG_ERR, "Failed to open fd %u for share log", (unsigned int)i);
  755. } else if (!strcmp(arg, "-")) {
  756. sharelog_file = stdout;
  757. if (!sharelog_file)
  758. applog(LOG_ERR, "Standard output missing for share log");
  759. } else {
  760. sharelog_file = fopen(arg, "a");
  761. if (!sharelog_file)
  762. applog(LOG_ERR, "Failed to open %s for share log", arg);
  763. }
  764. return NULL;
  765. }
  766. static char *temp_cutoff_str = "";
  767. static char *temp_target_str = "";
  768. char *set_temp_cutoff(char *arg)
  769. {
  770. int val;
  771. if (!(arg && arg[0]))
  772. return "Invalid parameters for set temp cutoff";
  773. val = atoi(arg);
  774. if (val < 0 || val > 200)
  775. return "Invalid value passed to set temp cutoff";
  776. temp_cutoff_str = arg;
  777. return NULL;
  778. }
  779. char *set_temp_target(char *arg)
  780. {
  781. int val;
  782. if (!(arg && arg[0]))
  783. return "Invalid parameters for set temp target";
  784. val = atoi(arg);
  785. if (val < 0 || val > 200)
  786. return "Invalid value passed to set temp target";
  787. temp_target_str = arg;
  788. return NULL;
  789. }
  790. // For a single element string, this always returns the number (for all calls)
  791. // For multi-element strings, it returns each element as a number in order, and 0 when there are no more
  792. static int temp_strtok(char *base, char **n)
  793. {
  794. char *i = *n;
  795. char *p = strchr(i, ',');
  796. if (p) {
  797. p[0] = '\0';
  798. *n = &p[1];
  799. }
  800. else
  801. if (base != i)
  802. *n = strchr(i, '\0');
  803. return atoi(i);
  804. }
  805. static void load_temp_config()
  806. {
  807. int i, val = 0, target_off;
  808. char *cutoff_n, *target_n;
  809. struct cgpu_info *cgpu;
  810. cutoff_n = temp_cutoff_str;
  811. target_n = temp_target_str;
  812. for (i = 0; i < total_devices; ++i) {
  813. cgpu = devices[i];
  814. // cutoff default may be specified by driver during probe; otherwise, opt_cutofftemp (const)
  815. if (!cgpu->cutofftemp)
  816. cgpu->cutofftemp = opt_cutofftemp;
  817. // target default may be specified by driver, and is moved with offset; otherwise, offset minus 6
  818. if (cgpu->targettemp)
  819. target_off = cgpu->targettemp - cgpu->cutofftemp;
  820. else
  821. target_off = -6;
  822. val = temp_strtok(temp_cutoff_str, &cutoff_n);
  823. if (val < 0 || val > 200)
  824. quit(1, "Invalid value passed to set temp cutoff");
  825. if (val)
  826. cgpu->cutofftemp = val;
  827. val = temp_strtok(temp_target_str, &target_n);
  828. if (val < 0 || val > 200)
  829. quit(1, "Invalid value passed to set temp target");
  830. if (val)
  831. cgpu->targettemp = val;
  832. else
  833. cgpu->targettemp = cgpu->cutofftemp + target_off;
  834. applog(LOG_DEBUG, "%"PRIprepr": Set temperature config: target=%d cutoff=%d",
  835. cgpu->proc_repr,
  836. cgpu->targettemp, cgpu->cutofftemp);
  837. }
  838. if (cutoff_n != temp_cutoff_str && cutoff_n[0])
  839. quit(1, "Too many values passed to set temp cutoff");
  840. if (target_n != temp_target_str && target_n[0])
  841. quit(1, "Too many values passed to set temp target");
  842. }
  843. static char *set_api_allow(const char *arg)
  844. {
  845. opt_set_charp(arg, &opt_api_allow);
  846. return NULL;
  847. }
  848. static char *set_api_groups(const char *arg)
  849. {
  850. opt_set_charp(arg, &opt_api_groups);
  851. return NULL;
  852. }
  853. static char *set_api_description(const char *arg)
  854. {
  855. opt_set_charp(arg, &opt_api_description);
  856. return NULL;
  857. }
  858. #ifdef USE_ICARUS
  859. static char *set_icarus_options(const char *arg)
  860. {
  861. opt_set_charp(arg, &opt_icarus_options);
  862. return NULL;
  863. }
  864. static char *set_icarus_timing(const char *arg)
  865. {
  866. opt_set_charp(arg, &opt_icarus_timing);
  867. return NULL;
  868. }
  869. #endif
  870. __maybe_unused
  871. static char *set_null(const char __maybe_unused *arg)
  872. {
  873. return NULL;
  874. }
  875. /* These options are available from config file or commandline */
  876. static struct opt_table opt_config_table[] = {
  877. #ifdef WANT_CPUMINE
  878. OPT_WITH_ARG("--algo|-a",
  879. set_algo, show_algo, &opt_algo,
  880. "Specify sha256 implementation for CPU mining:\n"
  881. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  882. "\n\tc\t\tLinux kernel sha256, implemented in C"
  883. #ifdef WANT_SSE2_4WAY
  884. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  885. #endif
  886. #ifdef WANT_VIA_PADLOCK
  887. "\n\tvia\t\tVIA padlock implementation"
  888. #endif
  889. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  890. #ifdef WANT_CRYPTOPP_ASM32
  891. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  892. #endif
  893. #ifdef WANT_X8632_SSE2
  894. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  895. #endif
  896. #ifdef WANT_X8664_SSE2
  897. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  898. #endif
  899. #ifdef WANT_X8664_SSE4
  900. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  901. #endif
  902. #ifdef WANT_ALTIVEC_4WAY
  903. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  904. #endif
  905. ),
  906. #endif
  907. OPT_WITH_ARG("--api-allow",
  908. set_api_allow, NULL, NULL,
  909. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  910. OPT_WITH_ARG("--api-description",
  911. set_api_description, NULL, NULL,
  912. "Description placed in the API status header, default: BFGMiner version"),
  913. OPT_WITH_ARG("--api-groups",
  914. set_api_groups, NULL, NULL,
  915. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  916. OPT_WITHOUT_ARG("--api-listen",
  917. opt_set_bool, &opt_api_listen,
  918. "Enable API, default: disabled"),
  919. OPT_WITHOUT_ARG("--api-network",
  920. opt_set_bool, &opt_api_network,
  921. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  922. OPT_WITH_ARG("--api-port",
  923. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  924. "Port number of miner API"),
  925. #ifdef HAVE_ADL
  926. OPT_WITHOUT_ARG("--auto-fan",
  927. opt_set_bool, &opt_autofan,
  928. "Automatically adjust all GPU fan speeds to maintain a target temperature"),
  929. OPT_WITHOUT_ARG("--auto-gpu",
  930. opt_set_bool, &opt_autoengine,
  931. "Automatically adjust all GPU engine clock speeds to maintain a target temperature"),
  932. #endif
  933. OPT_WITHOUT_ARG("--balance",
  934. set_balance, &pool_strategy,
  935. "Change multipool strategy from failover to even share balance"),
  936. OPT_WITHOUT_ARG("--benchmark",
  937. opt_set_bool, &opt_benchmark,
  938. "Run BFGMiner in benchmark mode - produces no shares"),
  939. #if defined(USE_BITFORCE)
  940. OPT_WITHOUT_ARG("--bfl-range",
  941. opt_set_bool, &opt_bfl_noncerange,
  942. "Use nonce range on bitforce devices if supported"),
  943. #endif
  944. #ifdef WANT_CPUMINE
  945. OPT_WITH_ARG("--bench-algo|-b",
  946. set_int_0_to_9999, opt_show_intval, &opt_bench_algo,
  947. opt_hidden),
  948. #endif
  949. #if BLKMAKER_VERSION > 1
  950. OPT_WITH_ARG("--coinbase-addr",
  951. set_b58addr, NULL, &opt_coinbase_script,
  952. "Set coinbase payout address for solo mining"),
  953. OPT_WITH_ARG("--coinbase-payout|--cbaddr|--cb-addr|--payout",
  954. set_b58addr, NULL, &opt_coinbase_script,
  955. opt_hidden),
  956. #endif
  957. #if BLKMAKER_VERSION > 0
  958. OPT_WITH_ARG("--coinbase-sig",
  959. set_strdup, NULL, &opt_coinbase_sig,
  960. "Set coinbase signature when possible"),
  961. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  962. set_strdup, NULL, &opt_coinbase_sig,
  963. opt_hidden),
  964. #endif
  965. #ifdef HAVE_CURSES
  966. OPT_WITHOUT_ARG("--compact",
  967. opt_set_bool, &opt_compact,
  968. "Use compact display without per device statistics"),
  969. #endif
  970. #ifdef WANT_CPUMINE
  971. OPT_WITH_ARG("--cpu-threads|-t",
  972. force_nthreads_int, opt_show_intval, &opt_n_threads,
  973. "Number of miner CPU threads"),
  974. #endif
  975. OPT_WITHOUT_ARG("--debug|-D",
  976. enable_debug, &opt_debug,
  977. "Enable debug output"),
  978. OPT_WITHOUT_ARG("--debuglog",
  979. opt_set_bool, &opt_debug,
  980. "Enable debug logging"),
  981. OPT_WITH_ARG("--device|-d",
  982. set_devices, NULL, NULL,
  983. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  984. OPT_WITHOUT_ARG("--disable-gpu|-G",
  985. opt_set_bool, &opt_nogpu,
  986. #ifdef HAVE_OPENCL
  987. "Disable GPU mining even if suitable devices exist"
  988. #else
  989. opt_hidden
  990. #endif
  991. ),
  992. OPT_WITHOUT_ARG("--disable-rejecting",
  993. opt_set_bool, &opt_disable_pool,
  994. "Automatically disable pools that continually reject shares"),
  995. #if defined(WANT_CPUMINE) && (defined(HAVE_OPENCL) || defined(USE_FPGA))
  996. OPT_WITHOUT_ARG("--enable-cpu|-C",
  997. opt_set_bool, &opt_usecpu,
  998. "Enable CPU mining with other mining (default: no CPU mining if other devices exist)"),
  999. #endif
  1000. OPT_WITH_ARG("--expiry|-E",
  1001. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1002. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  1003. OPT_WITH_ARG("--expiry-lp",
  1004. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  1005. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  1006. OPT_WITHOUT_ARG("--failover-only",
  1007. opt_set_bool, &opt_fail_only,
  1008. "Don't leak work to backup pools when primary pool is lagging"),
  1009. #ifdef USE_FPGA
  1010. OPT_WITHOUT_ARG("--force-dev-init",
  1011. opt_set_bool, &opt_force_dev_init,
  1012. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  1013. #endif
  1014. #ifdef HAVE_OPENCL
  1015. OPT_WITH_ARG("--gpu-dyninterval",
  1016. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  1017. "Set the refresh interval in ms for GPUs using dynamic intensity"),
  1018. OPT_WITH_ARG("--gpu-platform",
  1019. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  1020. "Select OpenCL platform ID to use for GPU mining"),
  1021. OPT_WITH_ARG("--gpu-threads|-g",
  1022. set_int_1_to_10, opt_show_intval, &opt_g_threads,
  1023. "Number of threads per GPU (1 - 10)"),
  1024. #ifdef HAVE_ADL
  1025. OPT_WITH_ARG("--gpu-engine",
  1026. set_gpu_engine, NULL, NULL,
  1027. "GPU engine (over)clock range in MHz - one value, range and/or comma separated list (e.g. 850-900,900,750-850)"),
  1028. OPT_WITH_ARG("--gpu-fan",
  1029. set_gpu_fan, NULL, NULL,
  1030. "GPU fan percentage range - one value, range and/or comma separated list (e.g. 0-85,85,65)"),
  1031. OPT_WITH_ARG("--gpu-map",
  1032. set_gpu_map, NULL, NULL,
  1033. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  1034. OPT_WITH_ARG("--gpu-memclock",
  1035. set_gpu_memclock, NULL, NULL,
  1036. "Set the GPU memory (over)clock in MHz - one value for all or separate by commas for per card"),
  1037. OPT_WITH_ARG("--gpu-memdiff",
  1038. set_gpu_memdiff, NULL, NULL,
  1039. "Set a fixed difference in clock speed between the GPU and memory in auto-gpu mode"),
  1040. OPT_WITH_ARG("--gpu-powertune",
  1041. set_gpu_powertune, NULL, NULL,
  1042. "Set the GPU powertune percentage - one value for all or separate by commas for per card"),
  1043. OPT_WITHOUT_ARG("--gpu-reorder",
  1044. opt_set_bool, &opt_reorder,
  1045. "Attempt to reorder GPU devices according to PCI Bus ID"),
  1046. OPT_WITH_ARG("--gpu-vddc",
  1047. set_gpu_vddc, NULL, NULL,
  1048. "Set the GPU voltage in Volts - one value for all or separate by commas for per card"),
  1049. #endif
  1050. #ifdef USE_SCRYPT
  1051. OPT_WITH_ARG("--lookup-gap",
  1052. set_lookup_gap, NULL, NULL,
  1053. "Set GPU lookup gap for scrypt mining, comma separated"),
  1054. #endif
  1055. OPT_WITH_ARG("--intensity|-I",
  1056. set_intensity, NULL, NULL,
  1057. "Intensity of GPU scanning (d or " _MIN_INTENSITY_STR " -> " _MAX_INTENSITY_STR ", default: d to maintain desktop interactivity)"),
  1058. #endif
  1059. #if defined(HAVE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  1060. OPT_WITH_ARG("--kernel-path|-K",
  1061. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1062. "Specify a path to where bitstream and kernel files are"),
  1063. #endif
  1064. #ifdef HAVE_OPENCL
  1065. OPT_WITH_ARG("--kernel|-k",
  1066. set_kernel, NULL, NULL,
  1067. "Override sha256 kernel to use (diablo, poclbm, phatk or diakgcn) - one value or comma separated"),
  1068. #endif
  1069. #ifdef USE_ICARUS
  1070. OPT_WITH_ARG("--icarus-options",
  1071. set_icarus_options, NULL, NULL,
  1072. opt_hidden),
  1073. OPT_WITH_ARG("--icarus-timing",
  1074. set_icarus_timing, NULL, NULL,
  1075. opt_hidden),
  1076. #endif
  1077. OPT_WITHOUT_ARG("--load-balance",
  1078. set_loadbalance, &pool_strategy,
  1079. "Change multipool strategy from failover to efficiency based balance"),
  1080. OPT_WITH_ARG("--log|-l",
  1081. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  1082. "Interval in seconds between log output"),
  1083. #if defined(unix)
  1084. OPT_WITH_ARG("--monitor|-m",
  1085. opt_set_charp, NULL, &opt_stderr_cmd,
  1086. "Use custom pipe cmd for output messages"),
  1087. #endif // defined(unix)
  1088. OPT_WITHOUT_ARG("--net-delay",
  1089. opt_set_bool, &opt_delaynet,
  1090. "Impose small delays in networking to not overload slow routers"),
  1091. OPT_WITHOUT_ARG("--no-adl",
  1092. opt_set_bool, &opt_noadl,
  1093. #ifdef HAVE_ADL
  1094. "Disable the ATI display library used for monitoring and setting GPU parameters"
  1095. #else
  1096. opt_hidden
  1097. #endif
  1098. ),
  1099. OPT_WITHOUT_ARG("--no-gbt",
  1100. opt_set_invbool, &want_gbt,
  1101. "Disable getblocktemplate support"),
  1102. OPT_WITHOUT_ARG("--no-getwork",
  1103. opt_set_invbool, &want_getwork,
  1104. "Disable getwork support"),
  1105. OPT_WITHOUT_ARG("--no-longpoll",
  1106. opt_set_invbool, &want_longpoll,
  1107. "Disable X-Long-Polling support"),
  1108. OPT_WITHOUT_ARG("--no-pool-disable",
  1109. opt_set_invbool, &opt_disable_pool,
  1110. opt_hidden),
  1111. OPT_WITHOUT_ARG("--no-restart",
  1112. opt_set_invbool, &opt_restart,
  1113. "Do not attempt to restart devices that hang"
  1114. ),
  1115. OPT_WITHOUT_ARG("--no-show-processors",
  1116. opt_set_invbool, &opt_show_procs,
  1117. opt_hidden),
  1118. OPT_WITHOUT_ARG("--no-show-procs",
  1119. opt_set_invbool, &opt_show_procs,
  1120. opt_hidden),
  1121. OPT_WITHOUT_ARG("--no-stratum",
  1122. opt_set_invbool, &want_stratum,
  1123. "Disable Stratum detection"),
  1124. OPT_WITHOUT_ARG("--no-submit-stale",
  1125. opt_set_invbool, &opt_submit_stale,
  1126. "Don't submit shares if they are detected as stale"),
  1127. OPT_WITH_ARG("--pass|-p",
  1128. set_pass, NULL, NULL,
  1129. "Password for bitcoin JSON-RPC server"),
  1130. OPT_WITHOUT_ARG("--per-device-stats",
  1131. opt_set_bool, &want_per_device_stats,
  1132. "Force verbose mode and output per-device statistics"),
  1133. OPT_WITH_ARG("--pool-priority",
  1134. set_pool_priority, NULL, NULL,
  1135. "Priority for just the previous-defined pool"),
  1136. OPT_WITH_ARG("--pool-proxy|-x",
  1137. set_pool_proxy, NULL, NULL,
  1138. "Proxy URI to use for connecting to just the previous-defined pool"),
  1139. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  1140. set_pool_force_rollntime, NULL, NULL,
  1141. opt_hidden),
  1142. OPT_WITHOUT_ARG("--protocol-dump|-P",
  1143. opt_set_bool, &opt_protocol,
  1144. "Verbose dump of protocol-level activities"),
  1145. OPT_WITH_ARG("--queue|-Q",
  1146. set_int_0_to_9999, opt_show_intval, &opt_queue,
  1147. "Minimum number of work items to have queued (0+)"),
  1148. OPT_WITHOUT_ARG("--quiet|-q",
  1149. opt_set_bool, &opt_quiet,
  1150. "Disable logging output, display status and errors"),
  1151. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  1152. opt_set_bool, &opt_quiet_work_updates,
  1153. opt_hidden),
  1154. OPT_WITHOUT_ARG("--real-quiet",
  1155. opt_set_bool, &opt_realquiet,
  1156. "Disable all output"),
  1157. OPT_WITHOUT_ARG("--remove-disabled",
  1158. opt_set_bool, &opt_removedisabled,
  1159. "Remove disabled devices entirely, as if they didn't exist"),
  1160. OPT_WITH_ARG("--request-diff",
  1161. set_request_diff, opt_show_floatval, &request_pdiff,
  1162. "Request a specific difficulty from pools"),
  1163. OPT_WITH_ARG("--retries",
  1164. opt_set_intval, opt_show_intval, &opt_retries,
  1165. "Number of times to retry failed submissions before giving up (-1 means never)"),
  1166. OPT_WITH_ARG("--retry-pause",
  1167. set_null, NULL, NULL,
  1168. opt_hidden),
  1169. OPT_WITH_ARG("--rotate",
  1170. set_rotate, opt_show_intval, &opt_rotate_period,
  1171. "Change multipool strategy from failover to regularly rotate at N minutes"),
  1172. OPT_WITHOUT_ARG("--round-robin",
  1173. set_rr, &pool_strategy,
  1174. "Change multipool strategy from failover to round robin on failure"),
  1175. #ifdef USE_FPGA_SERIAL
  1176. OPT_WITH_ARG("--scan-serial|-S",
  1177. add_serial, NULL, NULL,
  1178. "Serial port to probe for FPGA Mining device"),
  1179. #endif
  1180. OPT_WITH_ARG("--scan-time|-s",
  1181. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  1182. "Upper bound on time spent scanning current work, in seconds"),
  1183. OPT_WITH_ARG("--scantime",
  1184. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  1185. opt_hidden),
  1186. OPT_WITH_ARG("--sched-start",
  1187. set_schedtime, NULL, &schedstart,
  1188. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  1189. OPT_WITH_ARG("--sched-stop",
  1190. set_schedtime, NULL, &schedstop,
  1191. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  1192. #ifdef USE_SCRYPT
  1193. OPT_WITHOUT_ARG("--scrypt",
  1194. opt_set_bool, &opt_scrypt,
  1195. "Use the scrypt algorithm for mining (non-bitcoin)"),
  1196. #ifdef HAVE_OPENCL
  1197. OPT_WITH_ARG("--shaders",
  1198. set_shaders, NULL, NULL,
  1199. "GPU shaders per card for tuning scrypt, comma separated"),
  1200. #endif
  1201. #endif
  1202. OPT_WITH_ARG("--sharelog",
  1203. set_sharelog, NULL, NULL,
  1204. "Append share log to file"),
  1205. OPT_WITH_ARG("--shares",
  1206. opt_set_intval, NULL, &opt_shares,
  1207. "Quit after mining N shares (default: unlimited)"),
  1208. OPT_WITHOUT_ARG("--show-processors",
  1209. opt_set_bool, &opt_show_procs,
  1210. "Show per processor statistics in summary"),
  1211. OPT_WITHOUT_ARG("--show-procs",
  1212. opt_set_bool, &opt_show_procs,
  1213. opt_hidden),
  1214. OPT_WITH_ARG("--skip-security-checks",
  1215. set_int_0_to_9999, NULL, &opt_skip_checks,
  1216. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  1217. OPT_WITH_ARG("--socks-proxy",
  1218. opt_set_charp, NULL, &opt_socks_proxy,
  1219. "Set socks4 proxy (host:port)"),
  1220. OPT_WITHOUT_ARG("--submit-stale",
  1221. opt_set_bool, &opt_submit_stale,
  1222. opt_hidden),
  1223. OPT_WITHOUT_ARG("--submit-threads",
  1224. opt_set_intval, &opt_submit_threads,
  1225. "Minimum number of concurrent share submissions (default: 64)"),
  1226. #ifdef HAVE_SYSLOG_H
  1227. OPT_WITHOUT_ARG("--syslog",
  1228. opt_set_bool, &use_syslog,
  1229. "Use system log for output messages (default: standard error)"),
  1230. #endif
  1231. #if defined(HAVE_ADL) || defined(USE_BITFORCE) || defined(USE_MODMINER)
  1232. OPT_WITH_ARG("--temp-cutoff",
  1233. set_temp_cutoff, opt_show_intval, &opt_cutofftemp,
  1234. "Temperature where a device will be automatically disabled, one value or comma separated list"),
  1235. #endif
  1236. #if defined(HAVE_ADL) || defined(USE_MODMINER)
  1237. OPT_WITH_ARG("--temp-hysteresis",
  1238. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  1239. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  1240. #ifdef HAVE_ADL
  1241. OPT_WITH_ARG("--temp-overheat",
  1242. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  1243. "Overheat temperature when automatically managing fan and GPU speeds, one value or comma separated list"),
  1244. #endif
  1245. OPT_WITH_ARG("--temp-target",
  1246. set_temp_target, NULL, NULL,
  1247. "Target temperature when automatically managing fan and clock speeds, one value or comma separated list"),
  1248. #endif
  1249. OPT_WITHOUT_ARG("--text-only|-T",
  1250. opt_set_invbool, &use_curses,
  1251. #ifdef HAVE_CURSES
  1252. "Disable ncurses formatted screen output"
  1253. #else
  1254. opt_hidden
  1255. #endif
  1256. ),
  1257. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  1258. OPT_WITH_ARG("--thread-concurrency",
  1259. set_thread_concurrency, NULL, NULL,
  1260. "Set GPU thread concurrency for scrypt mining, comma separated"),
  1261. #endif
  1262. OPT_WITH_ARG("--url|-o",
  1263. set_url, NULL, NULL,
  1264. "URL for bitcoin JSON-RPC server"),
  1265. OPT_WITH_ARG("--user|-u",
  1266. set_user, NULL, NULL,
  1267. "Username for bitcoin JSON-RPC server"),
  1268. #ifdef HAVE_OPENCL
  1269. OPT_WITH_ARG("--vectors|-v",
  1270. set_vector, NULL, NULL,
  1271. "Override detected optimal vector (1, 2 or 4) - one value or comma separated list"),
  1272. #endif
  1273. OPT_WITHOUT_ARG("--verbose",
  1274. opt_set_bool, &opt_log_output,
  1275. "Log verbose output to stderr as well as status output"),
  1276. #ifdef HAVE_OPENCL
  1277. OPT_WITH_ARG("--worksize|-w",
  1278. set_worksize, NULL, NULL,
  1279. "Override detected optimal worksize - one value or comma separated list"),
  1280. #endif
  1281. OPT_WITH_ARG("--userpass|-O",
  1282. set_userpass, NULL, NULL,
  1283. "Username:Password pair for bitcoin JSON-RPC server"),
  1284. OPT_WITHOUT_ARG("--worktime",
  1285. opt_set_bool, &opt_worktime,
  1286. "Display extra work time debug information"),
  1287. OPT_WITH_ARG("--pools",
  1288. opt_set_bool, NULL, NULL, opt_hidden),
  1289. OPT_ENDTABLE
  1290. };
  1291. static char *load_config(const char *arg, void __maybe_unused *unused);
  1292. static int fileconf_load;
  1293. static char *parse_config(json_t *config, bool fileconf)
  1294. {
  1295. static char err_buf[200];
  1296. struct opt_table *opt;
  1297. json_t *val;
  1298. if (fileconf && !fileconf_load)
  1299. fileconf_load = 1;
  1300. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  1301. char *p, *name, *sp;
  1302. /* We don't handle subtables. */
  1303. assert(!(opt->type & OPT_SUBTABLE));
  1304. /* Pull apart the option name(s). */
  1305. name = strdup(opt->names);
  1306. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  1307. char *err = "Invalid value";
  1308. /* Ignore short options. */
  1309. if (p[1] != '-')
  1310. continue;
  1311. val = json_object_get(config, p+2);
  1312. if (!val)
  1313. continue;
  1314. if (opt->type & OPT_HASARG) {
  1315. if (json_is_string(val)) {
  1316. err = opt->cb_arg(json_string_value(val),
  1317. opt->u.arg);
  1318. } else if (json_is_number(val)) {
  1319. char buf[256], *p, *q;
  1320. snprintf(buf, 256, "%f", json_number_value(val));
  1321. if ( (p = strchr(buf, '.')) ) {
  1322. // Trim /\.0*$/ to work properly with integer-only arguments
  1323. q = p;
  1324. while (*(++q) == '0') {}
  1325. if (*q == '\0')
  1326. *p = '\0';
  1327. }
  1328. err = opt->cb_arg(buf, opt->u.arg);
  1329. } else if (json_is_array(val)) {
  1330. int n, size = json_array_size(val);
  1331. err = NULL;
  1332. for (n = 0; n < size && !err; n++) {
  1333. if (json_is_string(json_array_get(val, n)))
  1334. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  1335. else if (json_is_object(json_array_get(val, n)))
  1336. err = parse_config(json_array_get(val, n), false);
  1337. }
  1338. }
  1339. } else if (opt->type & OPT_NOARG) {
  1340. if (json_is_true(val))
  1341. err = opt->cb(opt->u.arg);
  1342. else if (json_is_boolean(val)) {
  1343. if (opt->cb == (void*)opt_set_bool)
  1344. err = opt_set_invbool(opt->u.arg);
  1345. else if (opt->cb == (void*)opt_set_invbool)
  1346. err = opt_set_bool(opt->u.arg);
  1347. }
  1348. }
  1349. if (err) {
  1350. /* Allow invalid values to be in configuration
  1351. * file, just skipping over them provided the
  1352. * JSON is still valid after that. */
  1353. if (fileconf) {
  1354. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  1355. fileconf_load = -1;
  1356. } else {
  1357. sprintf(err_buf, "Parsing JSON option %s: %s",
  1358. p, err);
  1359. return err_buf;
  1360. }
  1361. }
  1362. }
  1363. free(name);
  1364. }
  1365. val = json_object_get(config, JSON_INCLUDE_CONF);
  1366. if (val && json_is_string(val))
  1367. return load_config(json_string_value(val), NULL);
  1368. return NULL;
  1369. }
  1370. char *cnfbuf = NULL;
  1371. static char *load_config(const char *arg, void __maybe_unused *unused)
  1372. {
  1373. json_error_t err;
  1374. json_t *config;
  1375. char *json_error;
  1376. if (!cnfbuf)
  1377. cnfbuf = strdup(arg);
  1378. if (++include_count > JSON_MAX_DEPTH)
  1379. return JSON_MAX_DEPTH_ERR;
  1380. #if JANSSON_MAJOR_VERSION > 1
  1381. config = json_load_file(arg, 0, &err);
  1382. #else
  1383. config = json_load_file(arg, &err);
  1384. #endif
  1385. if (!json_is_object(config)) {
  1386. json_error = malloc(JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text));
  1387. if (!json_error)
  1388. quit(1, "Malloc failure in json error");
  1389. sprintf(json_error, JSON_LOAD_ERROR, arg, err.text);
  1390. return json_error;
  1391. }
  1392. config_loaded = true;
  1393. /* Parse the config now, so we can override it. That can keep pointers
  1394. * so don't free config object. */
  1395. return parse_config(config, true);
  1396. }
  1397. static void load_default_config(void)
  1398. {
  1399. cnfbuf = malloc(PATH_MAX);
  1400. #if defined(unix)
  1401. if (getenv("HOME") && *getenv("HOME")) {
  1402. strcpy(cnfbuf, getenv("HOME"));
  1403. strcat(cnfbuf, "/");
  1404. } else
  1405. strcpy(cnfbuf, "");
  1406. char *dirp = cnfbuf + strlen(cnfbuf);
  1407. strcpy(dirp, ".bfgminer/");
  1408. strcat(dirp, def_conf);
  1409. if (access(cnfbuf, R_OK))
  1410. // No BFGMiner config, try Cgminer's...
  1411. strcpy(dirp, ".cgminer/cgminer.conf");
  1412. #else
  1413. strcpy(cnfbuf, "");
  1414. strcat(cnfbuf, def_conf);
  1415. #endif
  1416. if (!access(cnfbuf, R_OK))
  1417. load_config(cnfbuf, NULL);
  1418. else {
  1419. free(cnfbuf);
  1420. cnfbuf = NULL;
  1421. }
  1422. }
  1423. extern const char *opt_argv0;
  1424. static char *opt_verusage_and_exit(const char *extra)
  1425. {
  1426. printf("%s\nBuilt with "
  1427. #ifdef HAVE_OPENCL
  1428. "GPU "
  1429. #endif
  1430. #ifdef WANT_CPUMINE
  1431. "CPU "
  1432. #endif
  1433. #ifdef USE_BITFORCE
  1434. "bitforce "
  1435. #endif
  1436. #ifdef USE_ICARUS
  1437. "icarus "
  1438. #endif
  1439. #ifdef USE_MODMINER
  1440. "modminer "
  1441. #endif
  1442. #ifdef USE_X6500
  1443. "x6500 "
  1444. #endif
  1445. #ifdef USE_ZTEX
  1446. "ztex "
  1447. #endif
  1448. #ifdef USE_SCRYPT
  1449. "scrypt "
  1450. #endif
  1451. "mining support.\n"
  1452. , packagename);
  1453. printf("%s", opt_usage(opt_argv0, extra));
  1454. fflush(stdout);
  1455. exit(0);
  1456. }
  1457. /* These options are available from commandline only */
  1458. static struct opt_table opt_cmdline_table[] = {
  1459. OPT_WITH_ARG("--config|-c",
  1460. load_config, NULL, NULL,
  1461. "Load a JSON-format configuration file\n"
  1462. "See example.conf for an example configuration."),
  1463. OPT_WITHOUT_ARG("--help|-h",
  1464. opt_verusage_and_exit, NULL,
  1465. "Print this message"),
  1466. #ifdef HAVE_OPENCL
  1467. OPT_WITHOUT_ARG("--ndevs|-n",
  1468. print_ndevs_and_exit, &nDevs,
  1469. "Display number of detected GPUs, OpenCL platform information, and exit"),
  1470. #endif
  1471. OPT_WITHOUT_ARG("--version|-V",
  1472. opt_version_and_exit, packagename,
  1473. "Display version and exit"),
  1474. OPT_ENDTABLE
  1475. };
  1476. static bool jobj_binary(const json_t *obj, const char *key,
  1477. void *buf, size_t buflen, bool required)
  1478. {
  1479. const char *hexstr;
  1480. json_t *tmp;
  1481. tmp = json_object_get(obj, key);
  1482. if (unlikely(!tmp)) {
  1483. if (unlikely(required))
  1484. applog(LOG_ERR, "JSON key '%s' not found", key);
  1485. return false;
  1486. }
  1487. hexstr = json_string_value(tmp);
  1488. if (unlikely(!hexstr)) {
  1489. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  1490. return false;
  1491. }
  1492. if (!hex2bin(buf, hexstr, buflen))
  1493. return false;
  1494. return true;
  1495. }
  1496. static void calc_midstate(struct work *work)
  1497. {
  1498. union {
  1499. unsigned char c[64];
  1500. uint32_t i[16];
  1501. } data;
  1502. swap32yes(&data.i[0], work->data, 16);
  1503. sha2_context ctx;
  1504. sha2_starts(&ctx);
  1505. sha2_update(&ctx, data.c, 64);
  1506. memcpy(work->midstate, ctx.state, sizeof(work->midstate));
  1507. swap32tole(work->midstate, work->midstate, 8);
  1508. }
  1509. static struct work *make_work(void)
  1510. {
  1511. struct work *work = calloc(1, sizeof(struct work));
  1512. if (unlikely(!work))
  1513. quit(1, "Failed to calloc work in make_work");
  1514. mutex_lock(&control_lock);
  1515. work->id = total_work++;
  1516. mutex_unlock(&control_lock);
  1517. return work;
  1518. }
  1519. /* This is the central place all work that is about to be retired should be
  1520. * cleaned to remove any dynamically allocated arrays within the struct */
  1521. void clean_work(struct work *work)
  1522. {
  1523. free(work->sessionid);
  1524. free(work->job_id);
  1525. free(work->nonce2);
  1526. free(work->ntime);
  1527. work->job_id = NULL;
  1528. work->nonce2 = NULL;
  1529. work->ntime = NULL;
  1530. if (work->tmpl) {
  1531. struct pool *pool = work->pool;
  1532. mutex_lock(&pool->pool_lock);
  1533. bool free_tmpl = !--*work->tmpl_refcount;
  1534. mutex_unlock(&pool->pool_lock);
  1535. if (free_tmpl) {
  1536. blktmpl_free(work->tmpl);
  1537. free(work->tmpl_refcount);
  1538. }
  1539. }
  1540. memset(work, 0, sizeof(struct work));
  1541. }
  1542. /* All dynamically allocated work structs should be freed here to not leak any
  1543. * ram from arrays allocated within the work struct */
  1544. void free_work(struct work *work)
  1545. {
  1546. clean_work(work);
  1547. free(work);
  1548. }
  1549. static char *workpadding = "000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000";
  1550. // Must only be called with ch_lock held!
  1551. static
  1552. void __update_block_title(const unsigned char *hash_swap)
  1553. {
  1554. char *tmp;
  1555. if (hash_swap) {
  1556. // Only provided when the block has actually changed
  1557. free(current_hash);
  1558. current_hash = malloc(3 /* ... */ + 16 /* block hash segment */ + 1);
  1559. tmp = bin2hex(&hash_swap[24], 8);
  1560. sprintf(current_hash, "...%s", tmp);
  1561. free(tmp);
  1562. known_blkheight_current = false;
  1563. } else if (likely(known_blkheight_current)) {
  1564. return;
  1565. }
  1566. if (current_block_id == known_blkheight_blkid) {
  1567. // FIXME: The block number will overflow this sometime around AD 2025-2027
  1568. if (known_blkheight < 1000000) {
  1569. memmove(&current_hash[3], &current_hash[11], 8);
  1570. sprintf(&current_hash[11], " #%6u", known_blkheight);
  1571. }
  1572. known_blkheight_current = true;
  1573. }
  1574. }
  1575. static
  1576. void have_block_height(uint32_t block_id, uint32_t blkheight)
  1577. {
  1578. if (known_blkheight == blkheight)
  1579. return;
  1580. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, be32toh(block_id), blkheight);
  1581. mutex_lock(&ch_lock);
  1582. known_blkheight = blkheight;
  1583. known_blkheight_blkid = block_id;
  1584. if (block_id == current_block_id)
  1585. __update_block_title(NULL);
  1586. mutex_unlock(&ch_lock);
  1587. }
  1588. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  1589. {
  1590. json_t *res_val = json_object_get(val, "result");
  1591. json_t *tmp_val;
  1592. bool ret = false;
  1593. if (unlikely(detect_algo == 1)) {
  1594. json_t *tmp = json_object_get(res_val, "algorithm");
  1595. const char *v = tmp ? json_string_value(tmp) : "";
  1596. if (strncasecmp(v, "scrypt", 6))
  1597. detect_algo = 2;
  1598. }
  1599. if (work->tmpl) {
  1600. const char *err = blktmpl_add_jansson(work->tmpl, res_val, time(NULL));
  1601. if (err) {
  1602. applog(LOG_ERR, "blktmpl error: %s", err);
  1603. return false;
  1604. }
  1605. work->rolltime = blkmk_time_left(work->tmpl, time(NULL));
  1606. #if BLKMAKER_VERSION > 1
  1607. if (opt_coinbase_script.sz)
  1608. {
  1609. bool newcb;
  1610. #if BLKMAKER_VERSION > 2
  1611. blkmk_init_generation2(work->tmpl, opt_coinbase_script.data, opt_coinbase_script.sz, &newcb);
  1612. #else
  1613. newcb = !work->tmpl->cbtxn;
  1614. blkmk_init_generation(work->tmpl, opt_coinbase_script.data, opt_coinbase_script.sz);
  1615. #endif
  1616. if (newcb)
  1617. {
  1618. ssize_t ae = blkmk_append_coinbase_safe(work->tmpl, &template_nonce, sizeof(template_nonce));
  1619. if (ae < (ssize_t)sizeof(template_nonce))
  1620. applog(LOG_WARNING, "Cannot append template-nonce to coinbase on pool %u (%"PRId64") - you might be wasting hashing!", work->pool->pool_no, (int64_t)ae);
  1621. ++template_nonce;
  1622. }
  1623. }
  1624. #endif
  1625. #if BLKMAKER_VERSION > 0
  1626. {
  1627. ssize_t ae = blkmk_append_coinbase_safe(work->tmpl, opt_coinbase_sig, 101);
  1628. static bool appenderr = false;
  1629. if (ae <= 0) {
  1630. if (opt_coinbase_sig) {
  1631. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  1632. appenderr = true;
  1633. }
  1634. } else if (ae >= 3 || opt_coinbase_sig) {
  1635. const char *cbappend = opt_coinbase_sig;
  1636. if (!cbappend) {
  1637. const char full[] = PACKAGE " " VERSION;
  1638. // NOTE: Intentially including a trailing \0 on long forms so extranonce doesn't confuse things
  1639. if ((size_t)ae >= sizeof(full))
  1640. cbappend = full;
  1641. else if ((size_t)ae >= sizeof(PACKAGE))
  1642. cbappend = PACKAGE;
  1643. else
  1644. cbappend = "BFG";
  1645. }
  1646. size_t cbappendsz = strlen(cbappend);
  1647. static bool truncatewarning = false;
  1648. if (cbappendsz <= (size_t)ae) {
  1649. ae = cbappendsz;
  1650. truncatewarning = false;
  1651. } else {
  1652. char *tmp = malloc(ae + 1);
  1653. memcpy(tmp, opt_coinbase_sig, ae);
  1654. tmp[ae] = '\0';
  1655. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  1656. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  1657. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  1658. free(tmp);
  1659. truncatewarning = true;
  1660. }
  1661. ae = blkmk_append_coinbase_safe(work->tmpl, cbappend, ae);
  1662. if (ae <= 0) {
  1663. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  1664. appenderr = true;
  1665. } else
  1666. appenderr = false;
  1667. }
  1668. }
  1669. #endif
  1670. if (blkmk_get_data(work->tmpl, work->data, 80, time(NULL), NULL, &work->dataid) < 76)
  1671. return false;
  1672. swap32yes(work->data, work->data, 80 / 4);
  1673. memcpy(&work->data[80], "\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\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x80\x02\0\0", 48);
  1674. const struct blktmpl_longpoll_req *lp;
  1675. if ((lp = blktmpl_get_longpoll(work->tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  1676. free(pool->lp_id);
  1677. pool->lp_id = strdup(lp->id);
  1678. #if 0 /* This just doesn't work :( */
  1679. curl_socket_t sock = pool->lp_socket;
  1680. if (sock != CURL_SOCKET_BAD) {
  1681. pool->lp_socket = CURL_SOCKET_BAD;
  1682. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  1683. shutdown(sock, SHUT_RDWR);
  1684. }
  1685. #endif
  1686. }
  1687. }
  1688. else
  1689. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  1690. applog(LOG_ERR, "JSON inval data");
  1691. return false;
  1692. }
  1693. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  1694. // Calculate it ourselves
  1695. applog(LOG_DEBUG, "Calculating midstate locally");
  1696. calc_midstate(work);
  1697. }
  1698. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  1699. applog(LOG_ERR, "JSON inval target");
  1700. return false;
  1701. }
  1702. if (work->tmpl) {
  1703. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  1704. {
  1705. int p = (sizeof(work->target) - 1) - i;
  1706. unsigned char c = work->target[i];
  1707. work->target[i] = work->target[p];
  1708. work->target[p] = c;
  1709. }
  1710. }
  1711. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  1712. uint32_t blkheight = json_number_value(tmp_val);
  1713. uint32_t block_id = ((uint32_t*)work->data)[1];
  1714. have_block_height(block_id, blkheight);
  1715. }
  1716. memset(work->hash, 0, sizeof(work->hash));
  1717. gettimeofday(&work->tv_staged, NULL);
  1718. ret = true;
  1719. return ret;
  1720. }
  1721. int dev_from_id(int thr_id)
  1722. {
  1723. return thr_info[thr_id].cgpu->device_id;
  1724. }
  1725. /* Make the change in the recent value adjust dynamically when the difference
  1726. * is large, but damp it when the values are closer together. This allows the
  1727. * value to change quickly, but not fluctuate too dramatically when it has
  1728. * stabilised. */
  1729. void decay_time(double *f, double fadd)
  1730. {
  1731. double ratio = 0;
  1732. if (likely(*f > 0)) {
  1733. ratio = fadd / *f;
  1734. if (ratio > 1)
  1735. ratio = 1 / ratio;
  1736. }
  1737. if (ratio > 0.63)
  1738. *f = (fadd * 0.58 + *f) / 1.58;
  1739. else
  1740. *f = (fadd + *f * 0.58) / 1.58;
  1741. }
  1742. static int __total_staged(void)
  1743. {
  1744. return HASH_COUNT(staged_work);
  1745. }
  1746. static int total_staged(void)
  1747. {
  1748. int ret;
  1749. mutex_lock(stgd_lock);
  1750. ret = __total_staged();
  1751. mutex_unlock(stgd_lock);
  1752. return ret;
  1753. }
  1754. #ifdef HAVE_CURSES
  1755. WINDOW *mainwin, *statuswin, *logwin;
  1756. #endif
  1757. double total_secs = 1.0;
  1758. static char statusline[256];
  1759. /* logstart is where the log window should start */
  1760. static int devcursor, logstart, logcursor;
  1761. #ifdef HAVE_CURSES
  1762. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  1763. static int statusy;
  1764. static int devsummaryYOffset;
  1765. static int total_lines;
  1766. #endif
  1767. #ifdef HAVE_OPENCL
  1768. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  1769. #endif
  1770. struct cgpu_info *cpus;
  1771. #ifdef HAVE_CURSES
  1772. static inline void unlock_curses(void)
  1773. {
  1774. mutex_unlock(&console_lock);
  1775. }
  1776. static inline void lock_curses(void)
  1777. {
  1778. mutex_lock(&console_lock);
  1779. }
  1780. static bool curses_active_locked(void)
  1781. {
  1782. bool ret;
  1783. lock_curses();
  1784. ret = curses_active;
  1785. if (!ret)
  1786. unlock_curses();
  1787. return ret;
  1788. }
  1789. // Cancellable getch
  1790. int my_cancellable_getch(void)
  1791. {
  1792. // This only works because the macro only hits direct getch() calls
  1793. typedef int (*real_getch_t)(void);
  1794. const real_getch_t real_getch = __real_getch;
  1795. int type, rv;
  1796. bool sct;
  1797. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  1798. rv = real_getch();
  1799. if (sct)
  1800. pthread_setcanceltype(type, &type);
  1801. return rv;
  1802. }
  1803. #endif
  1804. void tailsprintf(char *f, const char *fmt, ...)
  1805. {
  1806. va_list ap;
  1807. va_start(ap, fmt);
  1808. vsprintf(f + strlen(f), fmt, ap);
  1809. va_end(ap);
  1810. }
  1811. /* Convert a uint64_t value into a truncated string for displaying with its
  1812. * associated suitable for Mega, Giga etc. Buf array needs to be long enough */
  1813. static void suffix_string(uint64_t val, char *buf, int sigdigits)
  1814. {
  1815. const double dkilo = 1000.0;
  1816. const uint64_t kilo = 1000ull;
  1817. const uint64_t mega = 1000000ull;
  1818. const uint64_t giga = 1000000000ull;
  1819. const uint64_t tera = 1000000000000ull;
  1820. const uint64_t peta = 1000000000000000ull;
  1821. const uint64_t exa = 1000000000000000000ull;
  1822. char suffix[2] = "";
  1823. bool decimal = true;
  1824. double dval;
  1825. if (val >= exa) {
  1826. val /= peta;
  1827. dval = (double)val / dkilo;
  1828. sprintf(suffix, "E");
  1829. } else if (val >= peta) {
  1830. val /= tera;
  1831. dval = (double)val / dkilo;
  1832. sprintf(suffix, "P");
  1833. } else if (val >= tera) {
  1834. val /= giga;
  1835. dval = (double)val / dkilo;
  1836. sprintf(suffix, "T");
  1837. } else if (val >= giga) {
  1838. val /= mega;
  1839. dval = (double)val / dkilo;
  1840. sprintf(suffix, "G");
  1841. } else if (val >= mega) {
  1842. val /= kilo;
  1843. dval = (double)val / dkilo;
  1844. sprintf(suffix, "M");
  1845. } else if (val >= kilo) {
  1846. dval = (double)val / dkilo;
  1847. sprintf(suffix, "k");
  1848. } else {
  1849. dval = val;
  1850. decimal = false;
  1851. }
  1852. if (!sigdigits) {
  1853. if (decimal)
  1854. sprintf(buf, "%.3g%s", dval, suffix);
  1855. else
  1856. sprintf(buf, "%d%s", (unsigned int)dval, suffix);
  1857. } else {
  1858. /* Always show sigdigits + 1, padded on right with zeroes
  1859. * followed by suffix */
  1860. int ndigits = sigdigits - 1 - (dval > 0.0 ? floor(log10(dval)) : 0);
  1861. sprintf(buf, "%*.*f%s", sigdigits + 1, ndigits, dval, suffix);
  1862. }
  1863. }
  1864. static float
  1865. utility_to_hashrate(double utility)
  1866. {
  1867. return utility * 0x4444444;
  1868. }
  1869. static const char*_unitchar = "kMGTPEZY?";
  1870. static void
  1871. hashrate_pick_unit(float hashrate, unsigned char*unit)
  1872. {
  1873. unsigned char i;
  1874. for (i = 0; i <= *unit; ++i)
  1875. hashrate /= 1e3;
  1876. while (hashrate >= 1000)
  1877. {
  1878. hashrate /= 1e3;
  1879. if (likely(_unitchar[*unit] != '?'))
  1880. ++*unit;
  1881. }
  1882. }
  1883. enum h2bs_fmt {
  1884. H2B_NOUNIT, // "xxx.x"
  1885. H2B_SHORT, // "xxx.xMH/s"
  1886. H2B_SPACED, // "xxx.x MH/s"
  1887. };
  1888. static const size_t h2bs_fmt_size[] = {6, 10, 11};
  1889. static char*
  1890. hashrate_to_bufstr(char*buf, float hashrate, signed char unitin, enum h2bs_fmt fmt)
  1891. {
  1892. unsigned char prec, i, ucp, unit;
  1893. if (unitin == -1)
  1894. {
  1895. unit = 0;
  1896. hashrate_pick_unit(hashrate, &unit);
  1897. }
  1898. else
  1899. unit = unitin;
  1900. i = 5;
  1901. switch (fmt) {
  1902. case H2B_SPACED:
  1903. buf[i++] = ' ';
  1904. case H2B_SHORT:
  1905. buf[i++] = _unitchar[unit];
  1906. strcpy(&buf[i], "h/s");
  1907. default:
  1908. break;
  1909. }
  1910. for (i = 0; i <= unit; ++i)
  1911. hashrate /= 1000;
  1912. if (hashrate >= 100 || unit < 2)
  1913. prec = 1;
  1914. else
  1915. if (hashrate >= 10)
  1916. prec = 2;
  1917. else
  1918. prec = 3;
  1919. ucp = (fmt == H2B_NOUNIT ? '\0' : buf[5]);
  1920. sprintf(buf, "%5.*f", prec, hashrate);
  1921. buf[5] = ucp;
  1922. return buf;
  1923. }
  1924. static void
  1925. ti_hashrate_bufstr(char**out, float current, float average, float sharebased, enum h2bs_fmt longfmt)
  1926. {
  1927. unsigned char unit = 0;
  1928. hashrate_pick_unit(current, &unit);
  1929. hashrate_pick_unit(average, &unit);
  1930. hashrate_pick_unit(sharebased, &unit);
  1931. hashrate_to_bufstr(out[0], current, unit, H2B_NOUNIT);
  1932. hashrate_to_bufstr(out[1], average, unit, H2B_NOUNIT);
  1933. hashrate_to_bufstr(out[2], sharebased, unit, longfmt);
  1934. }
  1935. #ifdef HAVE_CURSES
  1936. static void adj_width(int var, int *length);
  1937. #endif
  1938. static void get_statline2(char *buf, struct cgpu_info *cgpu, bool for_curses)
  1939. {
  1940. #ifdef HAVE_CURSES
  1941. static int awidth = 1, rwidth = 1, hwwidth = 1, uwidth = 1;
  1942. #else
  1943. assert(for_curses == false);
  1944. #endif
  1945. const struct device_api *api = cgpu->api;
  1946. void (*statline_func)(char *, struct cgpu_info *);
  1947. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  1948. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[hashrate_style]];
  1949. if (!opt_show_procs)
  1950. cgpu = cgpu->device;
  1951. cgpu->utility = cgpu->accepted / total_secs * 60;
  1952. cgpu->utility_diff1 = cgpu->diff_accepted / total_secs * 60;
  1953. double rolling = cgpu->rolling;
  1954. double mhashes = cgpu->total_mhashes;
  1955. double wutil = cgpu->utility_diff1;
  1956. int accepted = cgpu->accepted;
  1957. int rejected = cgpu->rejected;
  1958. int hwerrs = cgpu->hw_errors;
  1959. double util = cgpu->utility;
  1960. if (!opt_show_procs)
  1961. for (struct cgpu_info *slave = cgpu; (slave = slave->next_proc); )
  1962. {
  1963. slave->utility = slave->accepted / total_secs * 60;
  1964. slave->utility_diff1 = slave->diff_accepted / total_secs * 60;
  1965. rolling += slave->rolling;
  1966. mhashes += slave->total_mhashes;
  1967. wutil += slave->utility_diff1;
  1968. accepted += slave->accepted;
  1969. rejected += slave->rejected;
  1970. hwerrs += slave->hw_errors;
  1971. util += slave->utility;
  1972. }
  1973. ti_hashrate_bufstr(
  1974. (char*[]){cHr, aHr, uHr},
  1975. 1e6*rolling,
  1976. 1e6*mhashes / total_secs,
  1977. utility_to_hashrate(wutil),
  1978. hashrate_style);
  1979. // Processor representation
  1980. #ifdef HAVE_CURSES
  1981. if (for_curses)
  1982. {
  1983. if (opt_show_procs)
  1984. sprintf(buf, " %"PRIprepr": ", cgpu->proc_repr);
  1985. else
  1986. sprintf(buf, " %s: ", cgpu->dev_repr);
  1987. }
  1988. else
  1989. #endif
  1990. sprintf(buf, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  1991. if (api->get_dev_statline_before || api->get_statline_before)
  1992. {
  1993. if (api->get_dev_statline_before && api->get_statline_before)
  1994. statline_func = opt_show_procs ? api->get_statline_before : api->get_dev_statline_before;
  1995. else
  1996. statline_func = api->get_statline_before ?: api->get_dev_statline_before;
  1997. statline_func(buf, cgpu);
  1998. }
  1999. else
  2000. tailsprintf(buf, " | ");
  2001. #ifdef HAVE_CURSES
  2002. if (for_curses)
  2003. {
  2004. const char *cHrStatsOpt[] = {"DEAD ", "SICK ", "OFF ", "REST ", " ERR ", "WAIT ", cHr};
  2005. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  2006. bool all_dead = true, all_off = true;
  2007. for (struct cgpu_info *proc = cgpu; proc; proc = proc->next_proc)
  2008. {
  2009. switch (cHrStatsI) {
  2010. default:
  2011. if (proc->status == LIFE_WAIT)
  2012. cHrStatsI = 5;
  2013. case 5:
  2014. if (proc->deven == DEV_RECOVER_ERR)
  2015. cHrStatsI = 4;
  2016. case 4:
  2017. if (proc->deven == DEV_RECOVER)
  2018. cHrStatsI = 3;
  2019. case 3:
  2020. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD)
  2021. {
  2022. cHrStatsI = 1;
  2023. all_off = false;
  2024. }
  2025. else
  2026. if (likely(proc->deven != DEV_DISABLED))
  2027. all_off = false;
  2028. case 1:
  2029. break;
  2030. }
  2031. if (likely(proc->status != LIFE_DEAD))
  2032. all_dead = false;
  2033. if (opt_show_procs)
  2034. break;
  2035. }
  2036. if (unlikely(all_dead))
  2037. cHrStatsI = 0;
  2038. else
  2039. if (unlikely(all_off))
  2040. cHrStatsI = 2;
  2041. adj_width(accepted, &awidth);
  2042. adj_width(rejected, &rwidth);
  2043. adj_width(hwerrs, &hwwidth);
  2044. adj_width(util, &uwidth);
  2045. tailsprintf(buf, "%s/%s/%s | A:%*d R:%*d HW:%*d U:%*.2f/m",
  2046. cHrStatsOpt[cHrStatsI],
  2047. aHr, uHr,
  2048. awidth, accepted,
  2049. rwidth, rejected,
  2050. hwwidth, hwerrs,
  2051. uwidth + 3, util
  2052. );
  2053. }
  2054. else
  2055. #endif
  2056. {
  2057. tailsprintf(buf, "%ds:%s avg:%s u:%s | A:%d R:%d HW:%d U:%.1f/m",
  2058. opt_log_interval,
  2059. cHr, aHr, uHr,
  2060. accepted,
  2061. rejected,
  2062. hwerrs,
  2063. util);
  2064. }
  2065. if (api->get_dev_statline_after || api->get_statline)
  2066. {
  2067. if (api->get_dev_statline_after && api->get_statline)
  2068. statline_func = opt_show_procs ? api->get_statline : api->get_dev_statline_after;
  2069. else
  2070. statline_func = api->get_statline ?: api->get_dev_statline_after;
  2071. statline_func(buf, cgpu);
  2072. }
  2073. }
  2074. #define get_statline(buf, cgpu) get_statline2(buf, cgpu, false)
  2075. static void text_print_status(int thr_id)
  2076. {
  2077. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  2078. char logline[256];
  2079. if (cgpu) {
  2080. get_statline(logline, cgpu);
  2081. printf("%s\n", logline);
  2082. }
  2083. }
  2084. #ifdef HAVE_CURSES
  2085. /* Must be called with curses mutex lock held and curses_active */
  2086. static void curses_print_status(void)
  2087. {
  2088. struct pool *pool = current_pool();
  2089. struct timeval now, tv;
  2090. float efficiency;
  2091. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  2092. wattron(statuswin, A_BOLD);
  2093. mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  2094. if (!gettimeofday(&now, NULL))
  2095. {
  2096. unsigned int days, hours;
  2097. div_t d;
  2098. timersub(&now, &miner_started, &tv);
  2099. d = div(tv.tv_sec, 86400);
  2100. days = d.quot;
  2101. d = div(d.rem, 3600);
  2102. hours = d.quot;
  2103. d = div(d.rem, 60);
  2104. wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  2105. , days
  2106. , (days == 1) ? ' ' : 's'
  2107. , hours
  2108. , d.quot
  2109. , d.rem
  2110. );
  2111. }
  2112. wattroff(statuswin, A_BOLD);
  2113. mvwhline(statuswin, 1, 0, '-', 80);
  2114. mvwprintw(statuswin, 2, 0, " %s", statusline);
  2115. wclrtoeol(statuswin);
  2116. mvwprintw(statuswin, 3, 0, " ST: %d DW: %d GW: %d LW: %d GF: %d NB: %d AS: %d RF: %d E: %.2f",
  2117. total_staged(), total_discarded,
  2118. total_getworks,
  2119. local_work,
  2120. total_go,
  2121. new_blocks,
  2122. total_submitting,
  2123. total_ro,
  2124. efficiency);
  2125. wclrtoeol(statuswin);
  2126. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && total_pools > 1) {
  2127. mvwprintw(statuswin, 4, 0, " Connected to multiple pools with%s LP",
  2128. have_longpoll ? "": "out");
  2129. } else if (pool->has_stratum) {
  2130. mvwprintw(statuswin, 4, 0, " Connected to %s diff %s with stratum as user %s",
  2131. pool->sockaddr_url, pool->diff, pool->rpc_user);
  2132. } else {
  2133. mvwprintw(statuswin, 4, 0, " Connected to %s diff %s with%s LP as user %s",
  2134. pool->sockaddr_url, pool->diff, have_longpoll ? "": "out", pool->rpc_user);
  2135. }
  2136. wclrtoeol(statuswin);
  2137. mvwprintw(statuswin, 5, 0, " Block: %s Diff:%s Started: %s Best share: %s ",
  2138. current_hash, block_diff, blocktime, best_share);
  2139. mvwhline(statuswin, 6, 0, '-', 80);
  2140. mvwhline(statuswin, statusy - 1, 0, '-', 80);
  2141. mvwprintw(statuswin, devcursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
  2142. have_opencl ? "[G]PU management " : "");
  2143. }
  2144. static void adj_width(int var, int *length)
  2145. {
  2146. if ((int)(log10(var) + 1) > *length)
  2147. (*length)++;
  2148. }
  2149. static int dev_width;
  2150. static void curses_print_devstatus(int thr_id)
  2151. {
  2152. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  2153. char logline[256];
  2154. int ypos;
  2155. if (opt_compact)
  2156. return;
  2157. /* Check this isn't out of the window size */
  2158. if (opt_show_procs)
  2159. ypos = cgpu->cgminer_id;
  2160. else
  2161. {
  2162. if (cgpu->proc_id)
  2163. return;
  2164. ypos = cgpu->device_line_id;
  2165. }
  2166. ypos += devsummaryYOffset;
  2167. if (ypos < 0)
  2168. return;
  2169. ypos += devcursor;
  2170. if (ypos >= statusy - 1)
  2171. return;
  2172. if (wmove(statuswin, ypos, 0) == ERR)
  2173. return;
  2174. get_statline2(logline, cgpu, true);
  2175. waddstr(statuswin, logline);
  2176. wclrtoeol(statuswin);
  2177. }
  2178. #endif
  2179. static void print_status(int thr_id)
  2180. {
  2181. if (!curses_active)
  2182. text_print_status(thr_id);
  2183. }
  2184. #ifdef HAVE_CURSES
  2185. /* Check for window resize. Called with curses mutex locked */
  2186. static inline void change_logwinsize(void)
  2187. {
  2188. int x, y, logx, logy;
  2189. getmaxyx(mainwin, y, x);
  2190. if (x < 80 || y < 25)
  2191. return;
  2192. if (y > statusy + 2 && statusy < logstart) {
  2193. if (y - 2 < logstart)
  2194. statusy = y - 2;
  2195. else
  2196. statusy = logstart;
  2197. logcursor = statusy + 1;
  2198. mvwin(logwin, logcursor, 0);
  2199. wresize(statuswin, statusy, x);
  2200. }
  2201. y -= logcursor;
  2202. getmaxyx(logwin, logy, logx);
  2203. /* Detect screen size change */
  2204. if (x != logx || y != logy)
  2205. wresize(logwin, y, x);
  2206. }
  2207. static void check_winsizes(void)
  2208. {
  2209. if (!use_curses)
  2210. return;
  2211. if (curses_active_locked()) {
  2212. int y, x;
  2213. erase();
  2214. x = getmaxx(statuswin);
  2215. if (logstart > LINES - 2)
  2216. statusy = LINES - 2;
  2217. else
  2218. statusy = logstart;
  2219. logcursor = statusy + 1;
  2220. wresize(statuswin, statusy, x);
  2221. getmaxyx(mainwin, y, x);
  2222. y -= logcursor;
  2223. wresize(logwin, y, x);
  2224. mvwin(logwin, logcursor, 0);
  2225. unlock_curses();
  2226. }
  2227. }
  2228. static int device_line_id_count;
  2229. static void switch_compact(void)
  2230. {
  2231. if (opt_compact) {
  2232. logstart = devcursor + 1;
  2233. logcursor = logstart + 1;
  2234. } else {
  2235. total_lines = (opt_show_procs ? total_devices : device_line_id_count);
  2236. logstart = devcursor + total_lines + 1;
  2237. logcursor = logstart + 1;
  2238. }
  2239. check_winsizes();
  2240. }
  2241. #define change_summarywinsize switch_compact
  2242. /* For mandatory printing when mutex is already locked */
  2243. void wlog(const char *f, ...)
  2244. {
  2245. va_list ap;
  2246. va_start(ap, f);
  2247. vw_printw(logwin, f, ap);
  2248. va_end(ap);
  2249. }
  2250. /* Mandatory printing */
  2251. void wlogprint(const char *f, ...)
  2252. {
  2253. va_list ap;
  2254. if (curses_active_locked()) {
  2255. va_start(ap, f);
  2256. vw_printw(logwin, f, ap);
  2257. va_end(ap);
  2258. unlock_curses();
  2259. }
  2260. }
  2261. #endif
  2262. #ifdef HAVE_CURSES
  2263. bool log_curses_only(int prio, const char *f, va_list ap)
  2264. {
  2265. bool high_prio;
  2266. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  2267. if (curses_active_locked()) {
  2268. if (!opt_loginput || high_prio) {
  2269. vw_printw(logwin, f, ap);
  2270. if (high_prio) {
  2271. touchwin(logwin);
  2272. wrefresh(logwin);
  2273. }
  2274. }
  2275. unlock_curses();
  2276. return true;
  2277. }
  2278. return false;
  2279. }
  2280. void clear_logwin(void)
  2281. {
  2282. if (curses_active_locked()) {
  2283. wclear(logwin);
  2284. unlock_curses();
  2285. }
  2286. }
  2287. #endif
  2288. /* Returns true if the regenerated work->hash solves a block */
  2289. static bool solves_block(const struct work *work)
  2290. {
  2291. unsigned char target[32];
  2292. real_block_target(target, work->data);
  2293. return hash_target_check(work->hash, target);
  2294. }
  2295. static void enable_pool(struct pool *pool)
  2296. {
  2297. if (pool->enabled != POOL_ENABLED) {
  2298. enabled_pools++;
  2299. pool->enabled = POOL_ENABLED;
  2300. }
  2301. }
  2302. static void disable_pool(struct pool *pool)
  2303. {
  2304. if (pool->enabled == POOL_ENABLED)
  2305. enabled_pools--;
  2306. pool->enabled = POOL_DISABLED;
  2307. }
  2308. static void reject_pool(struct pool *pool)
  2309. {
  2310. if (pool->enabled == POOL_ENABLED)
  2311. enabled_pools--;
  2312. pool->enabled = POOL_REJECTING;
  2313. }
  2314. static uint64_t share_diff(const struct work *);
  2315. static
  2316. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  2317. struct cgpu_info *cgpu = thr_info[work->thr_id].cgpu;
  2318. const unsigned char *hashpart = &work->hash[opt_scrypt ? 26 : 24];
  2319. uint64_t shrdiff = share_diff(work);
  2320. char shrdiffdisp[16];
  2321. int tgtdiff = floor(work->work_difficulty);
  2322. char tgtdiffdisp[16];
  2323. char where[20];
  2324. suffix_string(shrdiff, shrdiffdisp, 0);
  2325. suffix_string(tgtdiff, tgtdiffdisp, 0);
  2326. if (total_pools > 1)
  2327. sprintf(where, " pool %d", work->pool->pool_no);
  2328. else
  2329. where[0] = '\0';
  2330. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  2331. disp,
  2332. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  2333. cgpu->proc_repr,
  2334. where,
  2335. shrdiffdisp, tgtdiffdisp,
  2336. reason,
  2337. resubmit ? "(resubmit)" : "",
  2338. worktime
  2339. );
  2340. }
  2341. static bool test_work_current(struct work *);
  2342. /* Theoretically threads could race when modifying accepted and
  2343. * rejected values but the chance of two submits completing at the
  2344. * same time is zero so there is no point adding extra locking */
  2345. static void
  2346. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  2347. /*char *hashshow,*/ bool resubmit, char *worktime)
  2348. {
  2349. struct pool *pool = work->pool;
  2350. struct cgpu_info *cgpu = thr_info[work->thr_id].cgpu;
  2351. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  2352. mutex_lock(&stats_lock);
  2353. cgpu->accepted++;
  2354. total_accepted++;
  2355. pool->accepted++;
  2356. cgpu->diff_accepted += work->work_difficulty;
  2357. total_diff_accepted += work->work_difficulty;
  2358. pool->diff_accepted += work->work_difficulty;
  2359. mutex_unlock(&stats_lock);
  2360. pool->seq_rejects = 0;
  2361. cgpu->last_share_pool = pool->pool_no;
  2362. cgpu->last_share_pool_time = time(NULL);
  2363. cgpu->last_share_diff = work->work_difficulty;
  2364. pool->last_share_time = cgpu->last_share_pool_time;
  2365. pool->last_share_diff = work->work_difficulty;
  2366. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  2367. if (!QUIET) {
  2368. share_result_msg(work, "Accepted", "", resubmit, worktime);
  2369. }
  2370. sharelog("accept", work);
  2371. if (opt_shares && total_accepted >= opt_shares) {
  2372. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  2373. kill_work();
  2374. return;
  2375. }
  2376. /* Detect if a pool that has been temporarily disabled for
  2377. * continually rejecting shares has started accepting shares.
  2378. * This will only happen with the work returned from a
  2379. * longpoll */
  2380. if (unlikely(pool->enabled == POOL_REJECTING)) {
  2381. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  2382. enable_pool(pool);
  2383. switch_pools(NULL);
  2384. }
  2385. if (unlikely(work->block)) {
  2386. // Force moving on to this new block :)
  2387. struct work fakework;
  2388. memset(&fakework, 0, sizeof(fakework));
  2389. fakework.pool = work->pool;
  2390. // Copy block version, bits, and time from share
  2391. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  2392. memcpy(&fakework.data[68], &work->data[68], 8);
  2393. // Set prevblock to winning hash (swap32'd)
  2394. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  2395. test_work_current(&fakework);
  2396. }
  2397. } else {
  2398. mutex_lock(&stats_lock);
  2399. cgpu->rejected++;
  2400. total_rejected++;
  2401. pool->rejected++;
  2402. cgpu->diff_rejected += work->work_difficulty;
  2403. total_diff_rejected += work->work_difficulty;
  2404. pool->diff_rejected += work->work_difficulty;
  2405. pool->seq_rejects++;
  2406. mutex_unlock(&stats_lock);
  2407. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  2408. if (!QUIET) {
  2409. char where[20];
  2410. char disposition[36] = "reject";
  2411. char reason[32];
  2412. strcpy(reason, "");
  2413. if (total_pools > 1)
  2414. sprintf(where, "pool %d", work->pool->pool_no);
  2415. else
  2416. strcpy(where, "");
  2417. if (!json_is_string(res))
  2418. res = json_object_get(val, "reject-reason");
  2419. if (res) {
  2420. const char *reasontmp = json_string_value(res);
  2421. size_t reasonLen = strlen(reasontmp);
  2422. if (reasonLen > 28)
  2423. reasonLen = 28;
  2424. reason[0] = ' '; reason[1] = '(';
  2425. memcpy(2 + reason, reasontmp, reasonLen);
  2426. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  2427. memcpy(disposition + 7, reasontmp, reasonLen);
  2428. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  2429. } else if (work->stratum && err && json_is_array(err)) {
  2430. json_t *reason_val = json_array_get(err, 1);
  2431. char *reason_str;
  2432. if (reason_val && json_is_string(reason_val)) {
  2433. reason_str = (char *)json_string_value(reason_val);
  2434. snprintf(reason, 31, " (%s)", reason_str);
  2435. }
  2436. }
  2437. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  2438. sharelog(disposition, work);
  2439. }
  2440. /* Once we have more than a nominal amount of sequential rejects,
  2441. * at least 10 and more than 3 mins at the current utility,
  2442. * disable the pool because some pool error is likely to have
  2443. * ensued. Do not do this if we know the share just happened to
  2444. * be stale due to networking delays.
  2445. */
  2446. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  2447. double utility = total_accepted / total_secs * 60;
  2448. if (pool->seq_rejects > utility * 3) {
  2449. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  2450. pool->pool_no, pool->seq_rejects);
  2451. reject_pool(pool);
  2452. if (pool == current_pool())
  2453. switch_pools(NULL);
  2454. pool->seq_rejects = 0;
  2455. }
  2456. }
  2457. }
  2458. }
  2459. static const uint64_t diffone = 0xFFFF000000000000ull;
  2460. static double target_diff(const unsigned char *target);
  2461. static uint64_t share_diff(const struct work *work)
  2462. {
  2463. uint64_t ret;
  2464. ret = target_diff(work->hash);
  2465. mutex_lock(&control_lock);
  2466. if (ret > best_diff) {
  2467. best_diff = ret;
  2468. suffix_string(best_diff, best_share, 0);
  2469. }
  2470. if (ret > work->pool->best_diff)
  2471. work->pool->best_diff = ret;
  2472. mutex_unlock(&control_lock);
  2473. return ret;
  2474. }
  2475. static char *submit_upstream_work_request(struct work *work)
  2476. {
  2477. char *hexstr = NULL;
  2478. char *s, *sd;
  2479. struct pool *pool = work->pool;
  2480. if (work->tmpl) {
  2481. unsigned char data[80];
  2482. swap32yes(data, work->data, 80 / 4);
  2483. json_t *req = blkmk_submit_jansson(work->tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  2484. s = json_dumps(req, 0);
  2485. json_decref(req);
  2486. sd = bin2hex(data, 80);
  2487. } else {
  2488. /* build hex string */
  2489. hexstr = bin2hex(work->data, sizeof(work->data));
  2490. /* build JSON-RPC request */
  2491. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  2492. s = realloc_strcat(s, hexstr);
  2493. s = realloc_strcat(s, "\" ], \"id\":1}");
  2494. free(hexstr);
  2495. sd = s;
  2496. }
  2497. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  2498. if (work->tmpl)
  2499. free(sd);
  2500. else
  2501. s = realloc_strcat(s, "\n");
  2502. return s;
  2503. }
  2504. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  2505. json_t *res, *err;
  2506. bool rc = false;
  2507. int thr_id = work->thr_id;
  2508. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  2509. struct pool *pool = work->pool;
  2510. struct timeval tv_submit_reply;
  2511. char worktime[200] = "";
  2512. gettimeofday(&tv_submit_reply, NULL);
  2513. if (unlikely(!val)) {
  2514. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  2515. if (!pool_tset(pool, &pool->submit_fail)) {
  2516. total_ro++;
  2517. pool->remotefail_occasions++;
  2518. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  2519. }
  2520. goto out;
  2521. } else if (pool_tclear(pool, &pool->submit_fail))
  2522. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  2523. res = json_object_get(val, "result");
  2524. err = json_object_get(val, "error");
  2525. if (!QUIET) {
  2526. if (opt_worktime) {
  2527. char workclone[20];
  2528. struct tm _tm;
  2529. struct tm *tm, tm_getwork, tm_submit_reply;
  2530. tm = &_tm;
  2531. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  2532. (struct timeval *)&(work->tv_getwork));
  2533. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  2534. (struct timeval *)&(work->tv_getwork_reply));
  2535. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  2536. (struct timeval *)&(work->tv_work_start));
  2537. double work_to_submit = tdiff(ptv_submit,
  2538. (struct timeval *)&(work->tv_work_found));
  2539. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  2540. int diffplaces = 3;
  2541. localtime_r(&(work->tv_getwork.tv_sec), tm);
  2542. memcpy(&tm_getwork, tm, sizeof(struct tm));
  2543. localtime_r(&(tv_submit_reply.tv_sec), tm);
  2544. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  2545. if (work->clone) {
  2546. sprintf(workclone, "C:%1.3f",
  2547. tdiff((struct timeval *)&(work->tv_cloned),
  2548. (struct timeval *)&(work->tv_getwork_reply)));
  2549. }
  2550. else
  2551. strcpy(workclone, "O");
  2552. if (work->work_difficulty < 1)
  2553. diffplaces = 6;
  2554. 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",
  2555. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  2556. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  2557. work->getwork_mode, diffplaces, work->work_difficulty,
  2558. tm_getwork.tm_hour, tm_getwork.tm_min,
  2559. tm_getwork.tm_sec, getwork_time, workclone,
  2560. getwork_to_work, work_time, work_to_submit, submit_time,
  2561. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  2562. tm_submit_reply.tm_sec);
  2563. }
  2564. }
  2565. share_result(val, res, err, work, resubmit, worktime);
  2566. if (!opt_realquiet)
  2567. print_status(thr_id);
  2568. if (!want_per_device_stats) {
  2569. char logline[256];
  2570. get_statline(logline, cgpu);
  2571. applog(LOG_INFO, "%s", logline);
  2572. }
  2573. json_decref(val);
  2574. rc = true;
  2575. out:
  2576. return rc;
  2577. }
  2578. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  2579. * rolling average per 10 minutes and if pools start getting more, it biases
  2580. * away from them to distribute work evenly. The share count is reset to the
  2581. * rolling average every 10 minutes to not send all work to one pool after it
  2582. * has been disabled/out for an extended period. */
  2583. static struct pool *select_balanced(struct pool *cp)
  2584. {
  2585. int i, lowest = cp->shares;
  2586. struct pool *ret = cp;
  2587. for (i = 0; i < total_pools; i++) {
  2588. struct pool *pool = pools[i];
  2589. if (pool->idle || pool->enabled != POOL_ENABLED)
  2590. continue;
  2591. if (pool->shares < lowest) {
  2592. lowest = pool->shares;
  2593. ret = pool;
  2594. }
  2595. }
  2596. ret->shares++;
  2597. return ret;
  2598. }
  2599. static bool pool_active(struct pool *, bool pinging);
  2600. static void pool_died(struct pool *);
  2601. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  2602. static inline struct pool *select_pool(bool lagging)
  2603. {
  2604. static int rotating_pool = 0;
  2605. struct pool *pool, *cp;
  2606. cp = current_pool();
  2607. retry:
  2608. if (pool_strategy == POOL_BALANCE)
  2609. {
  2610. pool = select_balanced(cp);
  2611. goto have_pool;
  2612. }
  2613. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only))
  2614. pool = cp;
  2615. else
  2616. pool = NULL;
  2617. while (!pool) {
  2618. if (++rotating_pool >= total_pools)
  2619. rotating_pool = 0;
  2620. pool = pools[rotating_pool];
  2621. if ((!pool->idle && pool->enabled == POOL_ENABLED) || pool == cp)
  2622. break;
  2623. pool = NULL;
  2624. }
  2625. have_pool:
  2626. if (cp != pool)
  2627. {
  2628. if (!pool_active(pool, false))
  2629. {
  2630. pool_died(pool);
  2631. goto retry;
  2632. }
  2633. pool_tclear(pool, &pool->idle);
  2634. }
  2635. return pool;
  2636. }
  2637. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  2638. static double target_diff(const unsigned char *target)
  2639. {
  2640. double targ = 0;
  2641. signed int i;
  2642. for (i = 31; i >= 0; --i)
  2643. targ = (targ * 0x100) + target[i];
  2644. return DIFFEXACTONE / (targ ?: 1);
  2645. }
  2646. /*
  2647. * Calculate the work share difficulty
  2648. */
  2649. static void calc_diff(struct work *work, int known)
  2650. {
  2651. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  2652. double difficulty;
  2653. if (!known) {
  2654. work->work_difficulty = target_diff(work->target);
  2655. } else
  2656. work->work_difficulty = known;
  2657. difficulty = work->work_difficulty;
  2658. pool_stats->last_diff = difficulty;
  2659. suffix_string((uint64_t)difficulty, work->pool->diff, 0);
  2660. if (difficulty == pool_stats->min_diff)
  2661. pool_stats->min_diff_count++;
  2662. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  2663. pool_stats->min_diff = difficulty;
  2664. pool_stats->min_diff_count = 1;
  2665. }
  2666. if (difficulty == pool_stats->max_diff)
  2667. pool_stats->max_diff_count++;
  2668. else if (difficulty > pool_stats->max_diff) {
  2669. pool_stats->max_diff = difficulty;
  2670. pool_stats->max_diff_count = 1;
  2671. }
  2672. }
  2673. static void get_benchmark_work(struct work *work)
  2674. {
  2675. // Use a random work block pulled from a pool
  2676. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  2677. size_t bench_size = sizeof(*work);
  2678. size_t work_size = sizeof(bench_block);
  2679. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  2680. memset(work, 0, sizeof(*work));
  2681. memcpy(work, &bench_block, min_size);
  2682. work->mandatory = true;
  2683. work->pool = pools[0];
  2684. gettimeofday(&(work->tv_getwork), NULL);
  2685. memcpy(&(work->tv_getwork_reply), &(work->tv_getwork), sizeof(struct timeval));
  2686. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  2687. calc_diff(work, 0);
  2688. }
  2689. static void wake_gws(void);
  2690. static void update_last_work(struct work *work)
  2691. {
  2692. if (!work->tmpl)
  2693. // Only save GBT jobs, since rollntime isn't coordinated well yet
  2694. return;
  2695. struct pool *pool = work->pool;
  2696. mutex_lock(&pool->last_work_lock);
  2697. if (pool->last_work_copy)
  2698. free_work(pool->last_work_copy);
  2699. pool->last_work_copy = copy_work(work);
  2700. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  2701. mutex_unlock(&pool->last_work_lock);
  2702. }
  2703. static
  2704. void gbt_req_target(json_t *req)
  2705. {
  2706. json_t *j;
  2707. json_t *n;
  2708. if (!request_target_str)
  2709. return;
  2710. j = json_object_get(req, "params");
  2711. if (!j)
  2712. {
  2713. n = json_array();
  2714. if (!n)
  2715. return;
  2716. if (json_object_set_new(req, "params", n))
  2717. goto erradd;
  2718. j = n;
  2719. }
  2720. n = json_array_get(j, 0);
  2721. if (!n)
  2722. {
  2723. n = json_object();
  2724. if (!n)
  2725. return;
  2726. if (json_array_append_new(j, n))
  2727. goto erradd;
  2728. }
  2729. j = n;
  2730. n = json_string(request_target_str);
  2731. if (!n)
  2732. return;
  2733. if (json_object_set_new(j, "target", n))
  2734. goto erradd;
  2735. return;
  2736. erradd:
  2737. json_decref(n);
  2738. }
  2739. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe)
  2740. {
  2741. char *rpc_req;
  2742. clean_work(work);
  2743. switch (proto) {
  2744. case PLP_GETWORK:
  2745. work->getwork_mode = GETWORK_MODE_POOL;
  2746. return strdup(getwork_req);
  2747. case PLP_GETBLOCKTEMPLATE:
  2748. work->getwork_mode = GETWORK_MODE_GBT;
  2749. work->tmpl_refcount = malloc(sizeof(*work->tmpl_refcount));
  2750. if (!work->tmpl_refcount)
  2751. return NULL;
  2752. work->tmpl = blktmpl_create();
  2753. if (!work->tmpl)
  2754. goto gbtfail2;
  2755. *work->tmpl_refcount = 1;
  2756. gbt_capabilities_t caps = blktmpl_addcaps(work->tmpl);
  2757. if (!caps)
  2758. goto gbtfail;
  2759. caps |= GBT_LONGPOLL;
  2760. json_t *req = blktmpl_request_jansson(caps, lpid);
  2761. if (!req)
  2762. goto gbtfail;
  2763. if (probe)
  2764. gbt_req_target(req);
  2765. rpc_req = json_dumps(req, 0);
  2766. if (!rpc_req)
  2767. goto gbtfail;
  2768. json_decref(req);
  2769. return rpc_req;
  2770. default:
  2771. return NULL;
  2772. }
  2773. return NULL;
  2774. gbtfail:
  2775. blktmpl_free(work->tmpl);
  2776. work->tmpl = NULL;
  2777. gbtfail2:
  2778. free(work->tmpl_refcount);
  2779. work->tmpl_refcount = NULL;
  2780. return NULL;
  2781. }
  2782. #define prepare_rpc_req(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, false)
  2783. #define prepare_rpc_req_probe(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, true)
  2784. static const char *pool_protocol_name(enum pool_protocol proto)
  2785. {
  2786. switch (proto) {
  2787. case PLP_GETBLOCKTEMPLATE:
  2788. return "getblocktemplate";
  2789. case PLP_GETWORK:
  2790. return "getwork";
  2791. default:
  2792. return "UNKNOWN";
  2793. }
  2794. }
  2795. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  2796. {
  2797. switch (proto) {
  2798. case PLP_GETBLOCKTEMPLATE:
  2799. if (want_getwork)
  2800. return PLP_GETWORK;
  2801. default:
  2802. return PLP_NONE;
  2803. }
  2804. }
  2805. static bool get_upstream_work(struct work *work, CURL *curl)
  2806. {
  2807. struct pool *pool = work->pool;
  2808. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  2809. struct timeval tv_elapsed;
  2810. json_t *val = NULL;
  2811. bool rc = false;
  2812. char *url;
  2813. enum pool_protocol proto;
  2814. char *rpc_req;
  2815. if (pool->proto == PLP_NONE)
  2816. pool->proto = PLP_GETBLOCKTEMPLATE;
  2817. tryagain:
  2818. rpc_req = prepare_rpc_req(work, pool->proto, NULL);
  2819. work->pool = pool;
  2820. if (!rpc_req)
  2821. return false;
  2822. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  2823. url = pool->rpc_url;
  2824. gettimeofday(&(work->tv_getwork), NULL);
  2825. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  2826. false, &work->rolltime, pool, false);
  2827. pool_stats->getwork_attempts++;
  2828. free(rpc_req);
  2829. if (likely(val)) {
  2830. rc = work_decode(pool, work, val);
  2831. if (unlikely(!rc))
  2832. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  2833. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  2834. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  2835. pool->proto = proto;
  2836. goto tryagain;
  2837. } else
  2838. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  2839. gettimeofday(&(work->tv_getwork_reply), NULL);
  2840. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  2841. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  2842. pool_stats->getwork_wait_rolling /= 1.63;
  2843. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  2844. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  2845. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  2846. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  2847. }
  2848. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  2849. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  2850. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  2851. }
  2852. pool_stats->getwork_calls++;
  2853. work->pool = pool;
  2854. work->longpoll = false;
  2855. calc_diff(work, 0);
  2856. total_getworks++;
  2857. pool->getwork_requested++;
  2858. if (rc)
  2859. update_last_work(work);
  2860. if (likely(val))
  2861. json_decref(val);
  2862. return rc;
  2863. }
  2864. #ifdef HAVE_CURSES
  2865. static void disable_curses(void)
  2866. {
  2867. if (curses_active_locked()) {
  2868. curses_active = false;
  2869. leaveok(logwin, false);
  2870. leaveok(statuswin, false);
  2871. leaveok(mainwin, false);
  2872. nocbreak();
  2873. echo();
  2874. delwin(logwin);
  2875. delwin(statuswin);
  2876. delwin(mainwin);
  2877. endwin();
  2878. #ifdef WIN32
  2879. // Move the cursor to after curses output.
  2880. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  2881. CONSOLE_SCREEN_BUFFER_INFO csbi;
  2882. COORD coord;
  2883. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  2884. coord.X = 0;
  2885. coord.Y = csbi.dwSize.Y - 1;
  2886. SetConsoleCursorPosition(hout, coord);
  2887. }
  2888. #endif
  2889. unlock_curses();
  2890. }
  2891. }
  2892. #endif
  2893. static void __kill_work(void)
  2894. {
  2895. struct thr_info *thr;
  2896. int i;
  2897. if (!successful_connect)
  2898. return;
  2899. applog(LOG_INFO, "Received kill message");
  2900. shutting_down = true;
  2901. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  2902. notifier_wake(submit_waiting_notifier);
  2903. applog(LOG_DEBUG, "Killing off watchpool thread");
  2904. /* Kill the watchpool thread */
  2905. thr = &thr_info[watchpool_thr_id];
  2906. thr_info_cancel(thr);
  2907. applog(LOG_DEBUG, "Killing off watchdog thread");
  2908. /* Kill the watchdog thread */
  2909. thr = &thr_info[watchdog_thr_id];
  2910. thr_info_cancel(thr);
  2911. applog(LOG_DEBUG, "Stopping mining threads");
  2912. /* Stop the mining threads*/
  2913. for (i = 0; i < mining_threads; i++) {
  2914. thr = &thr_info[i];
  2915. if (thr->cgpu->threads)
  2916. thr_info_freeze(thr);
  2917. thr->pause = true;
  2918. }
  2919. sleep(1);
  2920. applog(LOG_DEBUG, "Killing off mining threads");
  2921. /* Kill the mining threads*/
  2922. for (i = 0; i < mining_threads; i++) {
  2923. thr = &thr_info[i];
  2924. if (thr->cgpu->threads)
  2925. thr_info_cancel(thr);
  2926. }
  2927. applog(LOG_DEBUG, "Killing off stage thread");
  2928. /* Stop the others */
  2929. thr = &thr_info[stage_thr_id];
  2930. thr_info_cancel(thr);
  2931. applog(LOG_DEBUG, "Killing off API thread");
  2932. thr = &thr_info[api_thr_id];
  2933. thr_info_cancel(thr);
  2934. }
  2935. /* This should be the common exit path */
  2936. void kill_work(void)
  2937. {
  2938. __kill_work();
  2939. quit(0, "Shutdown signal received.");
  2940. }
  2941. static
  2942. #ifdef WIN32
  2943. #ifndef _WIN64
  2944. const
  2945. #endif
  2946. #endif
  2947. char **initial_args;
  2948. static void clean_up(void);
  2949. void app_restart(void)
  2950. {
  2951. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  2952. __kill_work();
  2953. clean_up();
  2954. #if defined(unix)
  2955. if (forkpid > 0) {
  2956. kill(forkpid, SIGTERM);
  2957. forkpid = 0;
  2958. }
  2959. #endif
  2960. execv(initial_args[0], initial_args);
  2961. applog(LOG_WARNING, "Failed to restart application");
  2962. }
  2963. static void sighandler(int __maybe_unused sig)
  2964. {
  2965. /* Restore signal handlers so we can still quit if kill_work fails */
  2966. sigaction(SIGTERM, &termhandler, NULL);
  2967. sigaction(SIGINT, &inthandler, NULL);
  2968. kill_work();
  2969. }
  2970. static void start_longpoll(void);
  2971. static void stop_longpoll(void);
  2972. /* Called with pool_lock held. Recruit an extra curl if none are available for
  2973. * this pool. */
  2974. static void recruit_curl(struct pool *pool)
  2975. {
  2976. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  2977. if (unlikely(!ce))
  2978. quit(1, "Failed to calloc in recruit_curl");
  2979. ce->curl = curl_easy_init();
  2980. if (unlikely(!ce->curl))
  2981. quit(1, "Failed to init in recruit_curl");
  2982. list_add(&ce->node, &pool->curlring);
  2983. pool->curls++;
  2984. applog(LOG_DEBUG, "Recruited curl %d for pool %d", pool->curls, pool->pool_no);
  2985. }
  2986. /* Grab an available curl if there is one. If not, then recruit extra curls
  2987. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  2988. * and there are already 5 curls in circulation. Limit total number to the
  2989. * number of mining threads per pool as well to prevent blasting a pool during
  2990. * network delays/outages. */
  2991. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  2992. {
  2993. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  2994. struct curl_ent *ce;
  2995. mutex_lock(&pool->pool_lock);
  2996. retry:
  2997. if (!pool->curls)
  2998. recruit_curl(pool);
  2999. else if (list_empty(&pool->curlring)) {
  3000. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  3001. if (!blocking) {
  3002. mutex_unlock(&pool->pool_lock);
  3003. return NULL;
  3004. }
  3005. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  3006. goto retry;
  3007. } else
  3008. recruit_curl(pool);
  3009. }
  3010. ce = list_entry(pool->curlring.next, struct curl_ent, node);
  3011. list_del(&ce->node);
  3012. mutex_unlock(&pool->pool_lock);
  3013. return ce;
  3014. }
  3015. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  3016. {
  3017. return pop_curl_entry3(pool, blocking ? 1 : 0);
  3018. }
  3019. __maybe_unused
  3020. static struct curl_ent *pop_curl_entry(struct pool *pool)
  3021. {
  3022. return pop_curl_entry3(pool, 1);
  3023. }
  3024. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  3025. {
  3026. mutex_lock(&pool->pool_lock);
  3027. if (!ce || !ce->curl)
  3028. quit(1, "Attempted to add NULL in push_curl_entry");
  3029. list_add_tail(&ce->node, &pool->curlring);
  3030. gettimeofday(&ce->tv, NULL);
  3031. pthread_cond_broadcast(&pool->cr_cond);
  3032. mutex_unlock(&pool->pool_lock);
  3033. }
  3034. bool stale_work(struct work *work, bool share);
  3035. static inline bool should_roll(struct work *work)
  3036. {
  3037. struct timeval now;
  3038. time_t expiry;
  3039. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  3040. return false;
  3041. if (stale_work(work, false))
  3042. return false;
  3043. if (work->rolltime > opt_scantime)
  3044. expiry = work->rolltime;
  3045. else
  3046. expiry = opt_scantime;
  3047. expiry = expiry * 2 / 3;
  3048. /* We shouldn't roll if we're unlikely to get one shares' duration
  3049. * work out of doing so */
  3050. gettimeofday(&now, NULL);
  3051. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  3052. return false;
  3053. return true;
  3054. }
  3055. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  3056. * reject blocks as invalid. */
  3057. static inline bool can_roll(struct work *work)
  3058. {
  3059. if (work->stratum)
  3060. return false;
  3061. if (!(work->pool && !work->clone))
  3062. return false;
  3063. if (work->tmpl) {
  3064. if (stale_work(work, false))
  3065. return false;
  3066. return blkmk_work_left(work->tmpl);
  3067. }
  3068. return (work->rolltime &&
  3069. work->rolls < 7000 && !stale_work(work, false));
  3070. }
  3071. static void roll_work(struct work *work)
  3072. {
  3073. if (work->tmpl) {
  3074. if (blkmk_get_data(work->tmpl, work->data, 80, time(NULL), NULL, &work->dataid) < 76)
  3075. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  3076. swap32yes(work->data, work->data, 80 / 4);
  3077. calc_midstate(work);
  3078. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  3079. } else {
  3080. uint32_t *work_ntime;
  3081. uint32_t ntime;
  3082. work_ntime = (uint32_t *)(work->data + 68);
  3083. ntime = be32toh(*work_ntime);
  3084. ntime++;
  3085. *work_ntime = htobe32(ntime);
  3086. applog(LOG_DEBUG, "Successfully rolled time header in work");
  3087. }
  3088. local_work++;
  3089. work->rolls++;
  3090. work->blk.nonce = 0;
  3091. /* This is now a different work item so it needs a different ID for the
  3092. * hashtable */
  3093. work->id = total_work++;
  3094. }
  3095. /* Duplicates any dynamically allocated arrays within the work struct to
  3096. * prevent a copied work struct from freeing ram belonging to another struct */
  3097. void __copy_work(struct work *work, struct work *base_work)
  3098. {
  3099. int id = work->id;
  3100. clean_work(work);
  3101. memcpy(work, base_work, sizeof(struct work));
  3102. /* Keep the unique new id assigned during make_work to prevent copied
  3103. * work from having the same id. */
  3104. work->id = id;
  3105. if (base_work->sessionid)
  3106. work->sessionid = strdup(base_work->sessionid);
  3107. if (base_work->job_id)
  3108. work->job_id = strdup(base_work->job_id);
  3109. if (base_work->nonce2)
  3110. work->nonce2 = strdup(base_work->nonce2);
  3111. if (base_work->ntime)
  3112. work->ntime = strdup(base_work->ntime);
  3113. if (base_work->tmpl) {
  3114. struct pool *pool = work->pool;
  3115. mutex_lock(&pool->pool_lock);
  3116. ++*work->tmpl_refcount;
  3117. mutex_unlock(&pool->pool_lock);
  3118. }
  3119. }
  3120. /* Generates a copy of an existing work struct, creating fresh heap allocations
  3121. * for all dynamically allocated arrays within the struct */
  3122. struct work *copy_work(struct work *base_work)
  3123. {
  3124. struct work *work = make_work();
  3125. __copy_work(work, base_work);
  3126. return work;
  3127. }
  3128. static struct work *make_clone(struct work *work)
  3129. {
  3130. struct work *work_clone = copy_work(work);
  3131. work_clone->clone = true;
  3132. gettimeofday((struct timeval *)&(work_clone->tv_cloned), NULL);
  3133. work_clone->longpoll = false;
  3134. work_clone->mandatory = false;
  3135. /* Make cloned work appear slightly older to bias towards keeping the
  3136. * master work item which can be further rolled */
  3137. work_clone->tv_staged.tv_sec -= 1;
  3138. return work_clone;
  3139. }
  3140. static void stage_work(struct work *work);
  3141. static bool clone_available(void)
  3142. {
  3143. struct work *work_clone = NULL, *work, *tmp;
  3144. bool cloned = false;
  3145. mutex_lock(stgd_lock);
  3146. if (!staged_rollable)
  3147. goto out_unlock;
  3148. HASH_ITER(hh, staged_work, work, tmp) {
  3149. if (can_roll(work) && should_roll(work)) {
  3150. roll_work(work);
  3151. work_clone = make_clone(work);
  3152. roll_work(work);
  3153. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  3154. cloned = true;
  3155. break;
  3156. }
  3157. }
  3158. out_unlock:
  3159. mutex_unlock(stgd_lock);
  3160. if (cloned)
  3161. stage_work(work_clone);
  3162. return cloned;
  3163. }
  3164. static void pool_died(struct pool *pool)
  3165. {
  3166. if (!pool_tset(pool, &pool->idle)) {
  3167. gettimeofday(&pool->tv_idle, NULL);
  3168. if (pool == current_pool()) {
  3169. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  3170. switch_pools(NULL);
  3171. } else
  3172. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  3173. }
  3174. }
  3175. bool stale_work(struct work *work, bool share)
  3176. {
  3177. unsigned work_expiry;
  3178. struct pool *pool;
  3179. uint32_t block_id;
  3180. unsigned getwork_delay;
  3181. block_id = ((uint32_t*)work->data)[1];
  3182. pool = work->pool;
  3183. /* Technically the rolltime should be correct but some pools
  3184. * advertise a broken expire= that is lower than a meaningful
  3185. * scantime */
  3186. if (work->rolltime >= opt_scantime || work->tmpl)
  3187. work_expiry = work->rolltime;
  3188. else
  3189. work_expiry = opt_expiry;
  3190. unsigned max_expiry = (have_longpoll ? opt_expiry_lp : opt_expiry);
  3191. if (work_expiry > max_expiry)
  3192. work_expiry = max_expiry;
  3193. if (share) {
  3194. /* If the share isn't on this pool's latest block, it's stale */
  3195. if (pool->block_id && pool->block_id != block_id)
  3196. {
  3197. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  3198. return true;
  3199. }
  3200. /* If the pool doesn't want old shares, then any found in work before
  3201. * the most recent longpoll is stale */
  3202. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  3203. {
  3204. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  3205. return true;
  3206. }
  3207. } else {
  3208. /* If this work isn't for the latest Bitcoin block, it's stale */
  3209. /* But only care about the current pool if failover-only */
  3210. if (enabled_pools <= 1 || opt_fail_only) {
  3211. if (pool->block_id && block_id != pool->block_id)
  3212. {
  3213. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 1 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  3214. return true;
  3215. }
  3216. } else {
  3217. if (block_id != current_block_id)
  3218. {
  3219. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 0 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  3220. return true;
  3221. }
  3222. }
  3223. /* If the pool has asked us to restart since this work, it's stale */
  3224. if (work->work_restart_id != pool->work_restart_id)
  3225. {
  3226. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  3227. return true;
  3228. }
  3229. if (pool->has_stratum && work->job_id) {
  3230. bool same_job = true;
  3231. mutex_lock(&pool->pool_lock);
  3232. if (strcmp(work->job_id, pool->swork.job_id))
  3233. same_job = false;
  3234. mutex_unlock(&pool->pool_lock);
  3235. if (!same_job) {
  3236. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  3237. return true;
  3238. }
  3239. }
  3240. /* Factor in the average getwork delay of this pool, rounding it up to
  3241. * the nearest second */
  3242. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  3243. if (unlikely(work_expiry <= getwork_delay + 5))
  3244. work_expiry = 5;
  3245. else
  3246. work_expiry -= getwork_delay;
  3247. }
  3248. double elapsed_since_staged = difftime(time(NULL), work->tv_staged.tv_sec);
  3249. if (elapsed_since_staged > work_expiry) {
  3250. applog(LOG_DEBUG, "%s stale due to expiry (%.0f >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  3251. return true;
  3252. }
  3253. /* If the user only wants strict failover, any work from a pool other than
  3254. * the current one is always considered stale */
  3255. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  3256. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  3257. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  3258. return true;
  3259. }
  3260. return false;
  3261. }
  3262. static void regen_hash(struct work *work)
  3263. {
  3264. hash_data(work->hash, work->data);
  3265. }
  3266. static void check_solve(struct work *work)
  3267. {
  3268. if (opt_scrypt)
  3269. scrypt_outputhash(work);
  3270. else
  3271. regen_hash(work);
  3272. work->block = solves_block(work);
  3273. if (unlikely(work->block)) {
  3274. work->pool->solved++;
  3275. found_blocks++;
  3276. work->mandatory = true;
  3277. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  3278. }
  3279. }
  3280. static void submit_discard_share2(const char *reason, struct work *work)
  3281. {
  3282. sharelog(reason, work);
  3283. mutex_lock(&stats_lock);
  3284. ++total_stale;
  3285. ++(work->pool->stale_shares);
  3286. total_diff_stale += work->work_difficulty;
  3287. work->pool->diff_stale += work->work_difficulty;
  3288. mutex_unlock(&stats_lock);
  3289. }
  3290. static void submit_discard_share(struct work *work)
  3291. {
  3292. submit_discard_share2("discard", work);
  3293. }
  3294. struct submit_work_state {
  3295. struct work *work;
  3296. bool resubmit;
  3297. struct curl_ent *ce;
  3298. int failures;
  3299. time_t staleexpire;
  3300. char *s;
  3301. struct timeval tv_submit;
  3302. struct submit_work_state *next;
  3303. };
  3304. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  3305. {
  3306. long *timeout = userp;
  3307. *timeout = timeout_ms;
  3308. return 0;
  3309. }
  3310. static void sws_has_ce(struct submit_work_state *sws)
  3311. {
  3312. struct pool *pool = sws->work->pool;
  3313. sws->s = submit_upstream_work_request(sws->work);
  3314. gettimeofday(&sws->tv_submit, NULL);
  3315. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  3316. }
  3317. static struct submit_work_state *begin_submission(struct work *work)
  3318. {
  3319. struct pool *pool;
  3320. struct submit_work_state *sws = NULL;
  3321. pool = work->pool;
  3322. sws = malloc(sizeof(*sws));
  3323. *sws = (struct submit_work_state){
  3324. .work = work,
  3325. };
  3326. if (work->stratum && pool->sock == INVSOCK) {
  3327. applog(LOG_WARNING, "Share found for dead stratum pool %u, discarding", pool->pool_no);
  3328. submit_discard_share2("disconnect", work);
  3329. goto out;
  3330. }
  3331. check_solve(work);
  3332. if (stale_work(work, true)) {
  3333. work->stale = true;
  3334. if (opt_submit_stale)
  3335. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  3336. else if (pool->submit_old)
  3337. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  3338. else {
  3339. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  3340. submit_discard_share(work);
  3341. goto out;
  3342. }
  3343. sws->staleexpire = time(NULL) + 300;
  3344. }
  3345. if (work->stratum) {
  3346. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  3347. uint32_t nonce;
  3348. char *noncehex;
  3349. char *s;
  3350. sshare->sshare_time = time(NULL);
  3351. sshare->work = copy_work(work);
  3352. nonce = *((uint32_t *)(work->data + 76));
  3353. noncehex = bin2hex((const unsigned char *)&nonce, 4);
  3354. s = malloc(1024);
  3355. mutex_lock(&sshare_lock);
  3356. /* Give the stratum share a unique id */
  3357. sshare->id = swork_id++;
  3358. HASH_ADD_INT(stratum_shares, id, sshare);
  3359. sprintf(s, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  3360. pool->rpc_user, work->job_id, work->nonce2, work->ntime, noncehex, sshare->id);
  3361. mutex_unlock(&sshare_lock);
  3362. free(noncehex);
  3363. sws->s = s;
  3364. } else {
  3365. /* submit solution to bitcoin via JSON-RPC */
  3366. sws->ce = pop_curl_entry2(pool, false);
  3367. if (sws->ce) {
  3368. sws_has_ce(sws);
  3369. } else {
  3370. sws->next = pool->sws_waiting_on_curl;
  3371. pool->sws_waiting_on_curl = sws;
  3372. if (sws->next)
  3373. applog(LOG_DEBUG, "submit_thread queuing submission");
  3374. else
  3375. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  3376. }
  3377. }
  3378. return sws;
  3379. out:
  3380. free(sws);
  3381. return NULL;
  3382. }
  3383. static bool retry_submission(struct submit_work_state *sws)
  3384. {
  3385. struct work *work = sws->work;
  3386. struct pool *pool = work->pool;
  3387. sws->resubmit = true;
  3388. if ((!work->stale) && stale_work(work, true)) {
  3389. work->stale = true;
  3390. if (opt_submit_stale)
  3391. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  3392. else if (pool->submit_old)
  3393. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  3394. else {
  3395. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  3396. submit_discard_share(work);
  3397. return false;
  3398. }
  3399. sws->staleexpire = time(NULL) + 300;
  3400. }
  3401. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  3402. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  3403. submit_discard_share(work);
  3404. return false;
  3405. }
  3406. else if (work->stale) {
  3407. if (unlikely(opt_retries < 0 && sws->staleexpire <= time(NULL))) {
  3408. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  3409. submit_discard_share(work);
  3410. return false;
  3411. }
  3412. }
  3413. /* pause, then restart work-request loop */
  3414. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  3415. gettimeofday(&sws->tv_submit, NULL);
  3416. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  3417. return true;
  3418. }
  3419. static void free_sws(struct submit_work_state *sws)
  3420. {
  3421. free(sws->s);
  3422. free_work(sws->work);
  3423. free(sws);
  3424. }
  3425. static void *submit_work_thread(__maybe_unused void *userdata)
  3426. {
  3427. int wip = 0;
  3428. CURLM *curlm;
  3429. long curlm_timeout_ms = -1;
  3430. struct submit_work_state *sws, **swsp;
  3431. struct submit_work_state *write_sws = NULL;
  3432. unsigned tsreduce = 0;
  3433. pthread_detach(pthread_self());
  3434. RenameThread("submit_work");
  3435. applog(LOG_DEBUG, "Creating extra submit work thread");
  3436. curlm = curl_multi_init();
  3437. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  3438. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_ms);
  3439. fd_set rfds, wfds, efds;
  3440. int maxfd;
  3441. struct timeval timeout, *timeoutp;
  3442. int n;
  3443. CURLMsg *cm;
  3444. FD_ZERO(&rfds);
  3445. while (1) {
  3446. mutex_lock(&submitting_lock);
  3447. total_submitting -= tsreduce;
  3448. tsreduce = 0;
  3449. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  3450. notifier_read(submit_waiting_notifier);
  3451. }
  3452. while (!list_empty(&submit_waiting)) {
  3453. struct work *work = list_entry(submit_waiting.next, struct work, list);
  3454. list_del(&work->list);
  3455. if ( (sws = begin_submission(work)) ) {
  3456. if (sws->ce)
  3457. curl_multi_add_handle(curlm, sws->ce->curl);
  3458. else if (sws->s) {
  3459. sws->next = write_sws;
  3460. write_sws = sws;
  3461. }
  3462. ++wip;
  3463. }
  3464. else {
  3465. --total_submitting;
  3466. free_work(work);
  3467. }
  3468. }
  3469. if (unlikely(shutting_down && !wip))
  3470. break;
  3471. mutex_unlock(&submitting_lock);
  3472. FD_ZERO(&rfds);
  3473. FD_ZERO(&wfds);
  3474. FD_ZERO(&efds);
  3475. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  3476. if (curlm_timeout_ms >= 0) {
  3477. timeout.tv_sec = curlm_timeout_ms / 1000;
  3478. timeout.tv_usec = (curlm_timeout_ms % 1000) * 1000;
  3479. timeoutp = &timeout;
  3480. } else
  3481. timeoutp = NULL;
  3482. for (swsp = &write_sws; (sws = *swsp); ) {
  3483. int fd = sws->work->pool->sock;
  3484. if (fd == INVSOCK) {
  3485. applog(LOG_WARNING, "Stratum pool %u died while share waiting to submit, discarding", sws->work->pool->pool_no);
  3486. submit_discard_share2("disconnect", sws->work);
  3487. --wip;
  3488. ++tsreduce;
  3489. *swsp = sws->next;
  3490. free_sws(sws);
  3491. continue;
  3492. }
  3493. FD_SET(fd, &wfds);
  3494. if (fd > maxfd)
  3495. maxfd = fd;
  3496. swsp = &sws->next;
  3497. }
  3498. if (tsreduce) {
  3499. mutex_lock(&submitting_lock);
  3500. total_submitting -= tsreduce;
  3501. mutex_unlock(&submitting_lock);
  3502. tsreduce = 0;
  3503. }
  3504. FD_SET(submit_waiting_notifier[0], &rfds);
  3505. if (submit_waiting_notifier[0] > maxfd)
  3506. maxfd = submit_waiting_notifier[0];
  3507. if (select(maxfd+1, &rfds, &wfds, &efds, timeoutp) < 0) {
  3508. FD_ZERO(&rfds);
  3509. continue;
  3510. }
  3511. for (swsp = &write_sws; (sws = *swsp); ) {
  3512. int fd = sws->work->pool->sock;
  3513. if (fd == -1 || !FD_ISSET(fd, &wfds)) {
  3514. swsp = &sws->next;
  3515. continue;
  3516. }
  3517. struct pool *pool = sws->work->pool;
  3518. char *s = sws->s;
  3519. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  3520. if (likely(stratum_send(pool, s, strlen(s)))) {
  3521. if (pool_tclear(pool, &pool->submit_fail))
  3522. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  3523. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  3524. } else if (!pool_tset(pool, &pool->submit_fail)) {
  3525. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  3526. total_ro++;
  3527. pool->remotefail_occasions++;
  3528. }
  3529. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  3530. FD_CLR(fd, &wfds);
  3531. // Delete sws for this submission, since we're done with it
  3532. *swsp = sws->next;
  3533. free_sws(sws);
  3534. --wip;
  3535. }
  3536. curl_multi_perform(curlm, &n);
  3537. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  3538. if (cm->msg == CURLMSG_DONE)
  3539. {
  3540. bool finished;
  3541. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  3542. curl_multi_remove_handle(curlm, cm->easy_handle);
  3543. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  3544. if (!finished) {
  3545. if (retry_submission(sws))
  3546. curl_multi_add_handle(curlm, sws->ce->curl);
  3547. else
  3548. finished = true;
  3549. }
  3550. if (finished) {
  3551. --wip;
  3552. ++tsreduce;
  3553. struct pool *pool = sws->work->pool;
  3554. if (pool->sws_waiting_on_curl) {
  3555. pool->sws_waiting_on_curl->ce = sws->ce;
  3556. sws_has_ce(pool->sws_waiting_on_curl);
  3557. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  3558. curl_multi_add_handle(curlm, sws->ce->curl);
  3559. } else {
  3560. push_curl_entry(sws->ce, sws->work->pool);
  3561. }
  3562. free_sws(sws);
  3563. }
  3564. }
  3565. }
  3566. }
  3567. assert(!write_sws);
  3568. mutex_unlock(&submitting_lock);
  3569. curl_multi_cleanup(curlm);
  3570. applog(LOG_DEBUG, "submit_work thread exiting");
  3571. return NULL;
  3572. }
  3573. /* Find the pool that currently has the highest priority */
  3574. static struct pool *priority_pool(int choice)
  3575. {
  3576. struct pool *ret = NULL;
  3577. int i;
  3578. for (i = 0; i < total_pools; i++) {
  3579. struct pool *pool = pools[i];
  3580. if (pool->prio == choice) {
  3581. ret = pool;
  3582. break;
  3583. }
  3584. }
  3585. if (unlikely(!ret)) {
  3586. applog(LOG_ERR, "WTF No pool %d found!", choice);
  3587. return pools[choice];
  3588. }
  3589. return ret;
  3590. }
  3591. int prioritize_pools(char *param, int *pid)
  3592. {
  3593. char *ptr, *next;
  3594. int i, pr, prio = 0;
  3595. if (total_pools == 0) {
  3596. return MSG_NOPOOL;
  3597. }
  3598. if (param == NULL || *param == '\0') {
  3599. return MSG_MISPID;
  3600. }
  3601. bool pools_changed[total_pools];
  3602. int new_prio[total_pools];
  3603. for (i = 0; i < total_pools; ++i)
  3604. pools_changed[i] = false;
  3605. next = param;
  3606. while (next && *next) {
  3607. ptr = next;
  3608. next = strchr(ptr, ',');
  3609. if (next)
  3610. *(next++) = '\0';
  3611. i = atoi(ptr);
  3612. if (i < 0 || i >= total_pools) {
  3613. *pid = i;
  3614. return MSG_INVPID;
  3615. }
  3616. if (pools_changed[i]) {
  3617. *pid = i;
  3618. return MSG_DUPPID;
  3619. }
  3620. pools_changed[i] = true;
  3621. new_prio[i] = prio++;
  3622. }
  3623. // Only change them if no errors
  3624. for (i = 0; i < total_pools; i++) {
  3625. if (pools_changed[i])
  3626. pools[i]->prio = new_prio[i];
  3627. }
  3628. // In priority order, cycle through the unchanged pools and append them
  3629. for (pr = 0; pr < total_pools; pr++)
  3630. for (i = 0; i < total_pools; i++) {
  3631. if (!pools_changed[i] && pools[i]->prio == pr) {
  3632. pools[i]->prio = prio++;
  3633. pools_changed[i] = true;
  3634. break;
  3635. }
  3636. }
  3637. if (current_pool()->prio)
  3638. switch_pools(NULL);
  3639. return MSG_POOLPRIO;
  3640. }
  3641. void validate_pool_priorities(void)
  3642. {
  3643. // TODO: this should probably do some sort of logging
  3644. int i, j;
  3645. bool used[total_pools];
  3646. bool valid[total_pools];
  3647. for (i = 0; i < total_pools; i++)
  3648. used[i] = valid[i] = false;
  3649. for (i = 0; i < total_pools; i++) {
  3650. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  3651. if (!used[pools[i]->prio]) {
  3652. valid[i] = true;
  3653. used[pools[i]->prio] = true;
  3654. }
  3655. }
  3656. }
  3657. for (i = 0; i < total_pools; i++) {
  3658. if (!valid[i]) {
  3659. for (j = 0; j < total_pools; j++) {
  3660. if (!used[j]) {
  3661. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  3662. pools[i]->prio = j;
  3663. used[j] = true;
  3664. break;
  3665. }
  3666. }
  3667. }
  3668. }
  3669. }
  3670. void switch_pools(struct pool *selected)
  3671. {
  3672. struct pool *pool, *last_pool;
  3673. int i, pool_no, next_pool;
  3674. mutex_lock(&control_lock);
  3675. last_pool = currentpool;
  3676. pool_no = currentpool->pool_no;
  3677. /* Switch selected to pool number 0 and move the rest down */
  3678. if (selected) {
  3679. if (selected->prio != 0) {
  3680. for (i = 0; i < total_pools; i++) {
  3681. pool = pools[i];
  3682. if (pool->prio < selected->prio)
  3683. pool->prio++;
  3684. }
  3685. selected->prio = 0;
  3686. }
  3687. }
  3688. switch (pool_strategy) {
  3689. /* Both of these set to the master pool */
  3690. case POOL_BALANCE:
  3691. case POOL_FAILOVER:
  3692. case POOL_LOADBALANCE:
  3693. for (i = 0; i < total_pools; i++) {
  3694. pool = priority_pool(i);
  3695. if (!pool->idle && pool->enabled == POOL_ENABLED) {
  3696. pool_no = pool->pool_no;
  3697. break;
  3698. }
  3699. }
  3700. break;
  3701. /* Both of these simply increment and cycle */
  3702. case POOL_ROUNDROBIN:
  3703. case POOL_ROTATE:
  3704. if (selected && !selected->idle) {
  3705. pool_no = selected->pool_no;
  3706. break;
  3707. }
  3708. next_pool = pool_no;
  3709. /* Select the next alive pool */
  3710. for (i = 1; i < total_pools; i++) {
  3711. next_pool++;
  3712. if (next_pool >= total_pools)
  3713. next_pool = 0;
  3714. pool = pools[next_pool];
  3715. if (!pool->idle && pool->enabled == POOL_ENABLED) {
  3716. pool_no = next_pool;
  3717. break;
  3718. }
  3719. }
  3720. break;
  3721. default:
  3722. break;
  3723. }
  3724. currentpool = pools[pool_no];
  3725. pool = currentpool;
  3726. mutex_unlock(&control_lock);
  3727. /* Set the lagging flag to avoid pool not providing work fast enough
  3728. * messages in failover only mode since we have to get all fresh work
  3729. * as in restart_threads */
  3730. if (opt_fail_only)
  3731. pool_tset(pool, &pool->lagging);
  3732. if (pool != last_pool)
  3733. {
  3734. pool->block_id = 0;
  3735. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  3736. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  3737. }
  3738. }
  3739. mutex_lock(&lp_lock);
  3740. pthread_cond_broadcast(&lp_cond);
  3741. mutex_unlock(&lp_lock);
  3742. }
  3743. static void discard_work(struct work *work)
  3744. {
  3745. if (!work->clone && !work->rolls && !work->mined) {
  3746. if (work->pool)
  3747. work->pool->discarded_work++;
  3748. total_discarded++;
  3749. applog(LOG_DEBUG, "Discarded work");
  3750. } else
  3751. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  3752. free_work(work);
  3753. }
  3754. static void wake_gws(void)
  3755. {
  3756. mutex_lock(stgd_lock);
  3757. pthread_cond_signal(&gws_cond);
  3758. mutex_unlock(stgd_lock);
  3759. }
  3760. static void discard_stale(void)
  3761. {
  3762. struct work *work, *tmp;
  3763. int stale = 0;
  3764. mutex_lock(stgd_lock);
  3765. HASH_ITER(hh, staged_work, work, tmp) {
  3766. if (stale_work(work, false)) {
  3767. HASH_DEL(staged_work, work);
  3768. discard_work(work);
  3769. stale++;
  3770. }
  3771. }
  3772. pthread_cond_signal(&gws_cond);
  3773. mutex_unlock(stgd_lock);
  3774. if (stale)
  3775. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  3776. }
  3777. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  3778. {
  3779. bool rv;
  3780. struct timeval tv, orig;
  3781. ldiv_t d;
  3782. d = ldiv(ustime, 1000000);
  3783. tv = (struct timeval){
  3784. .tv_sec = d.quot,
  3785. .tv_usec = d.rem,
  3786. };
  3787. orig = work->tv_staged;
  3788. timersub(&orig, &tv, &work->tv_staged);
  3789. rv = stale_work(work, share);
  3790. work->tv_staged = orig;
  3791. return rv;
  3792. }
  3793. static void restart_threads(void)
  3794. {
  3795. struct pool *cp = current_pool();
  3796. int i;
  3797. struct thr_info *thr;
  3798. /* Artificially set the lagging flag to avoid pool not providing work
  3799. * fast enough messages after every long poll */
  3800. pool_tset(cp, &cp->lagging);
  3801. /* Discard staged work that is now stale */
  3802. discard_stale();
  3803. for (i = 0; i < mining_threads; i++)
  3804. {
  3805. thr = &thr_info[i];
  3806. thr->work_restart = true;
  3807. }
  3808. for (i = 0; i < mining_threads; i++)
  3809. {
  3810. thr = &thr_info[i];
  3811. notifier_wake(thr->work_restart_notifier);
  3812. }
  3813. }
  3814. static char *blkhashstr(unsigned char *hash)
  3815. {
  3816. unsigned char hash_swap[32];
  3817. swap256(hash_swap, hash);
  3818. swap32tole(hash_swap, hash_swap, 32 / 4);
  3819. return bin2hex(hash_swap, 32);
  3820. }
  3821. static void set_curblock(char *hexstr, unsigned char *hash)
  3822. {
  3823. unsigned char hash_swap[32];
  3824. char *old_hash;
  3825. current_block_id = ((uint32_t*)hash)[0];
  3826. strcpy(current_block, hexstr);
  3827. swap256(hash_swap, hash);
  3828. swap32tole(hash_swap, hash_swap, 32 / 4);
  3829. /* Don't free current_hash directly to avoid dereferencing when read
  3830. * elsewhere - and update block_timeval inside the same lock */
  3831. mutex_lock(&ch_lock);
  3832. gettimeofday(&block_timeval, NULL);
  3833. __update_block_title(hash_swap);
  3834. old_hash = current_fullhash;
  3835. current_fullhash = bin2hex(hash_swap, 32);
  3836. free(old_hash);
  3837. mutex_unlock(&ch_lock);
  3838. get_timestamp(blocktime, &block_timeval);
  3839. applog(LOG_INFO, "New block: %s diff %s", current_hash, block_diff);
  3840. }
  3841. /* Search to see if this string is from a block that has been seen before */
  3842. static bool block_exists(char *hexstr)
  3843. {
  3844. struct block *s;
  3845. rd_lock(&blk_lock);
  3846. HASH_FIND_STR(blocks, hexstr, s);
  3847. rd_unlock(&blk_lock);
  3848. if (s)
  3849. return true;
  3850. return false;
  3851. }
  3852. /* Tests if this work is from a block that has been seen before */
  3853. static inline bool from_existing_block(struct work *work)
  3854. {
  3855. char *hexstr = bin2hex(work->data + 8, 18);
  3856. bool ret;
  3857. ret = block_exists(hexstr);
  3858. free(hexstr);
  3859. return ret;
  3860. }
  3861. static int block_sort(struct block *blocka, struct block *blockb)
  3862. {
  3863. return blocka->block_no - blockb->block_no;
  3864. }
  3865. static void set_blockdiff(const struct work *work)
  3866. {
  3867. unsigned char target[32];
  3868. uint64_t diff64;
  3869. real_block_target(target, work->data);
  3870. diff64 = target_diff(target);
  3871. suffix_string(diff64, block_diff, 0);
  3872. }
  3873. static bool test_work_current(struct work *work)
  3874. {
  3875. bool ret = true;
  3876. char *hexstr;
  3877. if (work->mandatory)
  3878. return ret;
  3879. uint32_t block_id = ((uint32_t*)(work->data))[1];
  3880. /* Hack to work around dud work sneaking into test */
  3881. hexstr = bin2hex(work->data + 8, 18);
  3882. if (!strncmp(hexstr, "000000000000000000000000000000000000", 36))
  3883. goto out_free;
  3884. /* Search to see if this block exists yet and if not, consider it a
  3885. * new block and set the current block details to this one */
  3886. if (!block_exists(hexstr)) {
  3887. struct block *s = calloc(sizeof(struct block), 1);
  3888. int deleted_block = 0;
  3889. ret = false;
  3890. if (unlikely(!s))
  3891. quit (1, "test_work_current OOM");
  3892. strcpy(s->hash, hexstr);
  3893. s->block_no = new_blocks++;
  3894. wr_lock(&blk_lock);
  3895. /* Only keep the last hour's worth of blocks in memory since
  3896. * work from blocks before this is virtually impossible and we
  3897. * want to prevent memory usage from continually rising */
  3898. if (HASH_COUNT(blocks) > 6) {
  3899. struct block *oldblock;
  3900. HASH_SORT(blocks, block_sort);
  3901. oldblock = blocks;
  3902. deleted_block = oldblock->block_no;
  3903. HASH_DEL(blocks, oldblock);
  3904. free(oldblock);
  3905. }
  3906. HASH_ADD_STR(blocks, hash, s);
  3907. set_blockdiff(work);
  3908. wr_unlock(&blk_lock);
  3909. work->pool->block_id = block_id;
  3910. if (deleted_block)
  3911. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  3912. template_nonce = 0;
  3913. set_curblock(hexstr, &work->data[4]);
  3914. if (unlikely(new_blocks == 1))
  3915. goto out_free;
  3916. if (!work->stratum) {
  3917. if (work->longpoll) {
  3918. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  3919. work->pool->pool_no);
  3920. } else if (have_longpoll)
  3921. applog(LOG_NOTICE, "New block detected on network before longpoll");
  3922. else
  3923. applog(LOG_NOTICE, "New block detected on network");
  3924. }
  3925. restart_threads();
  3926. } else {
  3927. bool restart = false;
  3928. struct pool *curpool = NULL;
  3929. if (unlikely(work->pool->block_id != block_id)) {
  3930. bool was_active = work->pool->block_id != 0;
  3931. work->pool->block_id = block_id;
  3932. if (!work->longpoll)
  3933. update_last_work(work);
  3934. if (was_active) { // Pool actively changed block
  3935. if (work->pool == (curpool = current_pool()))
  3936. restart = true;
  3937. if (block_id == current_block_id) {
  3938. // Caught up, only announce if this pool is the one in use
  3939. if (restart)
  3940. applog(LOG_NOTICE, "%s %d caught up to new block",
  3941. work->longpoll ? "Longpoll from pool" : "Pool",
  3942. work->pool->pool_no);
  3943. } else {
  3944. // Switched to a block we know, but not the latest... why?
  3945. // This might detect pools trying to double-spend or 51%,
  3946. // but let's not make any accusations until it's had time
  3947. // in the real world.
  3948. free(hexstr);
  3949. hexstr = blkhashstr(&work->data[4]);
  3950. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  3951. work->longpoll ? "Longpoll from pool" : "Pool",
  3952. work->pool->pool_no,
  3953. hexstr);
  3954. }
  3955. }
  3956. }
  3957. if (work->longpoll) {
  3958. ++work->pool->work_restart_id;
  3959. update_last_work(work);
  3960. if ((!restart) && work->pool == current_pool()) {
  3961. applog(
  3962. (opt_quiet_work_updates ? LOG_DEBUG : LOG_NOTICE),
  3963. "Longpoll from pool %d requested work update",
  3964. work->pool->pool_no);
  3965. restart = true;
  3966. }
  3967. }
  3968. if (restart)
  3969. restart_threads();
  3970. }
  3971. work->longpoll = false;
  3972. out_free:
  3973. free(hexstr);
  3974. return ret;
  3975. }
  3976. static int tv_sort(struct work *worka, struct work *workb)
  3977. {
  3978. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  3979. }
  3980. static bool work_rollable(struct work *work)
  3981. {
  3982. return (!work->clone && work->rolltime);
  3983. }
  3984. static bool hash_push(struct work *work)
  3985. {
  3986. bool rc = true;
  3987. mutex_lock(stgd_lock);
  3988. if (work_rollable(work))
  3989. staged_rollable++;
  3990. if (likely(!getq->frozen)) {
  3991. HASH_ADD_INT(staged_work, id, work);
  3992. HASH_SORT(staged_work, tv_sort);
  3993. } else
  3994. rc = false;
  3995. pthread_cond_broadcast(&getq->cond);
  3996. mutex_unlock(stgd_lock);
  3997. return rc;
  3998. }
  3999. static void *stage_thread(void *userdata)
  4000. {
  4001. struct thr_info *mythr = userdata;
  4002. bool ok = true;
  4003. RenameThread("stage");
  4004. while (ok) {
  4005. struct work *work = NULL;
  4006. applog(LOG_DEBUG, "Popping work to stage thread");
  4007. work = tq_pop(mythr->q, NULL);
  4008. if (unlikely(!work)) {
  4009. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  4010. ok = false;
  4011. break;
  4012. }
  4013. work->work_restart_id = work->pool->work_restart_id;
  4014. test_work_current(work);
  4015. applog(LOG_DEBUG, "Pushing work to getwork queue (queued=%c)", work->queued?'Y':'N');
  4016. if (unlikely(!hash_push(work))) {
  4017. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  4018. continue;
  4019. }
  4020. }
  4021. tq_freeze(mythr->q);
  4022. return NULL;
  4023. }
  4024. static void stage_work(struct work *work)
  4025. {
  4026. applog(LOG_DEBUG, "Pushing work from pool %d to hash queue", work->pool->pool_no);
  4027. work->work_restart_id = work->pool->work_restart_id;
  4028. test_work_current(work);
  4029. hash_push(work);
  4030. }
  4031. #ifdef HAVE_CURSES
  4032. int curses_int(const char *query)
  4033. {
  4034. int ret;
  4035. char *cvar;
  4036. cvar = curses_input(query);
  4037. ret = atoi(cvar);
  4038. free(cvar);
  4039. return ret;
  4040. }
  4041. #endif
  4042. #ifdef HAVE_CURSES
  4043. static bool input_pool(bool live);
  4044. #endif
  4045. #ifdef HAVE_CURSES
  4046. static void display_pool_summary(struct pool *pool)
  4047. {
  4048. double efficiency = 0.0;
  4049. if (curses_active_locked()) {
  4050. wlog("Pool: %s\n", pool->rpc_url);
  4051. if (pool->solved)
  4052. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  4053. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  4054. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  4055. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  4056. wlog(" Accepted shares: %d\n", pool->accepted);
  4057. wlog(" Rejected shares: %d\n", pool->rejected);
  4058. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  4059. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  4060. if (pool->accepted || pool->rejected)
  4061. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  4062. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  4063. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  4064. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  4065. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  4066. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  4067. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  4068. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  4069. unlock_curses();
  4070. }
  4071. }
  4072. #endif
  4073. /* We can't remove the memory used for this struct pool because there may
  4074. * still be work referencing it. We just remove it from the pools list */
  4075. void remove_pool(struct pool *pool)
  4076. {
  4077. int i, last_pool = total_pools - 1;
  4078. struct pool *other;
  4079. /* Boost priority of any lower prio than this one */
  4080. for (i = 0; i < total_pools; i++) {
  4081. other = pools[i];
  4082. if (other->prio > pool->prio)
  4083. other->prio--;
  4084. }
  4085. if (pool->pool_no < last_pool) {
  4086. /* Swap the last pool for this one */
  4087. (pools[last_pool])->pool_no = pool->pool_no;
  4088. pools[pool->pool_no] = pools[last_pool];
  4089. }
  4090. /* Give it an invalid number */
  4091. pool->pool_no = total_pools;
  4092. pool->removed = true;
  4093. pool->has_stratum = false;
  4094. total_pools--;
  4095. }
  4096. /* add a mutex if this needs to be thread safe in the future */
  4097. static struct JE {
  4098. char *buf;
  4099. struct JE *next;
  4100. } *jedata = NULL;
  4101. static void json_escape_free()
  4102. {
  4103. struct JE *jeptr = jedata;
  4104. struct JE *jenext;
  4105. jedata = NULL;
  4106. while (jeptr) {
  4107. jenext = jeptr->next;
  4108. free(jeptr->buf);
  4109. free(jeptr);
  4110. jeptr = jenext;
  4111. }
  4112. }
  4113. static char *json_escape(char *str)
  4114. {
  4115. struct JE *jeptr;
  4116. char *buf, *ptr;
  4117. /* 2x is the max, may as well just allocate that */
  4118. ptr = buf = malloc(strlen(str) * 2 + 1);
  4119. jeptr = malloc(sizeof(*jeptr));
  4120. jeptr->buf = buf;
  4121. jeptr->next = jedata;
  4122. jedata = jeptr;
  4123. while (*str) {
  4124. if (*str == '\\' || *str == '"')
  4125. *(ptr++) = '\\';
  4126. *(ptr++) = *(str++);
  4127. }
  4128. *ptr = '\0';
  4129. return buf;
  4130. }
  4131. void write_config(FILE *fcfg)
  4132. {
  4133. int i;
  4134. /* Write pool values */
  4135. fputs("{\n\"pools\" : [", fcfg);
  4136. for(i = 0; i < total_pools; i++) {
  4137. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "", json_escape(pools[i]->rpc_url));
  4138. if (pools[i]->rpc_proxy)
  4139. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pools[i]->rpc_proxy));
  4140. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pools[i]->rpc_user));
  4141. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pools[i]->rpc_pass));
  4142. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pools[i]->prio);
  4143. if (pools[i]->force_rollntime)
  4144. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pools[i]->force_rollntime);
  4145. fprintf(fcfg, "\n\t}");
  4146. }
  4147. fputs("\n]\n", fcfg);
  4148. #ifdef HAVE_OPENCL
  4149. if (nDevs) {
  4150. /* Write GPU device values */
  4151. fputs(",\n\"intensity\" : \"", fcfg);
  4152. for(i = 0; i < nDevs; i++)
  4153. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  4154. fputs("\",\n\"vectors\" : \"", fcfg);
  4155. for(i = 0; i < nDevs; i++)
  4156. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  4157. gpus[i].vwidth);
  4158. fputs("\",\n\"worksize\" : \"", fcfg);
  4159. for(i = 0; i < nDevs; i++)
  4160. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  4161. (int)gpus[i].work_size);
  4162. fputs("\",\n\"kernel\" : \"", fcfg);
  4163. for(i = 0; i < nDevs; i++) {
  4164. fprintf(fcfg, "%s", i > 0 ? "," : "");
  4165. switch (gpus[i].kernel) {
  4166. case KL_NONE: // Shouldn't happen
  4167. break;
  4168. case KL_POCLBM:
  4169. fprintf(fcfg, "poclbm");
  4170. break;
  4171. case KL_PHATK:
  4172. fprintf(fcfg, "phatk");
  4173. break;
  4174. case KL_DIAKGCN:
  4175. fprintf(fcfg, "diakgcn");
  4176. break;
  4177. case KL_DIABLO:
  4178. fprintf(fcfg, "diablo");
  4179. break;
  4180. case KL_SCRYPT:
  4181. fprintf(fcfg, "scrypt");
  4182. break;
  4183. }
  4184. }
  4185. #ifdef USE_SCRYPT
  4186. fputs("\",\n\"lookup-gap\" : \"", fcfg);
  4187. for(i = 0; i < nDevs; i++)
  4188. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  4189. (int)gpus[i].opt_lg);
  4190. fputs("\",\n\"thread-concurrency\" : \"", fcfg);
  4191. for(i = 0; i < nDevs; i++)
  4192. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  4193. (int)gpus[i].opt_tc);
  4194. fputs("\",\n\"shaders\" : \"", fcfg);
  4195. for(i = 0; i < nDevs; i++)
  4196. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  4197. (int)gpus[i].shaders);
  4198. #endif
  4199. #ifdef HAVE_ADL
  4200. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  4201. for(i = 0; i < nDevs; i++)
  4202. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  4203. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  4204. for(i = 0; i < nDevs; i++)
  4205. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  4206. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  4207. for(i = 0; i < nDevs; i++)
  4208. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  4209. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  4210. for(i = 0; i < nDevs; i++)
  4211. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  4212. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  4213. for(i = 0; i < nDevs; i++)
  4214. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  4215. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  4216. for(i = 0; i < nDevs; i++)
  4217. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  4218. fputs("\",\n\"temp-cutoff\" : \"", fcfg);
  4219. for(i = 0; i < nDevs; i++)
  4220. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].cutofftemp);
  4221. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  4222. for(i = 0; i < nDevs; i++)
  4223. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  4224. fputs("\",\n\"temp-target\" : \"", fcfg);
  4225. for(i = 0; i < nDevs; i++)
  4226. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].targettemp);
  4227. #endif
  4228. fputs("\"", fcfg);
  4229. }
  4230. #endif
  4231. #ifdef HAVE_ADL
  4232. if (opt_reorder)
  4233. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  4234. #endif
  4235. #ifdef WANT_CPUMINE
  4236. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  4237. #endif
  4238. /* Simple bool and int options */
  4239. struct opt_table *opt;
  4240. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  4241. char *p, *name = strdup(opt->names);
  4242. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  4243. if (p[1] != '-')
  4244. continue;
  4245. if (opt->type & OPT_NOARG &&
  4246. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  4247. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  4248. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  4249. if (opt->type & OPT_HASARG &&
  4250. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  4251. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  4252. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  4253. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  4254. opt->desc != opt_hidden &&
  4255. 0 <= *(int *)opt->u.arg)
  4256. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  4257. }
  4258. }
  4259. /* Special case options */
  4260. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  4261. if (pool_strategy == POOL_BALANCE)
  4262. fputs(",\n\"balance\" : true", fcfg);
  4263. if (pool_strategy == POOL_LOADBALANCE)
  4264. fputs(",\n\"load-balance\" : true", fcfg);
  4265. if (pool_strategy == POOL_ROUNDROBIN)
  4266. fputs(",\n\"round-robin\" : true", fcfg);
  4267. if (pool_strategy == POOL_ROTATE)
  4268. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  4269. #if defined(unix)
  4270. if (opt_stderr_cmd && *opt_stderr_cmd)
  4271. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  4272. #endif // defined(unix)
  4273. if (opt_kernel_path && *opt_kernel_path) {
  4274. char *kpath = strdup(opt_kernel_path);
  4275. if (kpath[strlen(kpath)-1] == '/')
  4276. kpath[strlen(kpath)-1] = 0;
  4277. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  4278. }
  4279. if (schedstart.enable)
  4280. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  4281. if (schedstop.enable)
  4282. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  4283. if (opt_socks_proxy && *opt_socks_proxy)
  4284. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  4285. #ifdef HAVE_OPENCL
  4286. for(i = 0; i < nDevs; i++)
  4287. if (gpus[i].deven == DEV_DISABLED)
  4288. break;
  4289. if (i < nDevs)
  4290. for (i = 0; i < nDevs; i++)
  4291. if (gpus[i].deven != DEV_DISABLED)
  4292. fprintf(fcfg, ",\n\"device\" : \"%d\"", i);
  4293. #endif
  4294. if (opt_api_allow)
  4295. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  4296. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  4297. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  4298. if (opt_api_groups)
  4299. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  4300. if (opt_icarus_options)
  4301. fprintf(fcfg, ",\n\"icarus-options\" : \"%s\"", json_escape(opt_icarus_options));
  4302. if (opt_icarus_timing)
  4303. fprintf(fcfg, ",\n\"icarus-timing\" : \"%s\"", json_escape(opt_icarus_timing));
  4304. fputs("\n}\n", fcfg);
  4305. json_escape_free();
  4306. }
  4307. void zero_bestshare(void)
  4308. {
  4309. int i;
  4310. best_diff = 0;
  4311. memset(best_share, 0, 8);
  4312. suffix_string(best_diff, best_share, 0);
  4313. for (i = 0; i < total_pools; i++) {
  4314. struct pool *pool = pools[i];
  4315. pool->best_diff = 0;
  4316. }
  4317. }
  4318. void zero_stats(void)
  4319. {
  4320. int i;
  4321. gettimeofday(&total_tv_start, NULL);
  4322. miner_started = total_tv_start;
  4323. total_mhashes_done = 0;
  4324. total_getworks = 0;
  4325. total_accepted = 0;
  4326. total_rejected = 0;
  4327. hw_errors = 0;
  4328. total_stale = 0;
  4329. total_discarded = 0;
  4330. total_bytes_xfer = 0;
  4331. new_blocks = 0;
  4332. local_work = 0;
  4333. total_go = 0;
  4334. total_ro = 0;
  4335. total_secs = 1.0;
  4336. total_diff1 = 0;
  4337. found_blocks = 0;
  4338. total_diff_accepted = 0;
  4339. total_diff_rejected = 0;
  4340. total_diff_stale = 0;
  4341. for (i = 0; i < total_pools; i++) {
  4342. struct pool *pool = pools[i];
  4343. pool->getwork_requested = 0;
  4344. pool->accepted = 0;
  4345. pool->rejected = 0;
  4346. pool->solved = 0;
  4347. pool->getwork_requested = 0;
  4348. pool->stale_shares = 0;
  4349. pool->discarded_work = 0;
  4350. pool->getfail_occasions = 0;
  4351. pool->remotefail_occasions = 0;
  4352. pool->last_share_time = 0;
  4353. pool->diff1 = 0;
  4354. pool->diff_accepted = 0;
  4355. pool->diff_rejected = 0;
  4356. pool->diff_stale = 0;
  4357. pool->last_share_diff = 0;
  4358. pool->cgminer_stats.getwork_calls = 0;
  4359. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  4360. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  4361. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  4362. pool->cgminer_pool_stats.getwork_calls = 0;
  4363. pool->cgminer_pool_stats.getwork_attempts = 0;
  4364. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  4365. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  4366. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  4367. pool->cgminer_pool_stats.min_diff = 0;
  4368. pool->cgminer_pool_stats.max_diff = 0;
  4369. pool->cgminer_pool_stats.min_diff_count = 0;
  4370. pool->cgminer_pool_stats.max_diff_count = 0;
  4371. pool->cgminer_pool_stats.times_sent = 0;
  4372. pool->cgminer_pool_stats.bytes_sent = 0;
  4373. pool->cgminer_pool_stats.net_bytes_sent = 0;
  4374. pool->cgminer_pool_stats.times_received = 0;
  4375. pool->cgminer_pool_stats.bytes_received = 0;
  4376. pool->cgminer_pool_stats.net_bytes_received = 0;
  4377. }
  4378. zero_bestshare();
  4379. mutex_lock(&hash_lock);
  4380. for (i = 0; i < total_devices; ++i) {
  4381. struct cgpu_info *cgpu = devices[i];
  4382. cgpu->total_mhashes = 0;
  4383. cgpu->accepted = 0;
  4384. cgpu->rejected = 0;
  4385. cgpu->hw_errors = 0;
  4386. cgpu->utility = 0.0;
  4387. cgpu->utility_diff1 = 0;
  4388. cgpu->last_share_pool_time = 0;
  4389. cgpu->diff1 = 0;
  4390. cgpu->diff_accepted = 0;
  4391. cgpu->diff_rejected = 0;
  4392. cgpu->last_share_diff = 0;
  4393. cgpu->thread_fail_init_count = 0;
  4394. cgpu->thread_zero_hash_count = 0;
  4395. cgpu->thread_fail_queue_count = 0;
  4396. cgpu->dev_sick_idle_60_count = 0;
  4397. cgpu->dev_dead_idle_600_count = 0;
  4398. cgpu->dev_nostart_count = 0;
  4399. cgpu->dev_over_heat_count = 0;
  4400. cgpu->dev_thermal_cutoff_count = 0;
  4401. cgpu->dev_comms_error_count = 0;
  4402. cgpu->dev_throttle_count = 0;
  4403. cgpu->cgminer_stats.getwork_calls = 0;
  4404. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  4405. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  4406. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  4407. }
  4408. mutex_unlock(&hash_lock);
  4409. }
  4410. #ifdef HAVE_CURSES
  4411. static void display_pools(void)
  4412. {
  4413. struct pool *pool;
  4414. int selected, i, j;
  4415. char input;
  4416. opt_loginput = true;
  4417. immedok(logwin, true);
  4418. clear_logwin();
  4419. updated:
  4420. for (j = 0; j < total_pools; j++) {
  4421. for (i = 0; i < total_pools; i++) {
  4422. pool = pools[i];
  4423. if (pool->prio != j)
  4424. continue;
  4425. if (pool == current_pool())
  4426. wattron(logwin, A_BOLD);
  4427. if (pool->enabled != POOL_ENABLED)
  4428. wattron(logwin, A_DIM);
  4429. wlogprint("%d: ", pool->prio);
  4430. switch (pool->enabled) {
  4431. case POOL_ENABLED:
  4432. wlogprint("Enabled ");
  4433. break;
  4434. case POOL_DISABLED:
  4435. wlogprint("Disabled ");
  4436. break;
  4437. case POOL_REJECTING:
  4438. wlogprint("Rejectin ");
  4439. break;
  4440. }
  4441. if (pool->idle)
  4442. wlogprint("Dead ");
  4443. else
  4444. if (pool->has_stratum)
  4445. wlogprint("Strtm");
  4446. else
  4447. if (pool->lp_url && pool->proto != pool->lp_proto)
  4448. wlogprint("Mixed");
  4449. else
  4450. switch (pool->proto) {
  4451. case PLP_GETBLOCKTEMPLATE:
  4452. wlogprint(" GBT ");
  4453. break;
  4454. case PLP_GETWORK:
  4455. wlogprint("GWork");
  4456. break;
  4457. default:
  4458. wlogprint("Alive");
  4459. }
  4460. wlogprint(" Pool %d: %s User:%s\n",
  4461. pool->pool_no,
  4462. pool->rpc_url, pool->rpc_user);
  4463. wattroff(logwin, A_BOLD | A_DIM);
  4464. break; //for (i = 0; i < total_pools; i++)
  4465. }
  4466. }
  4467. retry:
  4468. wlogprint("\nCurrent pool management strategy: %s\n",
  4469. strategies[pool_strategy]);
  4470. if (pool_strategy == POOL_ROTATE)
  4471. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  4472. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  4473. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool [P]rioritize pool\n");
  4474. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  4475. wlogprint("Or press any other key to continue\n");
  4476. input = getch();
  4477. if (!strncasecmp(&input, "a", 1)) {
  4478. input_pool(true);
  4479. goto updated;
  4480. } else if (!strncasecmp(&input, "r", 1)) {
  4481. if (total_pools <= 1) {
  4482. wlogprint("Cannot remove last pool");
  4483. goto retry;
  4484. }
  4485. selected = curses_int("Select pool number");
  4486. if (selected < 0 || selected >= total_pools) {
  4487. wlogprint("Invalid selection\n");
  4488. goto retry;
  4489. }
  4490. pool = pools[selected];
  4491. if (pool == current_pool())
  4492. switch_pools(NULL);
  4493. if (pool == current_pool()) {
  4494. wlogprint("Unable to remove pool due to activity\n");
  4495. goto retry;
  4496. }
  4497. disable_pool(pool);
  4498. remove_pool(pool);
  4499. goto updated;
  4500. } else if (!strncasecmp(&input, "s", 1)) {
  4501. selected = curses_int("Select pool number");
  4502. if (selected < 0 || selected >= total_pools) {
  4503. wlogprint("Invalid selection\n");
  4504. goto retry;
  4505. }
  4506. pool = pools[selected];
  4507. enable_pool(pool);
  4508. switch_pools(pool);
  4509. goto updated;
  4510. } else if (!strncasecmp(&input, "d", 1)) {
  4511. if (enabled_pools <= 1) {
  4512. wlogprint("Cannot disable last pool");
  4513. goto retry;
  4514. }
  4515. selected = curses_int("Select pool number");
  4516. if (selected < 0 || selected >= total_pools) {
  4517. wlogprint("Invalid selection\n");
  4518. goto retry;
  4519. }
  4520. pool = pools[selected];
  4521. disable_pool(pool);
  4522. if (pool == current_pool())
  4523. switch_pools(NULL);
  4524. goto updated;
  4525. } else if (!strncasecmp(&input, "e", 1)) {
  4526. selected = curses_int("Select pool number");
  4527. if (selected < 0 || selected >= total_pools) {
  4528. wlogprint("Invalid selection\n");
  4529. goto retry;
  4530. }
  4531. pool = pools[selected];
  4532. enable_pool(pool);
  4533. if (pool->prio < current_pool()->prio)
  4534. switch_pools(pool);
  4535. goto updated;
  4536. } else if (!strncasecmp(&input, "c", 1)) {
  4537. for (i = 0; i <= TOP_STRATEGY; i++)
  4538. wlogprint("%d: %s\n", i, strategies[i]);
  4539. selected = curses_int("Select strategy number type");
  4540. if (selected < 0 || selected > TOP_STRATEGY) {
  4541. wlogprint("Invalid selection\n");
  4542. goto retry;
  4543. }
  4544. if (selected == POOL_ROTATE) {
  4545. opt_rotate_period = curses_int("Select interval in minutes");
  4546. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  4547. opt_rotate_period = 0;
  4548. wlogprint("Invalid selection\n");
  4549. goto retry;
  4550. }
  4551. }
  4552. pool_strategy = selected;
  4553. switch_pools(NULL);
  4554. goto updated;
  4555. } else if (!strncasecmp(&input, "i", 1)) {
  4556. selected = curses_int("Select pool number");
  4557. if (selected < 0 || selected >= total_pools) {
  4558. wlogprint("Invalid selection\n");
  4559. goto retry;
  4560. }
  4561. pool = pools[selected];
  4562. display_pool_summary(pool);
  4563. goto retry;
  4564. } else if (!strncasecmp(&input, "f", 1)) {
  4565. opt_fail_only ^= true;
  4566. goto updated;
  4567. } else if (!strncasecmp(&input, "p", 1)) {
  4568. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  4569. int res = prioritize_pools(prilist, &i);
  4570. free(prilist);
  4571. switch (res) {
  4572. case MSG_NOPOOL:
  4573. wlogprint("No pools\n");
  4574. goto retry;
  4575. case MSG_MISPID:
  4576. wlogprint("Missing pool id parameter\n");
  4577. goto retry;
  4578. case MSG_INVPID:
  4579. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  4580. goto retry;
  4581. case MSG_DUPPID:
  4582. wlogprint("Duplicate pool specified %d\n", i);
  4583. goto retry;
  4584. case MSG_POOLPRIO:
  4585. default:
  4586. goto updated;
  4587. }
  4588. } else
  4589. clear_logwin();
  4590. immedok(logwin, false);
  4591. opt_loginput = false;
  4592. }
  4593. static const char *summary_detail_level_str(void)
  4594. {
  4595. if (opt_compact)
  4596. return "compact";
  4597. if (opt_show_procs)
  4598. return "processors";
  4599. return "devices";
  4600. }
  4601. static void display_options(void)
  4602. {
  4603. int selected;
  4604. char input;
  4605. opt_loginput = true;
  4606. immedok(logwin, true);
  4607. clear_logwin();
  4608. retry:
  4609. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  4610. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  4611. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  4612. "[L]og interval:%d\n[Z]ero statistics\n",
  4613. opt_debug_console ? "on" : "off",
  4614. want_per_device_stats? "on" : "off",
  4615. opt_quiet ? "on" : "off",
  4616. opt_log_output ? "on" : "off",
  4617. opt_protocol ? "on" : "off",
  4618. opt_worktime ? "on" : "off",
  4619. summary_detail_level_str(),
  4620. opt_log_interval);
  4621. wlogprint("Select an option or any other key to return\n");
  4622. input = getch();
  4623. if (!strncasecmp(&input, "q", 1)) {
  4624. opt_quiet ^= true;
  4625. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  4626. goto retry;
  4627. } else if (!strncasecmp(&input, "v", 1)) {
  4628. opt_log_output ^= true;
  4629. if (opt_log_output)
  4630. opt_quiet = false;
  4631. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  4632. goto retry;
  4633. } else if (!strncasecmp(&input, "n", 1)) {
  4634. opt_log_output = false;
  4635. opt_debug_console = false;
  4636. opt_quiet = false;
  4637. opt_protocol = false;
  4638. opt_compact = false;
  4639. opt_show_procs = false;
  4640. devsummaryYOffset = 0;
  4641. want_per_device_stats = false;
  4642. wlogprint("Output mode reset to normal\n");
  4643. switch_compact();
  4644. goto retry;
  4645. } else if (!strncasecmp(&input, "d", 1)) {
  4646. opt_debug = true;
  4647. opt_debug_console ^= true;
  4648. opt_log_output = opt_debug_console;
  4649. if (opt_debug_console)
  4650. opt_quiet = false;
  4651. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  4652. goto retry;
  4653. } else if (!strncasecmp(&input, "m", 1)) {
  4654. if (opt_compact)
  4655. opt_compact = false;
  4656. else
  4657. if (!opt_show_procs)
  4658. opt_show_procs = true;
  4659. else
  4660. {
  4661. opt_compact = true;
  4662. opt_show_procs = false;
  4663. devsummaryYOffset = 0;
  4664. }
  4665. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  4666. switch_compact();
  4667. goto retry;
  4668. } else if (!strncasecmp(&input, "p", 1)) {
  4669. want_per_device_stats ^= true;
  4670. opt_log_output = want_per_device_stats;
  4671. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  4672. goto retry;
  4673. } else if (!strncasecmp(&input, "r", 1)) {
  4674. opt_protocol ^= true;
  4675. if (opt_protocol)
  4676. opt_quiet = false;
  4677. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  4678. goto retry;
  4679. } else if (!strncasecmp(&input, "c", 1))
  4680. clear_logwin();
  4681. else if (!strncasecmp(&input, "l", 1)) {
  4682. selected = curses_int("Interval in seconds");
  4683. if (selected < 0 || selected > 9999) {
  4684. wlogprint("Invalid selection\n");
  4685. goto retry;
  4686. }
  4687. opt_log_interval = selected;
  4688. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  4689. goto retry;
  4690. } else if (!strncasecmp(&input, "s", 1)) {
  4691. opt_realquiet = true;
  4692. } else if (!strncasecmp(&input, "w", 1)) {
  4693. opt_worktime ^= true;
  4694. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  4695. goto retry;
  4696. } else if (!strncasecmp(&input, "z", 1)) {
  4697. zero_stats();
  4698. goto retry;
  4699. } else
  4700. clear_logwin();
  4701. immedok(logwin, false);
  4702. opt_loginput = false;
  4703. }
  4704. #endif
  4705. void default_save_file(char *filename)
  4706. {
  4707. #if defined(unix)
  4708. if (getenv("HOME") && *getenv("HOME")) {
  4709. strcpy(filename, getenv("HOME"));
  4710. strcat(filename, "/");
  4711. }
  4712. else
  4713. strcpy(filename, "");
  4714. strcat(filename, ".bfgminer/");
  4715. mkdir(filename, 0777);
  4716. #else
  4717. strcpy(filename, "");
  4718. #endif
  4719. strcat(filename, def_conf);
  4720. }
  4721. #ifdef HAVE_CURSES
  4722. static void set_options(void)
  4723. {
  4724. int selected;
  4725. char input;
  4726. opt_loginput = true;
  4727. immedok(logwin, true);
  4728. clear_logwin();
  4729. retry:
  4730. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  4731. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  4732. "[W]rite config file\n[B]FGMiner restart\n",
  4733. opt_queue, opt_scantime, opt_expiry, opt_retries);
  4734. wlogprint("Select an option or any other key to return\n");
  4735. input = getch();
  4736. if (!strncasecmp(&input, "q", 1)) {
  4737. selected = curses_int("Extra work items to queue");
  4738. if (selected < 0 || selected > 9999) {
  4739. wlogprint("Invalid selection\n");
  4740. goto retry;
  4741. }
  4742. opt_queue = selected;
  4743. goto retry;
  4744. } else if (!strncasecmp(&input, "l", 1)) {
  4745. if (want_longpoll)
  4746. stop_longpoll();
  4747. else
  4748. start_longpoll();
  4749. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  4750. goto retry;
  4751. } else if (!strncasecmp(&input, "s", 1)) {
  4752. selected = curses_int("Set scantime in seconds");
  4753. if (selected < 0 || selected > 9999) {
  4754. wlogprint("Invalid selection\n");
  4755. goto retry;
  4756. }
  4757. opt_scantime = selected;
  4758. goto retry;
  4759. } else if (!strncasecmp(&input, "e", 1)) {
  4760. selected = curses_int("Set expiry time in seconds");
  4761. if (selected < 0 || selected > 9999) {
  4762. wlogprint("Invalid selection\n");
  4763. goto retry;
  4764. }
  4765. opt_expiry = selected;
  4766. goto retry;
  4767. } else if (!strncasecmp(&input, "r", 1)) {
  4768. selected = curses_int("Retries before failing (-1 infinite)");
  4769. if (selected < -1 || selected > 9999) {
  4770. wlogprint("Invalid selection\n");
  4771. goto retry;
  4772. }
  4773. opt_retries = selected;
  4774. goto retry;
  4775. } else if (!strncasecmp(&input, "w", 1)) {
  4776. FILE *fcfg;
  4777. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  4778. default_save_file(filename);
  4779. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  4780. str = curses_input(prompt);
  4781. if (strcmp(str, "-1")) {
  4782. struct stat statbuf;
  4783. strcpy(filename, str);
  4784. free(str);
  4785. if (!stat(filename, &statbuf)) {
  4786. wlogprint("File exists, overwrite?\n");
  4787. input = getch();
  4788. if (strncasecmp(&input, "y", 1))
  4789. goto retry;
  4790. }
  4791. }
  4792. else
  4793. free(str);
  4794. fcfg = fopen(filename, "w");
  4795. if (!fcfg) {
  4796. wlogprint("Cannot open or create file\n");
  4797. goto retry;
  4798. }
  4799. write_config(fcfg);
  4800. fclose(fcfg);
  4801. goto retry;
  4802. } else if (!strncasecmp(&input, "b", 1)) {
  4803. wlogprint("Are you sure?\n");
  4804. input = getch();
  4805. if (!strncasecmp(&input, "y", 1))
  4806. app_restart();
  4807. else
  4808. clear_logwin();
  4809. } else
  4810. clear_logwin();
  4811. immedok(logwin, false);
  4812. opt_loginput = false;
  4813. }
  4814. static void *input_thread(void __maybe_unused *userdata)
  4815. {
  4816. RenameThread("input");
  4817. if (!curses_active)
  4818. return NULL;
  4819. while (1) {
  4820. int input;
  4821. input = getch();
  4822. switch (input) {
  4823. case 'q': case 'Q':
  4824. kill_work();
  4825. return NULL;
  4826. case 'd': case 'D':
  4827. display_options();
  4828. break;
  4829. case 'p': case 'P':
  4830. display_pools();
  4831. break;
  4832. case 's': case 'S':
  4833. set_options();
  4834. break;
  4835. case 'g': case 'G':
  4836. if (have_opencl)
  4837. manage_gpu();
  4838. break;
  4839. #ifdef HAVE_CURSES
  4840. case KEY_DOWN:
  4841. if (devsummaryYOffset < -(total_lines + devcursor - statusy))
  4842. break;
  4843. devsummaryYOffset -= 2;
  4844. case KEY_UP:
  4845. if (devsummaryYOffset == 0)
  4846. break;
  4847. ++devsummaryYOffset;
  4848. if (curses_active_locked()) {
  4849. int i;
  4850. for (i = 0; i < mining_threads; i++)
  4851. curses_print_devstatus(i);
  4852. touchwin(statuswin);
  4853. wrefresh(statuswin);
  4854. unlock_curses();
  4855. }
  4856. break;
  4857. #endif
  4858. }
  4859. if (opt_realquiet) {
  4860. disable_curses();
  4861. break;
  4862. }
  4863. }
  4864. return NULL;
  4865. }
  4866. #endif
  4867. static void *api_thread(void *userdata)
  4868. {
  4869. struct thr_info *mythr = userdata;
  4870. pthread_detach(pthread_self());
  4871. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4872. RenameThread("rpc");
  4873. api(api_thr_id);
  4874. PTH(mythr) = 0L;
  4875. return NULL;
  4876. }
  4877. void thread_reportin(struct thr_info *thr)
  4878. {
  4879. gettimeofday(&thr->last, NULL);
  4880. thr->cgpu->status = LIFE_WELL;
  4881. thr->getwork = 0;
  4882. thr->cgpu->device_last_well = time(NULL);
  4883. }
  4884. void thread_reportout(struct thr_info *thr)
  4885. {
  4886. thr->getwork = time(NULL);
  4887. }
  4888. static void hashmeter(int thr_id, struct timeval *diff,
  4889. uint64_t hashes_done)
  4890. {
  4891. struct timeval temp_tv_end, total_diff;
  4892. double secs;
  4893. double local_secs;
  4894. double utility;
  4895. static double local_mhashes_done = 0;
  4896. static double rolling = 0;
  4897. double local_mhashes = (double)hashes_done / 1000000.0;
  4898. bool showlog = false;
  4899. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[H2B_SPACED]];
  4900. /* Update the last time this thread reported in */
  4901. if (thr_id >= 0) {
  4902. gettimeofday(&thr_info[thr_id].last, NULL);
  4903. thr_info[thr_id].cgpu->device_last_well = time(NULL);
  4904. }
  4905. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  4906. /* So we can call hashmeter from a non worker thread */
  4907. if (thr_id >= 0) {
  4908. struct thr_info *thr = &thr_info[thr_id];
  4909. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  4910. int threadobj = cgpu->threads ?: 1;
  4911. double thread_rolling = 0.0;
  4912. int i;
  4913. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  4914. thr_id, hashes_done, hashes_done / 1000 / secs);
  4915. /* Rolling average for each thread and each device */
  4916. decay_time(&thr->rolling, local_mhashes / secs);
  4917. for (i = 0; i < threadobj; i++)
  4918. thread_rolling += cgpu->thr[i]->rolling;
  4919. mutex_lock(&hash_lock);
  4920. decay_time(&cgpu->rolling, thread_rolling);
  4921. cgpu->total_mhashes += local_mhashes;
  4922. mutex_unlock(&hash_lock);
  4923. // If needed, output detailed, per-device stats
  4924. if (want_per_device_stats) {
  4925. struct timeval now;
  4926. struct timeval elapsed;
  4927. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  4928. gettimeofday(&now, NULL);
  4929. timersub(&now, last_msg_tv, &elapsed);
  4930. if (opt_log_interval <= elapsed.tv_sec) {
  4931. struct cgpu_info *cgpu = thr->cgpu;
  4932. char logline[255];
  4933. *last_msg_tv = now;
  4934. get_statline(logline, cgpu);
  4935. if (!curses_active) {
  4936. printf("%s \r", logline);
  4937. fflush(stdout);
  4938. } else
  4939. applog(LOG_INFO, "%s", logline);
  4940. }
  4941. }
  4942. }
  4943. /* Totals are updated by all threads so can race without locking */
  4944. mutex_lock(&hash_lock);
  4945. gettimeofday(&temp_tv_end, NULL);
  4946. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  4947. total_mhashes_done += local_mhashes;
  4948. local_mhashes_done += local_mhashes;
  4949. if (total_diff.tv_sec < opt_log_interval)
  4950. /* Only update the total every opt_log_interval seconds */
  4951. goto out_unlock;
  4952. showlog = true;
  4953. gettimeofday(&total_tv_end, NULL);
  4954. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  4955. decay_time(&rolling, local_mhashes_done / local_secs);
  4956. global_hashrate = roundl(rolling) * 1000000;
  4957. timersub(&total_tv_end, &total_tv_start, &total_diff);
  4958. total_secs = (double)total_diff.tv_sec +
  4959. ((double)total_diff.tv_usec / 1000000.0);
  4960. utility = total_accepted / total_secs * 60;
  4961. ti_hashrate_bufstr(
  4962. (char*[]){cHr, aHr, uHr},
  4963. 1e6*rolling,
  4964. 1e6*total_mhashes_done / total_secs,
  4965. utility_to_hashrate(total_diff_accepted / (total_secs ?: 1) * 60),
  4966. H2B_SPACED);
  4967. sprintf(statusline, "%s%ds:%s avg:%s u:%s | A:%d R:%d S:%d HW:%d U:%.1f/m",
  4968. want_per_device_stats ? "ALL " : "",
  4969. opt_log_interval,
  4970. cHr, aHr,
  4971. uHr,
  4972. total_accepted, total_rejected, total_stale,
  4973. hw_errors,
  4974. utility);
  4975. local_mhashes_done = 0;
  4976. out_unlock:
  4977. mutex_unlock(&hash_lock);
  4978. if (showlog) {
  4979. if (!curses_active) {
  4980. printf("%s \r", statusline);
  4981. fflush(stdout);
  4982. } else
  4983. applog(LOG_INFO, "%s", statusline);
  4984. }
  4985. }
  4986. void hashmeter2(struct thr_info *thr)
  4987. {
  4988. struct timeval tv_now, tv_elapsed;
  4989. timerclear(&thr->tv_hashes_done);
  4990. gettimeofday(&tv_now, NULL);
  4991. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  4992. if (tv_elapsed.tv_sec >= opt_log_interval) {
  4993. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  4994. thr->hashes_done = 0;
  4995. thr->tv_lastupdate = tv_now;
  4996. }
  4997. }
  4998. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  4999. struct stratum_share *sshare)
  5000. {
  5001. struct work *work = sshare->work;
  5002. share_result(val, res_val, err_val, work, false, "");
  5003. }
  5004. /* Parses stratum json responses and tries to find the id that the request
  5005. * matched to and treat it accordingly. */
  5006. bool parse_stratum_response(struct pool *pool, char *s)
  5007. {
  5008. json_t *val = NULL, *err_val, *res_val, *id_val;
  5009. struct stratum_share *sshare;
  5010. json_error_t err;
  5011. bool ret = false;
  5012. int id;
  5013. val = JSON_LOADS(s, &err);
  5014. if (!val) {
  5015. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  5016. goto out;
  5017. }
  5018. res_val = json_object_get(val, "result");
  5019. err_val = json_object_get(val, "error");
  5020. id_val = json_object_get(val, "id");
  5021. if (json_is_null(id_val) || !id_val) {
  5022. char *ss;
  5023. if (err_val)
  5024. ss = json_dumps(err_val, JSON_INDENT(3));
  5025. else
  5026. ss = strdup("(unknown reason)");
  5027. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  5028. free(ss);
  5029. goto out;
  5030. }
  5031. if (!json_is_integer(id_val)) {
  5032. if (json_is_string(id_val)
  5033. && !strncmp(json_string_value(id_val), "txlist", 6)
  5034. && !strcmp(json_string_value(id_val) + 6, pool->swork.job_id)
  5035. && json_is_array(res_val)) {
  5036. // Check that the transactions actually hash to the merkle links
  5037. {
  5038. unsigned maxtx = 1 << pool->swork.merkles;
  5039. unsigned mintx = maxtx >> 1;
  5040. --maxtx;
  5041. unsigned acttx = (unsigned)json_array_size(res_val);
  5042. if (acttx < mintx || acttx > maxtx) {
  5043. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  5044. pool->pool_no, acttx, mintx, maxtx);
  5045. goto fishy;
  5046. }
  5047. // TODO: Check hashes match actual merkle links
  5048. }
  5049. if (pool->swork.opaque) {
  5050. pool->swork.opaque = false;
  5051. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  5052. pool->pool_no);
  5053. }
  5054. pool->swork.transparency_time = (time_t)-1;
  5055. fishy:
  5056. ret = true;
  5057. }
  5058. goto out;
  5059. }
  5060. id = json_integer_value(id_val);
  5061. mutex_lock(&sshare_lock);
  5062. HASH_FIND_INT(stratum_shares, &id, sshare);
  5063. if (sshare)
  5064. HASH_DEL(stratum_shares, sshare);
  5065. mutex_unlock(&sshare_lock);
  5066. if (!sshare) {
  5067. if (json_is_true(res_val))
  5068. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  5069. else
  5070. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  5071. goto out;
  5072. }
  5073. else {
  5074. mutex_lock(&submitting_lock);
  5075. --total_submitting;
  5076. mutex_unlock(&submitting_lock);
  5077. }
  5078. stratum_share_result(val, res_val, err_val, sshare);
  5079. free_work(sshare->work);
  5080. free(sshare);
  5081. ret = true;
  5082. out:
  5083. if (val)
  5084. json_decref(val);
  5085. return ret;
  5086. }
  5087. static void shutdown_stratum(struct pool *pool)
  5088. {
  5089. // Shut down Stratum as if we never had it
  5090. pool->stratum_active = false;
  5091. pool->stratum_auth = false;
  5092. pool->has_stratum = false;
  5093. shutdown(pool->sock, SHUT_RDWR);
  5094. free(pool->stratum_url);
  5095. if (pool->sockaddr_url == pool->stratum_url)
  5096. pool->sockaddr_url = NULL;
  5097. pool->stratum_url = NULL;
  5098. }
  5099. static void clear_stratum_shares(struct pool *pool)
  5100. {
  5101. struct stratum_share *sshare, *tmpshare;
  5102. struct work *work;
  5103. int cleared = 0;
  5104. double diff_stale = 0;
  5105. mutex_lock(&sshare_lock);
  5106. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  5107. if (sshare->work->pool == pool) {
  5108. HASH_DEL(stratum_shares, sshare);
  5109. work = sshare->work;
  5110. sharelog("disconnect", work);
  5111. diff_stale += work->work_difficulty;
  5112. free_work(sshare->work);
  5113. free(sshare);
  5114. cleared++;
  5115. }
  5116. }
  5117. mutex_unlock(&sshare_lock);
  5118. if (cleared) {
  5119. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  5120. mutex_lock(&stats_lock);
  5121. pool->stale_shares += cleared;
  5122. total_stale += cleared;
  5123. total_diff_stale += diff_stale;
  5124. pool->diff_stale += diff_stale;
  5125. mutex_unlock(&stats_lock);
  5126. mutex_lock(&submitting_lock);
  5127. total_submitting -= cleared;
  5128. mutex_unlock(&submitting_lock);
  5129. }
  5130. }
  5131. static void clear_pool_work(struct pool *pool)
  5132. {
  5133. struct work *work, *tmp;
  5134. int cleared = 0;
  5135. mutex_lock(stgd_lock);
  5136. HASH_ITER(hh, staged_work, work, tmp) {
  5137. if (work->pool == pool) {
  5138. HASH_DEL(staged_work, work);
  5139. free_work(work);
  5140. cleared++;
  5141. }
  5142. }
  5143. mutex_unlock(stgd_lock);
  5144. }
  5145. /* We only need to maintain a secondary pool connection when we need the
  5146. * capacity to get work from the backup pools while still on the primary */
  5147. static bool cnx_needed(struct pool *pool)
  5148. {
  5149. struct pool *cp;
  5150. /* Balance strategies need all pools online */
  5151. if (pool_strategy == POOL_BALANCE)
  5152. return true;
  5153. if (pool_strategy == POOL_LOADBALANCE)
  5154. return true;
  5155. /* Idle stratum pool needs something to kick it alive again */
  5156. if (pool->has_stratum && pool->idle)
  5157. return true;
  5158. /* Getwork pools without opt_fail_only need backup pools up to be able
  5159. * to leak shares */
  5160. cp = current_pool();
  5161. if (cp == pool)
  5162. return true;
  5163. if (!cp->has_stratum && (!opt_fail_only || !cp->hdr_path))
  5164. return true;
  5165. /* Keep stratum pools alive until at least a minute after their last
  5166. * generated work, to ensure we have a channel for any submissions */
  5167. if (pool->has_stratum && difftime(time(NULL), pool->last_work_time) < 60)
  5168. return true;
  5169. return false;
  5170. }
  5171. static void wait_lpcurrent(struct pool *pool);
  5172. static void pool_resus(struct pool *pool);
  5173. static void gen_stratum_work(struct pool *pool, struct work *work);
  5174. static void stratum_resumed(struct pool *pool)
  5175. {
  5176. if (!pool->stratum_notify)
  5177. return;
  5178. if (pool_tclear(pool, &pool->idle)) {
  5179. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  5180. pool_resus(pool);
  5181. }
  5182. }
  5183. /* One stratum thread per pool that has stratum waits on the socket checking
  5184. * for new messages and for the integrity of the socket connection. We reset
  5185. * the connection based on the integrity of the receive side only as the send
  5186. * side will eventually expire data it fails to send. */
  5187. static void *stratum_thread(void *userdata)
  5188. {
  5189. struct pool *pool = (struct pool *)userdata;
  5190. pthread_detach(pthread_self());
  5191. RenameThread("stratum");
  5192. srand(time(NULL) + (intptr_t)userdata);
  5193. while (42) {
  5194. struct timeval timeout;
  5195. fd_set rd;
  5196. char *s;
  5197. if (unlikely(!pool->has_stratum))
  5198. break;
  5199. /* Check to see whether we need to maintain this connection
  5200. * indefinitely or just bring it up when we switch to this
  5201. * pool */
  5202. if (!sock_full(pool) && !cnx_needed(pool)) {
  5203. suspend_stratum(pool);
  5204. clear_stratum_shares(pool);
  5205. clear_pool_work(pool);
  5206. wait_lpcurrent(pool);
  5207. if (!initiate_stratum(pool) || !auth_stratum(pool)) {
  5208. pool_died(pool);
  5209. while (!initiate_stratum(pool) || !auth_stratum(pool)) {
  5210. if (pool->removed)
  5211. goto out;
  5212. sleep(30);
  5213. }
  5214. }
  5215. }
  5216. FD_ZERO(&rd);
  5217. FD_SET(pool->sock, &rd);
  5218. timeout.tv_sec = 120;
  5219. timeout.tv_usec = 0;
  5220. /* If we fail to receive any notify messages for 2 minutes we
  5221. * assume the connection has been dropped and treat this pool
  5222. * as dead */
  5223. if (!sock_full(pool) && select(pool->sock + 1, &rd, NULL, NULL, &timeout) < 1)
  5224. s = NULL;
  5225. else
  5226. s = recv_line(pool);
  5227. if (!s) {
  5228. if (!pool->has_stratum)
  5229. break;
  5230. applog(LOG_INFO, "Stratum connection to pool %d interrupted", pool->pool_no);
  5231. pool->getfail_occasions++;
  5232. total_go++;
  5233. // Make any pending work/shares stale
  5234. pool->sock = INVSOCK;
  5235. pool->submit_old = false;
  5236. ++pool->work_restart_id;
  5237. /* If the socket to our stratum pool disconnects, all
  5238. * tracked submitted shares are lost and we will leak
  5239. * the memory if we don't discard their records. */
  5240. clear_stratum_shares(pool);
  5241. clear_pool_work(pool);
  5242. if (pool == current_pool())
  5243. restart_threads();
  5244. if (initiate_stratum(pool) && auth_stratum(pool))
  5245. continue;
  5246. shutdown_stratum(pool);
  5247. pool_died(pool);
  5248. break;
  5249. }
  5250. /* Check this pool hasn't died while being a backup pool and
  5251. * has not had its idle flag cleared */
  5252. stratum_resumed(pool);
  5253. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  5254. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  5255. free(s);
  5256. if (pool->swork.clean) {
  5257. struct work *work = make_work();
  5258. /* Generate a single work item to update the current
  5259. * block database */
  5260. pool->swork.clean = false;
  5261. gen_stratum_work(pool, work);
  5262. /* Try to extract block height from coinbase scriptSig */
  5263. char *hex_height = &pool->swork.coinbase1[8 /*version*/ + 2 /*txin count*/ + 72 /*prevout*/ + 2 /*scriptSig len*/ + 2 /*push opcode*/];
  5264. unsigned char cb_height_sz;
  5265. hex2bin(&cb_height_sz, &hex_height[-2], 1);
  5266. if (cb_height_sz == 3) {
  5267. // FIXME: The block number will overflow this by AD 2173
  5268. uint32_t block_id = ((uint32_t*)work->data)[1];
  5269. uint32_t height = 0;
  5270. hex2bin((unsigned char*)&height, hex_height, 3);
  5271. height = le32toh(height);
  5272. have_block_height(block_id, height);
  5273. }
  5274. ++pool->work_restart_id;
  5275. if (test_work_current(work)) {
  5276. /* Only accept a work update if this stratum
  5277. * connection is from the current pool */
  5278. if (pool == current_pool()) {
  5279. restart_threads();
  5280. applog(
  5281. (opt_quiet_work_updates ? LOG_DEBUG : LOG_NOTICE),
  5282. "Stratum from pool %d requested work update", pool->pool_no);
  5283. }
  5284. } else
  5285. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  5286. free_work(work);
  5287. }
  5288. if (pool->swork.transparency_time != (time_t)-1 && difftime(time(NULL), pool->swork.transparency_time) > 21.09375) {
  5289. // More than 4 timmills past since requested transactions
  5290. pool->swork.transparency_time = (time_t)-1;
  5291. pool->swork.opaque = true;
  5292. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  5293. pool->pool_no);
  5294. }
  5295. }
  5296. out:
  5297. return NULL;
  5298. }
  5299. static void init_stratum_thread(struct pool *pool)
  5300. {
  5301. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  5302. quit(1, "Failed to create stratum thread");
  5303. }
  5304. static void *longpoll_thread(void *userdata);
  5305. static bool stratum_works(struct pool *pool)
  5306. {
  5307. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  5308. if (!extract_sockaddr(pool, pool->stratum_url))
  5309. return false;
  5310. if (!initiate_stratum(pool))
  5311. return false;
  5312. return true;
  5313. }
  5314. static bool pool_active(struct pool *pool, bool pinging)
  5315. {
  5316. struct timeval tv_getwork, tv_getwork_reply;
  5317. bool ret = false;
  5318. json_t *val;
  5319. CURL *curl;
  5320. int rolltime;
  5321. char *rpc_req;
  5322. struct work *work;
  5323. enum pool_protocol proto;
  5324. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  5325. /* This is the central point we activate stratum when we can */
  5326. curl = curl_easy_init();
  5327. if (unlikely(!curl)) {
  5328. applog(LOG_ERR, "CURL initialisation failed");
  5329. return false;
  5330. }
  5331. if (!(want_gbt || want_getwork))
  5332. goto nohttp;
  5333. work = make_work();
  5334. /* Probe for GBT support on first pass */
  5335. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  5336. tryagain:
  5337. rpc_req = prepare_rpc_req_probe(work, proto, NULL);
  5338. work->pool = pool;
  5339. if (!rpc_req)
  5340. return false;
  5341. pool->probed = false;
  5342. gettimeofday(&tv_getwork, NULL);
  5343. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  5344. true, false, &rolltime, pool, false);
  5345. gettimeofday(&tv_getwork_reply, NULL);
  5346. free(rpc_req);
  5347. /* Detect if a http getwork pool has an X-Stratum header at startup,
  5348. * and if so, switch to that in preference to getwork if it works */
  5349. if (pool->stratum_url && want_stratum && (pool->has_stratum || stratum_works(pool))) {
  5350. curl_easy_cleanup(curl);
  5351. if (!pool->has_stratum) {
  5352. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  5353. if (!pool->rpc_url)
  5354. pool->rpc_url = strdup(pool->stratum_url);
  5355. pool->has_stratum = true;
  5356. }
  5357. free_work(work);
  5358. if (val)
  5359. json_decref(val);
  5360. retry_stratum:
  5361. /* We create the stratum thread for each pool just after
  5362. * successful authorisation. Once the auth flag has been set
  5363. * we never unset it and the stratum thread is responsible for
  5364. * setting/unsetting the active flag */
  5365. if (pool->stratum_auth)
  5366. return pool->stratum_active;
  5367. if (!pool->stratum_active && !initiate_stratum(pool))
  5368. return false;
  5369. if (!auth_stratum(pool))
  5370. return false;
  5371. init_stratum_thread(pool);
  5372. detect_algo = 2;
  5373. return true;
  5374. }
  5375. else if (pool->has_stratum)
  5376. shutdown_stratum(pool);
  5377. if (val) {
  5378. bool rc;
  5379. json_t *res;
  5380. res = json_object_get(val, "result");
  5381. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  5382. goto badwork;
  5383. work->rolltime = rolltime;
  5384. rc = work_decode(pool, work, val);
  5385. if (rc) {
  5386. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  5387. pool->pool_no, pool->rpc_url);
  5388. work->pool = pool;
  5389. memcpy(&(work->tv_getwork), &tv_getwork, sizeof(struct timeval));
  5390. memcpy(&(work->tv_getwork_reply), &tv_getwork_reply, sizeof(struct timeval));
  5391. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  5392. calc_diff(work, 0);
  5393. update_last_work(work);
  5394. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  5395. tq_push(thr_info[stage_thr_id].q, work);
  5396. total_getworks++;
  5397. pool->getwork_requested++;
  5398. ret = true;
  5399. gettimeofday(&pool->tv_idle, NULL);
  5400. } else {
  5401. badwork:
  5402. json_decref(val);
  5403. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  5404. pool->pool_no, pool->rpc_url);
  5405. pool->proto = proto = pool_protocol_fallback(proto);
  5406. if (PLP_NONE != proto)
  5407. goto tryagain;
  5408. free_work(work);
  5409. goto out;
  5410. }
  5411. json_decref(val);
  5412. if (proto != pool->proto) {
  5413. pool->proto = proto;
  5414. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  5415. }
  5416. if (pool->lp_url)
  5417. goto out;
  5418. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  5419. const struct blktmpl_longpoll_req *lp;
  5420. if (work->tmpl && (lp = blktmpl_get_longpoll(work->tmpl))) {
  5421. // NOTE: work_decode takes care of lp id
  5422. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  5423. if (!pool->lp_url)
  5424. return false;
  5425. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  5426. }
  5427. else
  5428. if (pool->hdr_path && want_getwork) {
  5429. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  5430. if (!pool->lp_url)
  5431. return false;
  5432. pool->lp_proto = PLP_GETWORK;
  5433. } else
  5434. pool->lp_url = NULL;
  5435. if (want_longpoll && !pool->lp_started) {
  5436. pool->lp_started = true;
  5437. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  5438. quit(1, "Failed to create pool longpoll thread");
  5439. }
  5440. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  5441. pool->proto = proto;
  5442. goto tryagain;
  5443. } else {
  5444. free_work(work);
  5445. nohttp:
  5446. /* If we failed to parse a getwork, this could be a stratum
  5447. * url without the prefix stratum+tcp:// so let's check it */
  5448. if (extract_sockaddr(pool, pool->rpc_url) && initiate_stratum(pool)) {
  5449. pool->has_stratum = true;
  5450. goto retry_stratum;
  5451. }
  5452. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  5453. pool->pool_no, pool->rpc_url);
  5454. if (!pinging)
  5455. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  5456. }
  5457. out:
  5458. curl_easy_cleanup(curl);
  5459. return ret;
  5460. }
  5461. static inline int cp_prio(void)
  5462. {
  5463. int prio;
  5464. mutex_lock(&control_lock);
  5465. prio = currentpool->prio;
  5466. mutex_unlock(&control_lock);
  5467. return prio;
  5468. }
  5469. static void pool_resus(struct pool *pool)
  5470. {
  5471. if (pool->prio < cp_prio() && pool_strategy == POOL_FAILOVER) {
  5472. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  5473. switch_pools(NULL);
  5474. } else
  5475. applog(LOG_INFO, "Pool %d %s resumed returning work", pool->pool_no, pool->rpc_url);
  5476. }
  5477. static struct work *hash_pop(void)
  5478. {
  5479. struct work *work = NULL, *tmp;
  5480. int hc;
  5481. retry:
  5482. mutex_lock(stgd_lock);
  5483. while (!getq->frozen && !HASH_COUNT(staged_work))
  5484. pthread_cond_wait(&getq->cond, stgd_lock);
  5485. hc = HASH_COUNT(staged_work);
  5486. /* Find clone work if possible, to allow masters to be reused */
  5487. if (hc > staged_rollable) {
  5488. HASH_ITER(hh, staged_work, work, tmp) {
  5489. if (!work_rollable(work))
  5490. break;
  5491. }
  5492. } else
  5493. work = staged_work;
  5494. if (can_roll(work) && should_roll(work))
  5495. {
  5496. // Instead of consuming it, force it to be cloned and grab the clone
  5497. mutex_unlock(stgd_lock);
  5498. clone_available();
  5499. goto retry;
  5500. }
  5501. HASH_DEL(staged_work, work);
  5502. if (work_rollable(work))
  5503. staged_rollable--;
  5504. /* Signal the getwork scheduler to look for more work */
  5505. pthread_cond_signal(&gws_cond);
  5506. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  5507. pthread_cond_signal(&getq->cond);
  5508. mutex_unlock(stgd_lock);
  5509. return work;
  5510. }
  5511. /* Clones work by rolling it if possible, and returning a clone instead of the
  5512. * original work item which gets staged again to possibly be rolled again in
  5513. * the future */
  5514. static struct work *clone_work(struct work *work)
  5515. {
  5516. int mrs = mining_threads + opt_queue - total_staged();
  5517. struct work *work_clone;
  5518. bool cloned;
  5519. if (mrs < 1)
  5520. return work;
  5521. cloned = false;
  5522. work_clone = make_clone(work);
  5523. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  5524. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  5525. stage_work(work_clone);
  5526. roll_work(work);
  5527. work_clone = make_clone(work);
  5528. /* Roll it again to prevent duplicates should this be used
  5529. * directly later on */
  5530. roll_work(work);
  5531. cloned = true;
  5532. }
  5533. if (cloned) {
  5534. stage_work(work);
  5535. return work_clone;
  5536. }
  5537. free_work(work_clone);
  5538. return work;
  5539. }
  5540. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  5541. {
  5542. unsigned char hash1[32];
  5543. sha2(data, len, hash1);
  5544. sha2(hash1, 32, hash);
  5545. }
  5546. /* Diff 1 is a 256 bit unsigned integer of
  5547. * 0x00000000ffff0000000000000000000000000000000000000000000000000000
  5548. * so we use a big endian 64 bit unsigned integer centred on the 5th byte to
  5549. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  5550. static void bdiff_target_leadzero(unsigned char *target, double diff)
  5551. {
  5552. uint64_t *data64, h64;
  5553. double d64;
  5554. d64 = diffone;
  5555. d64 /= diff;
  5556. d64 = ceil(d64);
  5557. h64 = d64;
  5558. memset(target, 0, 32);
  5559. if (d64 < 18446744073709551616.0) {
  5560. unsigned char *rtarget = target;
  5561. memset(rtarget, 0, 32);
  5562. if (opt_scrypt)
  5563. data64 = (uint64_t *)(rtarget + 2);
  5564. else
  5565. data64 = (uint64_t *)(rtarget + 4);
  5566. *data64 = htobe64(h64);
  5567. } else {
  5568. /* Support for the classic all FFs just-below-1 diff */
  5569. if (opt_scrypt)
  5570. memset(&target[2], 0xff, 30);
  5571. else
  5572. memset(&target[4], 0xff, 28);
  5573. }
  5574. }
  5575. static inline
  5576. void set_work_target(struct work *work, double diff)
  5577. {
  5578. unsigned char rtarget[32];
  5579. bdiff_target_leadzero(rtarget, diff);
  5580. swab256(work->target, rtarget);
  5581. if (opt_debug) {
  5582. char *htarget = bin2hex(rtarget, 32);
  5583. applog(LOG_DEBUG, "Generated target %s", htarget);
  5584. free(htarget);
  5585. }
  5586. }
  5587. /* Generates stratum based work based on the most recent notify information
  5588. * from the pool. This will keep generating work while a pool is down so we use
  5589. * other means to detect when the pool has died in stratum_thread */
  5590. static void gen_stratum_work(struct pool *pool, struct work *work)
  5591. {
  5592. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  5593. char *header, *merkle_hash;
  5594. uint32_t *data32, *swap32;
  5595. size_t alloc_len;
  5596. int i;
  5597. clean_work(work);
  5598. mutex_lock(&pool->pool_lock);
  5599. /* Generate coinbase */
  5600. work->nonce2 = bin2hex((const unsigned char *)&pool->nonce2, pool->n2size);
  5601. pool->nonce2++;
  5602. alloc_len = pool->swork.cb_len;
  5603. align_len(&alloc_len);
  5604. coinbase = calloc(alloc_len, 1);
  5605. if (unlikely(!coinbase))
  5606. quit(1, "Failed to calloc coinbase in gen_stratum_work");
  5607. hex2bin(coinbase, pool->swork.coinbase1, pool->swork.cb1_len);
  5608. hex2bin(coinbase + pool->swork.cb1_len, pool->nonce1, pool->n1_len);
  5609. hex2bin(coinbase + pool->swork.cb1_len + pool->n1_len, work->nonce2, pool->n2size);
  5610. hex2bin(coinbase + pool->swork.cb1_len + pool->n1_len + pool->n2size, pool->swork.coinbase2, pool->swork.cb2_len);
  5611. /* Generate merkle root */
  5612. gen_hash(coinbase, merkle_root, pool->swork.cb_len);
  5613. free(coinbase);
  5614. memcpy(merkle_sha, merkle_root, 32);
  5615. for (i = 0; i < pool->swork.merkles; i++) {
  5616. unsigned char merkle_bin[32];
  5617. hex2bin(merkle_bin, pool->swork.merkle[i], 32);
  5618. memcpy(merkle_sha + 32, merkle_bin, 32);
  5619. gen_hash(merkle_sha, merkle_root, 64);
  5620. memcpy(merkle_sha, merkle_root, 32);
  5621. }
  5622. data32 = (uint32_t *)merkle_sha;
  5623. swap32 = (uint32_t *)merkle_root;
  5624. for (i = 0; i < 32 / 4; i++)
  5625. swap32[i] = swab32(data32[i]);
  5626. merkle_hash = bin2hex((const unsigned char *)merkle_root, 32);
  5627. header = calloc(pool->swork.header_len, 1);
  5628. if (unlikely(!header))
  5629. quit(1, "Failed to calloc header in gen_stratum_work");
  5630. sprintf(header, "%s%s%s%s%s%s%s",
  5631. pool->swork.bbversion,
  5632. pool->swork.prev_hash,
  5633. merkle_hash,
  5634. pool->swork.ntime,
  5635. pool->swork.nbit,
  5636. "00000000", /* nonce */
  5637. workpadding);
  5638. /* Store the stratum work diff to check it still matches the pool's
  5639. * stratum diff when submitting shares */
  5640. work->sdiff = pool->swork.diff;
  5641. /* Copy parameters required for share submission */
  5642. work->job_id = strdup(pool->swork.job_id);
  5643. work->ntime = strdup(pool->swork.ntime);
  5644. if (pool->sessionid)
  5645. work->sessionid = strdup(pool->sessionid);
  5646. mutex_unlock(&pool->pool_lock);
  5647. applog(LOG_DEBUG, "Generated stratum merkle %s", merkle_hash);
  5648. applog(LOG_DEBUG, "Generated stratum header %s", header);
  5649. applog(LOG_DEBUG, "Work job_id %s nonce2 %s ntime %s", work->job_id, work->nonce2, work->ntime);
  5650. free(merkle_hash);
  5651. /* Convert hex data to binary data for work */
  5652. if (unlikely(!hex2bin(work->data, header, 128)))
  5653. quit(1, "Failed to convert header to data in gen_stratum_work");
  5654. free(header);
  5655. calc_midstate(work);
  5656. set_work_target(work, work->sdiff);
  5657. local_work++;
  5658. work->pool = pool;
  5659. work->stratum = true;
  5660. work->blk.nonce = 0;
  5661. work->id = total_work++;
  5662. work->longpoll = false;
  5663. work->getwork_mode = GETWORK_MODE_STRATUM;
  5664. work->work_restart_id = work->pool->work_restart_id;
  5665. calc_diff(work, 0);
  5666. gettimeofday(&work->tv_staged, NULL);
  5667. }
  5668. void request_work(struct thr_info *thr)
  5669. {
  5670. struct cgpu_info *cgpu = thr->cgpu;
  5671. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  5672. /* Tell the watchdog thread this thread is waiting on getwork and
  5673. * should not be restarted */
  5674. thread_reportout(thr);
  5675. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  5676. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  5677. {
  5678. if (proc->threads)
  5679. break;
  5680. thread_reportout(proc->thr[0]);
  5681. }
  5682. gettimeofday(&dev_stats->_get_start, NULL);
  5683. }
  5684. // FIXME: Make this non-blocking (and remove HACK above)
  5685. struct work *get_work(struct thr_info *thr)
  5686. {
  5687. const int thr_id = thr->id;
  5688. struct cgpu_info *cgpu = thr->cgpu;
  5689. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  5690. struct cgminer_stats *pool_stats;
  5691. struct timeval tv_get;
  5692. struct work *work = NULL;
  5693. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  5694. while (!work) {
  5695. work = hash_pop();
  5696. if (stale_work(work, false)) {
  5697. discard_work(work);
  5698. work = NULL;
  5699. wake_gws();
  5700. }
  5701. }
  5702. applog(LOG_DEBUG, "%"PRIpreprv": Got work from get queue to get work for thread %d", cgpu->proc_repr, thr_id);
  5703. work->thr_id = thr_id;
  5704. thread_reportin(thr);
  5705. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  5706. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  5707. {
  5708. if (proc->threads)
  5709. break;
  5710. thread_reportin(proc->thr[0]);
  5711. }
  5712. work->mined = true;
  5713. work->blk.nonce = 0;
  5714. gettimeofday(&tv_get, NULL);
  5715. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  5716. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  5717. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  5718. dev_stats->getwork_wait_max = tv_get;
  5719. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  5720. dev_stats->getwork_wait_min = tv_get;
  5721. ++dev_stats->getwork_calls;
  5722. pool_stats = &(work->pool->cgminer_stats);
  5723. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  5724. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  5725. pool_stats->getwork_wait_max = tv_get;
  5726. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  5727. pool_stats->getwork_wait_min = tv_get;
  5728. ++pool_stats->getwork_calls;
  5729. return work;
  5730. }
  5731. void submit_work_async(struct work *work_in, struct timeval *tv_work_found)
  5732. {
  5733. struct work *work = copy_work(work_in);
  5734. if (tv_work_found)
  5735. memcpy(&(work->tv_work_found), tv_work_found, sizeof(struct timeval));
  5736. applog(LOG_DEBUG, "Pushing submit work to work thread");
  5737. mutex_lock(&submitting_lock);
  5738. ++total_submitting;
  5739. list_add_tail(&work->list, &submit_waiting);
  5740. mutex_unlock(&submitting_lock);
  5741. notifier_wake(submit_waiting_notifier);
  5742. }
  5743. enum test_nonce2_result hashtest2(struct work *work, bool checktarget)
  5744. {
  5745. uint32_t *hash2_32 = (uint32_t *)&work->hash[0];
  5746. hash_data(work->hash, work->data);
  5747. if (hash2_32[7] != 0)
  5748. return TNR_BAD;
  5749. if (!checktarget)
  5750. return TNR_GOOD;
  5751. if (!hash_target_check_v(work->hash, work->target))
  5752. return TNR_HIGH;
  5753. return TNR_GOOD;
  5754. }
  5755. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  5756. {
  5757. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  5758. *work_nonce = htole32(nonce);
  5759. #ifdef USE_SCRYPT
  5760. if (opt_scrypt) {
  5761. if (!scrypt_test(work->data, work->target, nonce))
  5762. return TNR_BAD;
  5763. return TNR_GOOD;
  5764. }
  5765. #endif
  5766. return hashtest2(work, checktarget);
  5767. }
  5768. void submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  5769. {
  5770. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  5771. uint32_t bak_nonce = *work_nonce;
  5772. struct timeval tv_work_found;
  5773. gettimeofday(&tv_work_found, NULL);
  5774. *work_nonce = htole32(nonce);
  5775. mutex_lock(&stats_lock);
  5776. total_diff1++;
  5777. thr->cgpu->diff1++;
  5778. work->pool->diff1++;
  5779. mutex_unlock(&stats_lock);
  5780. /* Do one last check before attempting to submit the work */
  5781. /* Side effect: sets work->data for us */
  5782. switch (test_nonce2(work, nonce)) {
  5783. case TNR_BAD:
  5784. {
  5785. struct cgpu_info *cgpu = thr->cgpu;
  5786. applog(LOG_WARNING, "%"PRIpreprv": invalid nonce - HW error",
  5787. cgpu->proc_repr);
  5788. mutex_lock(&stats_lock);
  5789. ++hw_errors;
  5790. ++thr->cgpu->hw_errors;
  5791. mutex_unlock(&stats_lock);
  5792. if (thr->cgpu->api->hw_error)
  5793. thr->cgpu->api->hw_error(thr);
  5794. goto out;
  5795. }
  5796. case TNR_HIGH:
  5797. // Share above target, normal
  5798. /* Check the diff of the share, even if it didn't reach the
  5799. * target, just to set the best share value if it's higher. */
  5800. share_diff(work);
  5801. goto out;
  5802. case TNR_GOOD:
  5803. break;
  5804. }
  5805. submit_work_async(work, &tv_work_found);
  5806. out:
  5807. *work_nonce = bak_nonce;
  5808. }
  5809. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  5810. {
  5811. if (wdiff->tv_sec > opt_scantime ||
  5812. work->blk.nonce >= MAXTHREADS - hashes ||
  5813. hashes >= 0xfffffffe ||
  5814. stale_work(work, false))
  5815. return true;
  5816. return false;
  5817. }
  5818. void mt_disable_start(struct thr_info *mythr)
  5819. {
  5820. int thr_id = mythr->id;
  5821. hashmeter2(mythr);
  5822. mythr->prev_work = mythr->work;
  5823. mythr->work = NULL;
  5824. mythr->_job_transition_in_progress = false;
  5825. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  5826. mythr->rolling = mythr->cgpu->rolling = 0;
  5827. thread_reportout(mythr);
  5828. }
  5829. void mt_disable_finish(struct thr_info *mythr)
  5830. {
  5831. int thr_id = mythr->id;
  5832. const struct device_api *api = mythr->cgpu->api;
  5833. thread_reportin(mythr);
  5834. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  5835. if (api->thread_enable)
  5836. api->thread_enable(mythr);
  5837. }
  5838. void mt_disable(struct thr_info *mythr)
  5839. {
  5840. mt_disable_start(mythr);
  5841. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  5842. do {
  5843. notifier_read(mythr->notifier);
  5844. } while (mythr->pause);
  5845. mt_disable_finish(mythr);
  5846. }
  5847. enum {
  5848. STAT_SLEEP_INTERVAL = 1,
  5849. STAT_CTR_INTERVAL = 10000000,
  5850. FAILURE_INTERVAL = 30,
  5851. };
  5852. /* Stage another work item from the work returned in a longpoll */
  5853. static void convert_to_work(json_t *val, int rolltime, struct pool *pool, struct work *work, struct timeval *tv_lp, struct timeval *tv_lp_reply)
  5854. {
  5855. bool rc;
  5856. work->rolltime = rolltime;
  5857. rc = work_decode(pool, work, val);
  5858. if (unlikely(!rc)) {
  5859. applog(LOG_ERR, "Could not convert longpoll data to work");
  5860. free_work(work);
  5861. return;
  5862. }
  5863. total_getworks++;
  5864. pool->getwork_requested++;
  5865. work->pool = pool;
  5866. memcpy(&(work->tv_getwork), tv_lp, sizeof(struct timeval));
  5867. memcpy(&(work->tv_getwork_reply), tv_lp_reply, sizeof(struct timeval));
  5868. calc_diff(work, 0);
  5869. if (pool->enabled == POOL_REJECTING)
  5870. work->mandatory = true;
  5871. work->longpoll = true;
  5872. work->getwork_mode = GETWORK_MODE_LP;
  5873. update_last_work(work);
  5874. /* We'll be checking this work item twice, but we already know it's
  5875. * from a new block so explicitly force the new block detection now
  5876. * rather than waiting for it to hit the stage thread. This also
  5877. * allows testwork to know whether LP discovered the block or not. */
  5878. test_work_current(work);
  5879. /* Don't use backup LPs as work if we have failover-only enabled. Use
  5880. * the longpoll work from a pool that has been rejecting shares as a
  5881. * way to detect when the pool has recovered.
  5882. */
  5883. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  5884. free_work(work);
  5885. return;
  5886. }
  5887. work = clone_work(work);
  5888. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  5889. stage_work(work);
  5890. applog(LOG_DEBUG, "Converted longpoll data to work");
  5891. }
  5892. /* If we want longpoll, enable it for the chosen default pool, or, if
  5893. * the pool does not support longpoll, find the first one that does
  5894. * and use its longpoll support */
  5895. static struct pool *select_longpoll_pool(struct pool *cp)
  5896. {
  5897. int i;
  5898. if (cp->lp_url)
  5899. return cp;
  5900. for (i = 0; i < total_pools; i++) {
  5901. struct pool *pool = pools[i];
  5902. if (pool->has_stratum || pool->lp_url)
  5903. return pool;
  5904. }
  5905. return NULL;
  5906. }
  5907. /* This will make the longpoll thread wait till it's the current pool, or it
  5908. * has been flagged as rejecting, before attempting to open any connections.
  5909. */
  5910. static void wait_lpcurrent(struct pool *pool)
  5911. {
  5912. if (cnx_needed(pool))
  5913. return;
  5914. while (pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  5915. mutex_lock(&lp_lock);
  5916. pthread_cond_wait(&lp_cond, &lp_lock);
  5917. mutex_unlock(&lp_lock);
  5918. }
  5919. }
  5920. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  5921. struct pool *pool = vpool;
  5922. curl_socket_t sock = socket(addr->family, addr->socktype, addr->protocol);
  5923. pool->lp_socket = sock;
  5924. return sock;
  5925. }
  5926. static void *longpoll_thread(void *userdata)
  5927. {
  5928. struct pool *cp = (struct pool *)userdata;
  5929. /* This *pool is the source of the actual longpoll, not the pool we've
  5930. * tied it to */
  5931. struct pool *pool = NULL;
  5932. struct timeval start, reply, end;
  5933. CURL *curl = NULL;
  5934. int failures = 0;
  5935. char *lp_url;
  5936. int rolltime;
  5937. RenameThread("longpoll");
  5938. curl = curl_easy_init();
  5939. if (unlikely(!curl)) {
  5940. applog(LOG_ERR, "CURL initialisation failed");
  5941. return NULL;
  5942. }
  5943. retry_pool:
  5944. pool = select_longpoll_pool(cp);
  5945. if (!pool) {
  5946. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  5947. while (!pool) {
  5948. sleep(60);
  5949. pool = select_longpoll_pool(cp);
  5950. }
  5951. }
  5952. if (pool->has_stratum) {
  5953. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  5954. cp->rpc_url, pool->rpc_url);
  5955. goto out;
  5956. }
  5957. /* Any longpoll from any pool is enough for this to be true */
  5958. have_longpoll = true;
  5959. wait_lpcurrent(cp);
  5960. {
  5961. lp_url = pool->lp_url;
  5962. if (cp == pool)
  5963. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  5964. else
  5965. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  5966. }
  5967. while (42) {
  5968. json_t *val, *soval;
  5969. struct work *work = make_work();
  5970. char *lpreq;
  5971. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id);
  5972. work->pool = pool;
  5973. if (!lpreq)
  5974. goto lpfail;
  5975. wait_lpcurrent(cp);
  5976. gettimeofday(&start, NULL);
  5977. /* Longpoll connections can be persistent for a very long time
  5978. * and any number of issues could have come up in the meantime
  5979. * so always establish a fresh connection instead of relying on
  5980. * a persistent one. */
  5981. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  5982. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  5983. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  5984. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  5985. lpreq, false, true, &rolltime, pool, false);
  5986. pool->lp_socket = CURL_SOCKET_BAD;
  5987. gettimeofday(&reply, NULL);
  5988. free(lpreq);
  5989. if (likely(val)) {
  5990. soval = json_object_get(json_object_get(val, "result"), "submitold");
  5991. if (soval)
  5992. pool->submit_old = json_is_true(soval);
  5993. else
  5994. pool->submit_old = false;
  5995. convert_to_work(val, rolltime, pool, work, &start, &reply);
  5996. failures = 0;
  5997. json_decref(val);
  5998. } else {
  5999. /* Some pools regularly drop the longpoll request so
  6000. * only see this as longpoll failure if it happens
  6001. * immediately and just restart it the rest of the
  6002. * time. */
  6003. gettimeofday(&end, NULL);
  6004. free_work(work);
  6005. if (end.tv_sec - start.tv_sec > 30)
  6006. continue;
  6007. if (failures == 1)
  6008. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  6009. lpfail:
  6010. sleep(30);
  6011. }
  6012. if (pool != cp) {
  6013. pool = select_longpoll_pool(cp);
  6014. if (pool->has_stratum) {
  6015. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  6016. cp->rpc_url, pool->rpc_url);
  6017. break;
  6018. }
  6019. if (unlikely(!pool))
  6020. goto retry_pool;
  6021. }
  6022. if (unlikely(pool->removed))
  6023. break;
  6024. }
  6025. out:
  6026. curl_easy_cleanup(curl);
  6027. return NULL;
  6028. }
  6029. static void stop_longpoll(void)
  6030. {
  6031. int i;
  6032. want_longpoll = false;
  6033. for (i = 0; i < total_pools; ++i)
  6034. {
  6035. struct pool *pool = pools[i];
  6036. if (unlikely(!pool->lp_started))
  6037. continue;
  6038. pool->lp_started = false;
  6039. pthread_cancel(pool->longpoll_thread);
  6040. }
  6041. have_longpoll = false;
  6042. }
  6043. static void start_longpoll(void)
  6044. {
  6045. int i;
  6046. want_longpoll = true;
  6047. for (i = 0; i < total_pools; ++i)
  6048. {
  6049. struct pool *pool = pools[i];
  6050. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  6051. continue;
  6052. pool->lp_started = true;
  6053. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  6054. quit(1, "Failed to create pool longpoll thread");
  6055. }
  6056. }
  6057. void reinit_device(struct cgpu_info *cgpu)
  6058. {
  6059. if (cgpu->api->reinit_device)
  6060. cgpu->api->reinit_device(cgpu);
  6061. }
  6062. static struct timeval rotate_tv;
  6063. /* We reap curls if they are unused for over a minute */
  6064. static void reap_curl(struct pool *pool)
  6065. {
  6066. struct curl_ent *ent, *iter;
  6067. struct timeval now;
  6068. int reaped = 0;
  6069. gettimeofday(&now, NULL);
  6070. mutex_lock(&pool->pool_lock);
  6071. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  6072. if (pool->curls < 2)
  6073. break;
  6074. if (now.tv_sec - ent->tv.tv_sec > 300) {
  6075. reaped++;
  6076. pool->curls--;
  6077. list_del(&ent->node);
  6078. curl_easy_cleanup(ent->curl);
  6079. free(ent);
  6080. }
  6081. }
  6082. mutex_unlock(&pool->pool_lock);
  6083. if (reaped)
  6084. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  6085. }
  6086. static void *watchpool_thread(void __maybe_unused *userdata)
  6087. {
  6088. int intervals = 0;
  6089. RenameThread("watchpool");
  6090. while (42) {
  6091. struct timeval now;
  6092. int i;
  6093. if (++intervals > 20)
  6094. intervals = 0;
  6095. gettimeofday(&now, NULL);
  6096. for (i = 0; i < total_pools; i++) {
  6097. struct pool *pool = pools[i];
  6098. if (!opt_benchmark)
  6099. reap_curl(pool);
  6100. /* Get a rolling utility per pool over 10 mins */
  6101. if (intervals > 19) {
  6102. int shares = pool->diff1 - pool->last_shares;
  6103. pool->last_shares = pool->diff1;
  6104. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  6105. pool->shares = pool->utility;
  6106. }
  6107. if ((pool->enabled == POOL_DISABLED || pool->has_stratum) && pool->probed)
  6108. continue;
  6109. /* Test pool is idle once every minute */
  6110. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  6111. gettimeofday(&pool->tv_idle, NULL);
  6112. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  6113. pool_resus(pool);
  6114. }
  6115. }
  6116. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  6117. gettimeofday(&rotate_tv, NULL);
  6118. switch_pools(NULL);
  6119. }
  6120. sleep(30);
  6121. }
  6122. return NULL;
  6123. }
  6124. void mt_enable(struct thr_info *thr)
  6125. {
  6126. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  6127. notifier_wake(thr->notifier);
  6128. }
  6129. void proc_enable(struct cgpu_info *cgpu)
  6130. {
  6131. int j;
  6132. cgpu->deven = DEV_ENABLED;
  6133. for (j = cgpu->threads ?: 1; j--; )
  6134. mt_enable(cgpu->thr[j]);
  6135. }
  6136. #define device_recovered(cgpu) proc_enable(cgpu)
  6137. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  6138. * the screen at regular intervals, and restarts threads if they appear to have
  6139. * died. */
  6140. #define WATCHDOG_INTERVAL 3
  6141. #define WATCHDOG_SICK_TIME 60
  6142. #define WATCHDOG_DEAD_TIME 600
  6143. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  6144. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  6145. static void *watchdog_thread(void __maybe_unused *userdata)
  6146. {
  6147. const unsigned int interval = WATCHDOG_INTERVAL;
  6148. struct timeval zero_tv;
  6149. RenameThread("watchdog");
  6150. memset(&zero_tv, 0, sizeof(struct timeval));
  6151. gettimeofday(&rotate_tv, NULL);
  6152. while (1) {
  6153. int i;
  6154. struct timeval now;
  6155. sleep(interval);
  6156. discard_stale();
  6157. hashmeter(-1, &zero_tv, 0);
  6158. #ifdef HAVE_CURSES
  6159. if (curses_active_locked()) {
  6160. change_logwinsize();
  6161. curses_print_status();
  6162. for (i = 0; i < mining_threads; i++)
  6163. curses_print_devstatus(i);
  6164. touchwin(statuswin);
  6165. wrefresh(statuswin);
  6166. touchwin(logwin);
  6167. wrefresh(logwin);
  6168. unlock_curses();
  6169. }
  6170. #endif
  6171. gettimeofday(&now, NULL);
  6172. if (!sched_paused && !should_run()) {
  6173. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  6174. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  6175. if (!schedstart.enable) {
  6176. quit(0, "Terminating execution as planned");
  6177. break;
  6178. }
  6179. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  6180. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  6181. sched_paused = true;
  6182. for (i = 0; i < mining_threads; i++) {
  6183. struct thr_info *thr;
  6184. thr = &thr_info[i];
  6185. thr->pause = true;
  6186. }
  6187. } else if (sched_paused && should_run()) {
  6188. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  6189. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  6190. if (schedstop.enable)
  6191. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  6192. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  6193. sched_paused = false;
  6194. for (i = 0; i < mining_threads; i++) {
  6195. struct thr_info *thr;
  6196. thr = &thr_info[i];
  6197. thr->pause = false;
  6198. }
  6199. for (i = 0; i < total_devices; ++i)
  6200. {
  6201. struct cgpu_info *cgpu = devices[i];
  6202. /* Don't touch disabled devices */
  6203. if (cgpu->deven == DEV_DISABLED)
  6204. continue;
  6205. proc_enable(cgpu);
  6206. }
  6207. }
  6208. for (i = 0; i < total_devices; ++i) {
  6209. struct cgpu_info *cgpu = devices[i];
  6210. struct thr_info *thr;
  6211. thr = cgpu->thr[0];
  6212. enum dev_enable *denable;
  6213. char *dev_str = cgpu->proc_repr;
  6214. int gpu;
  6215. if (cgpu->api->get_stats)
  6216. cgpu->api->get_stats(cgpu);
  6217. gpu = cgpu->device_id;
  6218. denable = &cgpu->deven;
  6219. #ifdef HAVE_ADL
  6220. if (adl_active && cgpu->has_adl)
  6221. gpu_autotune(gpu, denable);
  6222. if (opt_debug && cgpu->has_adl) {
  6223. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  6224. float temp = 0, vddc = 0;
  6225. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  6226. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMHz V: %.3fV A: %d%% P: %d%%",
  6227. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  6228. }
  6229. #endif
  6230. /* Thread is disabled */
  6231. if (*denable == DEV_DISABLED)
  6232. continue;
  6233. else
  6234. if (*denable == DEV_RECOVER_ERR) {
  6235. if (opt_restart && difftime(time(NULL), cgpu->device_last_not_well) > cgpu->reinit_backoff) {
  6236. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  6237. dev_str);
  6238. if (cgpu->reinit_backoff < 300)
  6239. cgpu->reinit_backoff *= 2;
  6240. device_recovered(cgpu);
  6241. }
  6242. continue;
  6243. }
  6244. else
  6245. if (*denable == DEV_RECOVER) {
  6246. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  6247. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  6248. dev_str);
  6249. device_recovered(cgpu);
  6250. }
  6251. cgpu->device_last_not_well = time(NULL);
  6252. cgpu->device_not_well_reason = REASON_DEV_THERMAL_CUTOFF;
  6253. continue;
  6254. }
  6255. else
  6256. if (cgpu->temp > cgpu->cutofftemp)
  6257. {
  6258. applog(LOG_WARNING, "%s hit thermal cutoff limit, disabling!",
  6259. dev_str);
  6260. *denable = DEV_RECOVER;
  6261. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  6262. }
  6263. if (thr->getwork) {
  6264. if (cgpu->status == LIFE_WELL && thr->getwork < now.tv_sec - opt_log_interval) {
  6265. int thrid;
  6266. bool cgpu_idle = true;
  6267. thr->rolling = 0;
  6268. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  6269. if (!cgpu->thr[thrid]->getwork)
  6270. cgpu_idle = false;
  6271. if (cgpu_idle) {
  6272. cgpu->rolling = 0;
  6273. cgpu->status = LIFE_WAIT;
  6274. }
  6275. }
  6276. continue;
  6277. }
  6278. else if (cgpu->status == LIFE_WAIT)
  6279. cgpu->status = LIFE_WELL;
  6280. #ifdef WANT_CPUMINE
  6281. if (!strcmp(cgpu->api->dname, "cpu"))
  6282. continue;
  6283. #endif
  6284. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  6285. if (cgpu->status != LIFE_INIT)
  6286. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  6287. cgpu->status = LIFE_WELL;
  6288. cgpu->device_last_well = time(NULL);
  6289. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  6290. thr->rolling = cgpu->rolling = 0;
  6291. cgpu->status = LIFE_SICK;
  6292. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  6293. gettimeofday(&thr->sick, NULL);
  6294. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  6295. #ifdef HAVE_ADL
  6296. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  6297. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  6298. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  6299. } else
  6300. #endif
  6301. if (opt_restart) {
  6302. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  6303. reinit_device(cgpu);
  6304. }
  6305. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  6306. cgpu->status = LIFE_DEAD;
  6307. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  6308. gettimeofday(&thr->sick, NULL);
  6309. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  6310. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  6311. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  6312. /* Attempt to restart a GPU that's sick or dead once every minute */
  6313. gettimeofday(&thr->sick, NULL);
  6314. #ifdef HAVE_ADL
  6315. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  6316. /* Again do not attempt to restart a device that may have hard hung */
  6317. } else
  6318. #endif
  6319. if (opt_restart)
  6320. reinit_device(cgpu);
  6321. }
  6322. }
  6323. }
  6324. return NULL;
  6325. }
  6326. static void log_print_status(struct cgpu_info *cgpu)
  6327. {
  6328. char logline[255];
  6329. get_statline(logline, cgpu);
  6330. applog(LOG_WARNING, "%s", logline);
  6331. }
  6332. void print_summary(void)
  6333. {
  6334. struct timeval diff;
  6335. int hours, mins, secs, i;
  6336. double utility, efficiency = 0.0;
  6337. timersub(&total_tv_end, &total_tv_start, &diff);
  6338. hours = diff.tv_sec / 3600;
  6339. mins = (diff.tv_sec % 3600) / 60;
  6340. secs = diff.tv_sec % 60;
  6341. utility = total_accepted / total_secs * 60;
  6342. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  6343. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  6344. applog(LOG_WARNING, "Started at %s", datestamp);
  6345. if (total_pools == 1)
  6346. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  6347. #ifdef WANT_CPUMINE
  6348. if (opt_n_threads)
  6349. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  6350. #endif
  6351. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  6352. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  6353. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  6354. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  6355. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  6356. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  6357. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  6358. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  6359. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  6360. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  6361. if (total_accepted || total_rejected)
  6362. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  6363. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  6364. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  6365. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  6366. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  6367. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  6368. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  6369. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  6370. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  6371. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  6372. if (total_pools > 1) {
  6373. for (i = 0; i < total_pools; i++) {
  6374. struct pool *pool = pools[i];
  6375. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  6376. if (pool->solved)
  6377. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  6378. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  6379. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  6380. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  6381. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  6382. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  6383. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  6384. if (pool->accepted || pool->rejected)
  6385. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  6386. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  6387. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  6388. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  6389. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  6390. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  6391. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  6392. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  6393. }
  6394. }
  6395. applog(LOG_WARNING, "Summary of per device statistics:\n");
  6396. for (i = 0; i < total_devices; ++i)
  6397. {
  6398. struct cgpu_info *cgpu = devices[i];
  6399. if ((!cgpu->proc_id) && cgpu->next_proc)
  6400. {
  6401. // Device summary line
  6402. opt_show_procs = false;
  6403. log_print_status(cgpu);
  6404. opt_show_procs = true;
  6405. }
  6406. log_print_status(devices[i]);
  6407. }
  6408. if (opt_shares)
  6409. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  6410. fflush(stdout);
  6411. fflush(stderr);
  6412. if (opt_shares > total_accepted)
  6413. applog(LOG_WARNING, "WARNING - Mined only %d shares of %d requested.", total_accepted, opt_shares);
  6414. }
  6415. static void clean_up(void)
  6416. {
  6417. #ifdef HAVE_OPENCL
  6418. clear_adl(nDevs);
  6419. #endif
  6420. #ifdef HAVE_LIBUSB
  6421. libusb_exit(NULL);
  6422. #endif
  6423. gettimeofday(&total_tv_end, NULL);
  6424. #ifdef HAVE_CURSES
  6425. disable_curses();
  6426. #endif
  6427. if (!opt_realquiet && successful_connect)
  6428. print_summary();
  6429. if (opt_n_threads)
  6430. free(cpus);
  6431. curl_global_cleanup();
  6432. }
  6433. void quit(int status, const char *format, ...)
  6434. {
  6435. va_list ap;
  6436. clean_up();
  6437. if (format) {
  6438. va_start(ap, format);
  6439. vfprintf(stderr, format, ap);
  6440. va_end(ap);
  6441. }
  6442. fprintf(stderr, "\n");
  6443. fflush(stderr);
  6444. if (status) {
  6445. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  6446. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  6447. const char **p = NULL;
  6448. // NOTE debugger can bypass with: p = &p
  6449. *p = format; // Segfault, hopefully dumping core
  6450. }
  6451. }
  6452. #if defined(unix)
  6453. if (forkpid > 0) {
  6454. kill(forkpid, SIGTERM);
  6455. forkpid = 0;
  6456. }
  6457. #endif
  6458. exit(status);
  6459. }
  6460. #ifdef HAVE_CURSES
  6461. char *curses_input(const char *query)
  6462. {
  6463. char *input;
  6464. echo();
  6465. input = malloc(255);
  6466. if (!input)
  6467. quit(1, "Failed to malloc input");
  6468. leaveok(logwin, false);
  6469. wlogprint("%s:\n", query);
  6470. wgetnstr(logwin, input, 255);
  6471. if (!strlen(input))
  6472. strcpy(input, "-1");
  6473. leaveok(logwin, true);
  6474. noecho();
  6475. return input;
  6476. }
  6477. #endif
  6478. void add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  6479. {
  6480. pool->rpc_url = url;
  6481. pool->rpc_user = user;
  6482. pool->rpc_pass = pass;
  6483. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  6484. if (!pool->rpc_userpass)
  6485. quit(1, "Failed to malloc userpass");
  6486. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  6487. enable_pool(pool);
  6488. /* Prevent noise on startup */
  6489. pool->lagging = true;
  6490. /* Test the pool is not idle if we're live running, otherwise
  6491. * it will be tested separately */
  6492. if (live && !pool_active(pool, false)) {
  6493. gettimeofday(&pool->tv_idle, NULL);
  6494. pool->idle = true;
  6495. }
  6496. }
  6497. #ifdef HAVE_CURSES
  6498. static bool input_pool(bool live)
  6499. {
  6500. char *url = NULL, *user = NULL, *pass = NULL;
  6501. struct pool *pool;
  6502. bool ret = false;
  6503. immedok(logwin, true);
  6504. wlogprint("Input server details.\n");
  6505. url = curses_input("URL");
  6506. if (!url)
  6507. goto out;
  6508. user = curses_input("Username");
  6509. if (!user)
  6510. goto out;
  6511. pass = curses_input("Password");
  6512. if (!pass)
  6513. goto out;
  6514. pool = add_pool();
  6515. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  6516. strncmp(url, "https://", 8)) {
  6517. char *httpinput;
  6518. httpinput = malloc(256);
  6519. if (!httpinput)
  6520. quit(1, "Failed to malloc httpinput");
  6521. strcpy(httpinput, "http://");
  6522. strncat(httpinput, url, 248);
  6523. free(url);
  6524. url = httpinput;
  6525. }
  6526. add_pool_details(pool, live, url, user, pass);
  6527. ret = true;
  6528. out:
  6529. immedok(logwin, false);
  6530. if (!ret) {
  6531. if (url)
  6532. free(url);
  6533. if (user)
  6534. free(user);
  6535. if (pass)
  6536. free(pass);
  6537. }
  6538. return ret;
  6539. }
  6540. #endif
  6541. #if defined(unix)
  6542. static void fork_monitor()
  6543. {
  6544. // Make a pipe: [readFD, writeFD]
  6545. int pfd[2];
  6546. int r = pipe(pfd);
  6547. if (r < 0) {
  6548. perror("pipe - failed to create pipe for --monitor");
  6549. exit(1);
  6550. }
  6551. // Make stderr write end of pipe
  6552. fflush(stderr);
  6553. r = dup2(pfd[1], 2);
  6554. if (r < 0) {
  6555. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  6556. exit(1);
  6557. }
  6558. r = close(pfd[1]);
  6559. if (r < 0) {
  6560. perror("close - failed to close write end of pipe for --monitor");
  6561. exit(1);
  6562. }
  6563. // Don't allow a dying monitor to kill the main process
  6564. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  6565. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  6566. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  6567. perror("signal - failed to edit signal mask for --monitor");
  6568. exit(1);
  6569. }
  6570. // Fork a child process
  6571. forkpid = fork();
  6572. if (forkpid < 0) {
  6573. perror("fork - failed to fork child process for --monitor");
  6574. exit(1);
  6575. }
  6576. // Child: launch monitor command
  6577. if (0 == forkpid) {
  6578. // Make stdin read end of pipe
  6579. r = dup2(pfd[0], 0);
  6580. if (r < 0) {
  6581. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  6582. exit(1);
  6583. }
  6584. close(pfd[0]);
  6585. if (r < 0) {
  6586. perror("close - in child, failed to close read end of pipe for --monitor");
  6587. exit(1);
  6588. }
  6589. // Launch user specified command
  6590. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  6591. perror("execl - in child failed to exec user specified command for --monitor");
  6592. exit(1);
  6593. }
  6594. // Parent: clean up unused fds and bail
  6595. r = close(pfd[0]);
  6596. if (r < 0) {
  6597. perror("close - failed to close read end of pipe for --monitor");
  6598. exit(1);
  6599. }
  6600. }
  6601. #endif // defined(unix)
  6602. #ifdef HAVE_CURSES
  6603. void enable_curses(void) {
  6604. int x;
  6605. __maybe_unused int y;
  6606. lock_curses();
  6607. if (curses_active) {
  6608. unlock_curses();
  6609. return;
  6610. }
  6611. mainwin = initscr();
  6612. keypad(mainwin, true);
  6613. getmaxyx(mainwin, y, x);
  6614. statuswin = newwin(logstart, x, 0, 0);
  6615. leaveok(statuswin, true);
  6616. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  6617. // We resize the window later anyway, so just start it off at 1 :)
  6618. logwin = newwin(1, 0, logcursor, 0);
  6619. idlok(logwin, true);
  6620. scrollok(logwin, true);
  6621. leaveok(logwin, true);
  6622. cbreak();
  6623. noecho();
  6624. curses_active = true;
  6625. statusy = logstart;
  6626. unlock_curses();
  6627. }
  6628. #endif
  6629. /* TODO: fix need a dummy CPU device_api even if no support for CPU mining */
  6630. #ifndef WANT_CPUMINE
  6631. struct device_api cpu_api;
  6632. struct device_api cpu_api = {
  6633. .name = "CPU",
  6634. };
  6635. #endif
  6636. #ifdef USE_BITFORCE
  6637. extern struct device_api bitforce_api;
  6638. #endif
  6639. #ifdef USE_ICARUS
  6640. extern struct device_api cairnsmore_api;
  6641. extern struct device_api icarus_api;
  6642. #endif
  6643. #ifdef USE_MODMINER
  6644. extern struct device_api modminer_api;
  6645. #endif
  6646. #ifdef USE_X6500
  6647. extern struct device_api x6500_api;
  6648. #endif
  6649. #ifdef USE_ZTEX
  6650. extern struct device_api ztex_api;
  6651. #endif
  6652. static int cgminer_id_count = 0;
  6653. static int device_line_id_count;
  6654. void register_device(struct cgpu_info *cgpu)
  6655. {
  6656. cgpu->deven = DEV_ENABLED;
  6657. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  6658. if (!cgpu->proc_id)
  6659. cgpu->device_line_id = device_line_id_count++;
  6660. mining_threads += cgpu->threads ?: 1;
  6661. #ifdef HAVE_CURSES
  6662. adj_width(mining_threads, &dev_width);
  6663. #endif
  6664. #ifdef HAVE_OPENCL
  6665. if (cgpu->api == &opencl_api) {
  6666. gpu_threads += cgpu->threads;
  6667. }
  6668. #endif
  6669. }
  6670. struct _cgpu_devid_counter {
  6671. char name[4];
  6672. int lastid;
  6673. UT_hash_handle hh;
  6674. };
  6675. void renumber_cgpu(struct cgpu_info *cgpu)
  6676. {
  6677. static struct _cgpu_devid_counter *devids = NULL;
  6678. struct _cgpu_devid_counter *d;
  6679. HASH_FIND_STR(devids, cgpu->api->name, d);
  6680. if (d)
  6681. cgpu->device_id = ++d->lastid;
  6682. else {
  6683. d = malloc(sizeof(*d));
  6684. memcpy(d->name, cgpu->api->name, sizeof(d->name));
  6685. cgpu->device_id = d->lastid = 0;
  6686. HASH_ADD_STR(devids, name, d);
  6687. }
  6688. }
  6689. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  6690. {
  6691. sha2(buffer, length, digest);
  6692. return true;
  6693. }
  6694. int main(int argc, char *argv[])
  6695. {
  6696. bool pools_active = false;
  6697. struct sigaction handler;
  6698. struct thr_info *thr;
  6699. struct block *block;
  6700. unsigned int k;
  6701. int i, j;
  6702. char *s;
  6703. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  6704. /* This dangerous functions tramples random dynamically allocated
  6705. * variables so do it before anything at all */
  6706. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  6707. quit(1, "Failed to curl_global_init");
  6708. initial_args = malloc(sizeof(char *) * (argc + 1));
  6709. for (i = 0; i < argc; i++)
  6710. initial_args[i] = strdup(argv[i]);
  6711. initial_args[argc] = NULL;
  6712. #ifdef HAVE_LIBUSB
  6713. int err = libusb_init(NULL);
  6714. if (err) {
  6715. fprintf(stderr, "libusb_init() failed err %d", err);
  6716. fflush(stderr);
  6717. quit(1, "libusb_init() failed");
  6718. }
  6719. #endif
  6720. mutex_init(&hash_lock);
  6721. mutex_init(&qd_lock);
  6722. mutex_init(&console_lock);
  6723. mutex_init(&control_lock);
  6724. mutex_init(&stats_lock);
  6725. mutex_init(&sharelog_lock);
  6726. mutex_init(&ch_lock);
  6727. mutex_init(&sshare_lock);
  6728. rwlock_init(&blk_lock);
  6729. rwlock_init(&netacc_lock);
  6730. mutex_init(&lp_lock);
  6731. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  6732. quit(1, "Failed to pthread_cond_init lp_cond");
  6733. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  6734. quit(1, "Failed to pthread_cond_init gws_cond");
  6735. notifier_init(submit_waiting_notifier);
  6736. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  6737. #ifdef WANT_CPUMINE
  6738. init_max_name_len();
  6739. #endif
  6740. handler.sa_handler = &sighandler;
  6741. handler.sa_flags = 0;
  6742. sigemptyset(&handler.sa_mask);
  6743. sigaction(SIGTERM, &handler, &termhandler);
  6744. sigaction(SIGINT, &handler, &inthandler);
  6745. #ifndef WIN32
  6746. signal(SIGPIPE, SIG_IGN);
  6747. #endif
  6748. opt_kernel_path = alloca(PATH_MAX);
  6749. strcpy(opt_kernel_path, CGMINER_PREFIX);
  6750. cgminer_path = alloca(PATH_MAX);
  6751. s = strdup(argv[0]);
  6752. strcpy(cgminer_path, dirname(s));
  6753. free(s);
  6754. strcat(cgminer_path, "/");
  6755. #ifdef WANT_CPUMINE
  6756. // Hack to make cgminer silent when called recursively on WIN32
  6757. int skip_to_bench = 0;
  6758. #if defined(WIN32)
  6759. char buf[32];
  6760. if (GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, 16))
  6761. skip_to_bench = 1;
  6762. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  6763. skip_to_bench = 1;
  6764. #endif // defined(WIN32)
  6765. #endif
  6766. devcursor = 8;
  6767. logstart = devcursor + 1;
  6768. logcursor = logstart + 1;
  6769. block = calloc(sizeof(struct block), 1);
  6770. if (unlikely(!block))
  6771. quit (1, "main OOM");
  6772. for (i = 0; i < 36; i++)
  6773. strcat(block->hash, "0");
  6774. HASH_ADD_STR(blocks, hash, block);
  6775. strcpy(current_block, block->hash);
  6776. INIT_LIST_HEAD(&scan_devices);
  6777. mutex_init(&submitting_lock);
  6778. INIT_LIST_HEAD(&submit_waiting);
  6779. #ifdef HAVE_OPENCL
  6780. memset(gpus, 0, sizeof(gpus));
  6781. for (i = 0; i < MAX_GPUDEVICES; i++)
  6782. gpus[i].dynamic = true;
  6783. #endif
  6784. schedstart.tm.tm_sec = 1;
  6785. schedstop .tm.tm_sec = 1;
  6786. /* parse command line */
  6787. opt_register_table(opt_config_table,
  6788. "Options for both config file and command line");
  6789. opt_register_table(opt_cmdline_table,
  6790. "Options for command line only");
  6791. opt_parse(&argc, argv, applog_and_exit);
  6792. if (argc != 1)
  6793. quit(1, "Unexpected extra commandline arguments");
  6794. if (!config_loaded)
  6795. load_default_config();
  6796. if (opt_benchmark) {
  6797. struct pool *pool;
  6798. want_longpoll = false;
  6799. pool = add_pool();
  6800. pool->rpc_url = malloc(255);
  6801. strcpy(pool->rpc_url, "Benchmark");
  6802. pool->rpc_user = pool->rpc_url;
  6803. pool->rpc_pass = pool->rpc_url;
  6804. enable_pool(pool);
  6805. pool->idle = false;
  6806. successful_connect = true;
  6807. }
  6808. #ifdef USE_X6500
  6809. ft232r_scan();
  6810. #endif
  6811. #ifdef HAVE_CURSES
  6812. if (opt_realquiet || devices_enabled == -1)
  6813. use_curses = false;
  6814. if (use_curses)
  6815. enable_curses();
  6816. #endif
  6817. applog(LOG_WARNING, "Started %s", packagename);
  6818. if (cnfbuf) {
  6819. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  6820. switch (fileconf_load) {
  6821. case 0:
  6822. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  6823. applog(LOG_WARNING, "Configuration file could not be used.");
  6824. break;
  6825. case -1:
  6826. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  6827. if (use_curses)
  6828. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  6829. break;
  6830. default:
  6831. break;
  6832. }
  6833. free(cnfbuf);
  6834. cnfbuf = NULL;
  6835. }
  6836. strcat(opt_kernel_path, "/");
  6837. if (want_per_device_stats)
  6838. opt_log_output = true;
  6839. #ifdef WANT_CPUMINE
  6840. #ifdef USE_SCRYPT
  6841. if (opt_scrypt)
  6842. set_scrypt_algo(&opt_algo);
  6843. else
  6844. #endif
  6845. if (0 <= opt_bench_algo) {
  6846. double rate = bench_algo_stage3(opt_bench_algo);
  6847. if (!skip_to_bench)
  6848. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  6849. else {
  6850. // Write result to shared memory for parent
  6851. #if defined(WIN32)
  6852. char unique_name[64];
  6853. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32) || GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  6854. HANDLE map_handle = CreateFileMapping(
  6855. INVALID_HANDLE_VALUE, // use paging file
  6856. NULL, // default security attributes
  6857. PAGE_READWRITE, // read/write access
  6858. 0, // size: high 32-bits
  6859. 4096, // size: low 32-bits
  6860. unique_name // name of map object
  6861. );
  6862. if (NULL != map_handle) {
  6863. void *shared_mem = MapViewOfFile(
  6864. map_handle, // object to map view of
  6865. FILE_MAP_WRITE, // read/write access
  6866. 0, // high offset: map from
  6867. 0, // low offset: beginning
  6868. 0 // default: map entire file
  6869. );
  6870. if (NULL != shared_mem)
  6871. CopyMemory(shared_mem, &rate, sizeof(rate));
  6872. (void)UnmapViewOfFile(shared_mem);
  6873. }
  6874. (void)CloseHandle(map_handle);
  6875. }
  6876. #endif
  6877. }
  6878. exit(0);
  6879. }
  6880. #endif
  6881. #ifdef HAVE_OPENCL
  6882. if (!opt_nogpu)
  6883. opencl_api.api_detect();
  6884. gpu_threads = 0;
  6885. #endif
  6886. #ifdef USE_ICARUS
  6887. if (!opt_scrypt)
  6888. {
  6889. cairnsmore_api.api_detect();
  6890. icarus_api.api_detect();
  6891. }
  6892. #endif
  6893. #ifdef USE_BITFORCE
  6894. if (!opt_scrypt)
  6895. bitforce_api.api_detect();
  6896. #endif
  6897. #ifdef USE_MODMINER
  6898. if (!opt_scrypt)
  6899. modminer_api.api_detect();
  6900. #endif
  6901. #ifdef USE_X6500
  6902. if (!opt_scrypt)
  6903. x6500_api.api_detect();
  6904. #endif
  6905. #ifdef USE_ZTEX
  6906. if (!opt_scrypt)
  6907. ztex_api.api_detect();
  6908. #endif
  6909. #ifdef WANT_CPUMINE
  6910. cpu_api.api_detect();
  6911. #endif
  6912. #ifdef USE_X6500
  6913. ft232r_scan_free();
  6914. #endif
  6915. for (i = 0; i < total_devices; ++i)
  6916. if (!devices[i]->devtype)
  6917. devices[i]->devtype = "PGA";
  6918. if (devices_enabled == -1) {
  6919. applog(LOG_ERR, "Devices detected:");
  6920. for (i = 0; i < total_devices; ++i) {
  6921. struct cgpu_info *cgpu = devices[i];
  6922. if (cgpu->name)
  6923. applog(LOG_ERR, " %2d. %"PRIprepr": %s (driver: %s)", i, cgpu->proc_repr, cgpu->name, cgpu->api->dname);
  6924. else
  6925. applog(LOG_ERR, " %2d. %"PRIprepr" (driver: %s)", i, cgpu->proc_repr, cgpu->api->dname);
  6926. }
  6927. quit(0, "%d devices listed", total_devices);
  6928. }
  6929. mining_threads = 0;
  6930. if (devices_enabled) {
  6931. for (i = 0; i < (int)(sizeof(devices_enabled) * 8) - 1; ++i) {
  6932. if (devices_enabled & (1 << i)) {
  6933. if (i >= total_devices)
  6934. quit (1, "Command line options set a device that doesn't exist");
  6935. register_device(devices[i]);
  6936. } else if (i < total_devices) {
  6937. if (opt_removedisabled) {
  6938. if (devices[i]->api == &cpu_api)
  6939. --opt_n_threads;
  6940. } else {
  6941. register_device(devices[i]);
  6942. }
  6943. devices[i]->deven = DEV_DISABLED;
  6944. }
  6945. }
  6946. total_devices = cgminer_id_count;
  6947. } else {
  6948. for (i = 0; i < total_devices; ++i)
  6949. register_device(devices[i]);
  6950. }
  6951. if (!total_devices)
  6952. quit(1, "All devices disabled, cannot mine!");
  6953. load_temp_config();
  6954. for (i = 0; i < total_devices; ++i)
  6955. devices[i]->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6956. #ifdef HAVE_CURSES
  6957. change_summarywinsize();
  6958. #endif
  6959. if (!total_pools) {
  6960. applog(LOG_WARNING, "Need to specify at least one pool server.");
  6961. #ifdef HAVE_CURSES
  6962. if (!use_curses || !input_pool(false))
  6963. #endif
  6964. quit(1, "Pool setup failed");
  6965. }
  6966. for (i = 0; i < total_pools; i++) {
  6967. struct pool *pool = pools[i];
  6968. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6969. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6970. if (!pool->rpc_userpass) {
  6971. if (!pool->rpc_user || !pool->rpc_pass)
  6972. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  6973. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  6974. if (!pool->rpc_userpass)
  6975. quit(1, "Failed to malloc userpass");
  6976. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  6977. }
  6978. }
  6979. /* Set the currentpool to pool with priority 0 */
  6980. validate_pool_priorities();
  6981. for (i = 0; i < total_pools; i++) {
  6982. struct pool *pool = pools[i];
  6983. if (!pool->prio)
  6984. currentpool = pool;
  6985. }
  6986. #ifdef HAVE_SYSLOG_H
  6987. if (use_syslog)
  6988. openlog(PACKAGE, LOG_PID, LOG_USER);
  6989. #endif
  6990. #if defined(unix)
  6991. if (opt_stderr_cmd)
  6992. fork_monitor();
  6993. #endif // defined(unix)
  6994. total_threads = mining_threads + 7;
  6995. thr_info = calloc(total_threads, sizeof(*thr));
  6996. if (!thr_info)
  6997. quit(1, "Failed to calloc thr_info");
  6998. gwsched_thr_id = mining_threads;
  6999. stage_thr_id = mining_threads + 1;
  7000. thr = &thr_info[stage_thr_id];
  7001. thr->q = tq_new();
  7002. if (!thr->q)
  7003. quit(1, "Failed to tq_new");
  7004. /* start stage thread */
  7005. if (thr_info_create(thr, NULL, stage_thread, thr))
  7006. quit(1, "stage thread create failed");
  7007. pthread_detach(thr->pth);
  7008. /* Create a unique get work queue */
  7009. getq = tq_new();
  7010. if (!getq)
  7011. quit(1, "Failed to create getq");
  7012. /* We use the getq mutex as the staged lock */
  7013. stgd_lock = &getq->mutex;
  7014. if (opt_benchmark)
  7015. goto begin_bench;
  7016. for (i = 0; i < total_pools; i++) {
  7017. struct pool *pool = pools[i];
  7018. enable_pool(pool);
  7019. pool->idle = true;
  7020. }
  7021. applog(LOG_NOTICE, "Probing for an alive pool");
  7022. do {
  7023. /* Look for at least one active pool before starting */
  7024. for (j = 0; j < total_pools; j++) {
  7025. for (i = 0; i < total_pools; i++) {
  7026. struct pool *pool = pools[i];
  7027. if (pool->prio != j)
  7028. continue;
  7029. if (pool_active(pool, false)) {
  7030. pool_tset(pool, &pool->lagging);
  7031. pool_tclear(pool, &pool->idle);
  7032. if (!currentpool)
  7033. currentpool = pool;
  7034. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  7035. pools_active = true;
  7036. goto found_active_pool;
  7037. } else {
  7038. if (pool == currentpool)
  7039. currentpool = NULL;
  7040. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  7041. }
  7042. }
  7043. }
  7044. if (!pools_active) {
  7045. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  7046. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  7047. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  7048. for (i = 0; i < total_pools; i++) {
  7049. struct pool *pool;
  7050. pool = pools[i];
  7051. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  7052. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  7053. }
  7054. #ifdef HAVE_CURSES
  7055. if (use_curses) {
  7056. halfdelay(150);
  7057. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  7058. if (getch() != ERR)
  7059. quit(0, "No servers could be used! Exiting.");
  7060. cbreak();
  7061. } else
  7062. #endif
  7063. quit(0, "No servers could be used! Exiting.");
  7064. }
  7065. } while (!pools_active);
  7066. found_active_pool: ;
  7067. #ifdef USE_SCRYPT
  7068. if (detect_algo == 1 && !opt_scrypt) {
  7069. applog(LOG_NOTICE, "Detected scrypt algorithm");
  7070. opt_scrypt = true;
  7071. }
  7072. #endif
  7073. detect_algo = 0;
  7074. begin_bench:
  7075. total_mhashes_done = 0;
  7076. for (i = 0; i < total_devices; i++) {
  7077. struct cgpu_info *cgpu = devices[i];
  7078. cgpu->rolling = cgpu->total_mhashes = 0;
  7079. }
  7080. gettimeofday(&total_tv_start, NULL);
  7081. gettimeofday(&total_tv_end, NULL);
  7082. miner_started = total_tv_start;
  7083. if (schedstart.tm.tm_sec)
  7084. localtime_r(&miner_started.tv_sec, &schedstart.tm);
  7085. if (schedstop.tm.tm_sec)
  7086. localtime_r(&miner_started.tv_sec, &schedstop .tm);
  7087. get_datestamp(datestamp, &total_tv_start);
  7088. // Initialise processors and threads
  7089. k = 0;
  7090. for (i = 0; i < total_devices; ++i) {
  7091. struct cgpu_info *cgpu = devices[i];
  7092. const struct device_api *api = cgpu->api;
  7093. int threadobj = cgpu->threads;
  7094. if (!threadobj)
  7095. // Create a fake thread object to handle hashmeter etc
  7096. threadobj = 1;
  7097. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  7098. cgpu->thr[threadobj] = NULL;
  7099. cgpu->status = LIFE_INIT;
  7100. cgpu->max_hashes = 0;
  7101. // Setup thread structs before starting any of the threads, in case they try to interact
  7102. for (j = 0; j < threadobj; ++j, ++k) {
  7103. thr = &thr_info[k];
  7104. thr->id = k;
  7105. thr->cgpu = cgpu;
  7106. thr->device_thread = j;
  7107. thr->work_restart_notifier[1] = INVSOCK;
  7108. thr->_job_transition_in_progress = true;
  7109. timerclear(&thr->tv_morework);
  7110. thr->scanhash_working = true;
  7111. thr->hashes_done = 0;
  7112. timerclear(&thr->tv_hashes_done);
  7113. gettimeofday(&thr->tv_lastupdate, NULL);
  7114. thr->tv_poll.tv_sec = -1;
  7115. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  7116. cgpu->thr[j] = thr;
  7117. }
  7118. }
  7119. // Start threads
  7120. for (i = 0; i < total_devices; ++i) {
  7121. struct cgpu_info *cgpu = devices[i];
  7122. if (!cgpu->threads)
  7123. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  7124. for (j = 0; j < cgpu->threads; ++j) {
  7125. thr = cgpu->thr[j];
  7126. notifier_init(thr->notifier);
  7127. /* Enable threads for devices set not to mine but disable
  7128. * their queue in case we wish to enable them later */
  7129. if (cgpu->api->thread_prepare && !cgpu->api->thread_prepare(thr))
  7130. continue;
  7131. thread_reportout(thr);
  7132. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  7133. quit(1, "thread %d create failed", thr->id);
  7134. }
  7135. if (cgpu->deven == DEV_ENABLED)
  7136. proc_enable(cgpu);
  7137. }
  7138. #ifdef HAVE_OPENCL
  7139. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  7140. for (i = 0; i < nDevs; i++)
  7141. pause_dynamic_threads(i);
  7142. #endif
  7143. #ifdef WANT_CPUMINE
  7144. applog(LOG_INFO, "%d cpu miner threads started, "
  7145. "using SHA256 '%s' algorithm.",
  7146. opt_n_threads,
  7147. algo_names[opt_algo]);
  7148. #endif
  7149. gettimeofday(&total_tv_start, NULL);
  7150. gettimeofday(&total_tv_end, NULL);
  7151. {
  7152. pthread_t submit_thread;
  7153. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  7154. quit(1, "submit_work thread create failed");
  7155. }
  7156. watchpool_thr_id = mining_threads + 2;
  7157. thr = &thr_info[watchpool_thr_id];
  7158. /* start watchpool thread */
  7159. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  7160. quit(1, "watchpool thread create failed");
  7161. pthread_detach(thr->pth);
  7162. watchdog_thr_id = mining_threads + 3;
  7163. thr = &thr_info[watchdog_thr_id];
  7164. /* start watchdog thread */
  7165. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  7166. quit(1, "watchdog thread create failed");
  7167. pthread_detach(thr->pth);
  7168. #ifdef HAVE_OPENCL
  7169. /* Create reinit gpu thread */
  7170. gpur_thr_id = mining_threads + 4;
  7171. thr = &thr_info[gpur_thr_id];
  7172. thr->q = tq_new();
  7173. if (!thr->q)
  7174. quit(1, "tq_new failed for gpur_thr_id");
  7175. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  7176. quit(1, "reinit_gpu thread create failed");
  7177. #endif
  7178. /* Create API socket thread */
  7179. api_thr_id = mining_threads + 5;
  7180. thr = &thr_info[api_thr_id];
  7181. if (thr_info_create(thr, NULL, api_thread, thr))
  7182. quit(1, "API thread create failed");
  7183. #ifdef HAVE_CURSES
  7184. /* Create curses input thread for keyboard input. Create this last so
  7185. * that we know all threads are created since this can call kill_work
  7186. * to try and shut down ll previous threads. */
  7187. input_thr_id = mining_threads + 6;
  7188. thr = &thr_info[input_thr_id];
  7189. if (thr_info_create(thr, NULL, input_thread, thr))
  7190. quit(1, "input thread create failed");
  7191. pthread_detach(thr->pth);
  7192. #endif
  7193. /* Once everything is set up, main() becomes the getwork scheduler */
  7194. while (42) {
  7195. int ts, max_staged = opt_queue;
  7196. struct pool *pool, *cp;
  7197. bool lagging = false;
  7198. struct curl_ent *ce;
  7199. struct work *work;
  7200. cp = current_pool();
  7201. /* If the primary pool is a getwork pool and cannot roll work,
  7202. * try to stage one extra work per mining thread */
  7203. if (!cp->has_stratum && cp->proto != PLP_GETBLOCKTEMPLATE && !staged_rollable)
  7204. max_staged += mining_threads;
  7205. mutex_lock(stgd_lock);
  7206. ts = __total_staged();
  7207. if (!cp->has_stratum && cp->proto != PLP_GETBLOCKTEMPLATE && !ts && !opt_fail_only)
  7208. lagging = true;
  7209. /* Wait until hash_pop tells us we need to create more work */
  7210. if (ts > max_staged) {
  7211. pthread_cond_wait(&gws_cond, stgd_lock);
  7212. ts = __total_staged();
  7213. }
  7214. mutex_unlock(stgd_lock);
  7215. if (ts > max_staged)
  7216. continue;
  7217. work = make_work();
  7218. if (lagging && !pool_tset(cp, &cp->lagging)) {
  7219. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  7220. cp->getfail_occasions++;
  7221. total_go++;
  7222. }
  7223. pool = select_pool(lagging);
  7224. retry:
  7225. if (pool->has_stratum) {
  7226. while (!pool->stratum_active || !pool->stratum_notify) {
  7227. struct pool *altpool = select_pool(true);
  7228. if (altpool == pool && pool->has_stratum)
  7229. sleep(5);
  7230. goto retry;
  7231. }
  7232. pool->last_work_time = time(NULL);
  7233. gen_stratum_work(pool, work);
  7234. applog(LOG_DEBUG, "Generated stratum work");
  7235. stage_work(work);
  7236. continue;
  7237. }
  7238. if (pool->last_work_copy) {
  7239. mutex_lock(&pool->last_work_lock);
  7240. struct work *last_work = pool->last_work_copy;
  7241. if (!last_work)
  7242. {}
  7243. if (can_roll(last_work) && should_roll(last_work)) {
  7244. free_work(work);
  7245. work = make_clone(pool->last_work_copy);
  7246. mutex_unlock(&pool->last_work_lock);
  7247. roll_work(work);
  7248. applog(LOG_DEBUG, "Generated work from latest GBT job in get_work_thread with %d seconds left", (int)blkmk_time_left(work->tmpl, time(NULL)));
  7249. stage_work(work);
  7250. continue;
  7251. } else if (last_work->tmpl && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tmpl) > (unsigned long)mining_threads) {
  7252. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  7253. } else {
  7254. free_work(last_work);
  7255. pool->last_work_copy = NULL;
  7256. }
  7257. mutex_unlock(&pool->last_work_lock);
  7258. }
  7259. if (clone_available()) {
  7260. applog(LOG_DEBUG, "Cloned getwork work");
  7261. free_work(work);
  7262. continue;
  7263. }
  7264. if (opt_benchmark) {
  7265. get_benchmark_work(work);
  7266. applog(LOG_DEBUG, "Generated benchmark work");
  7267. stage_work(work);
  7268. continue;
  7269. }
  7270. work->pool = pool;
  7271. ce = pop_curl_entry3(pool, 2);
  7272. /* obtain new work from bitcoin via JSON-RPC */
  7273. if (!get_upstream_work(work, ce->curl)) {
  7274. struct pool *next_pool;
  7275. /* Make sure the pool just hasn't stopped serving
  7276. * requests but is up as we'll keep hammering it */
  7277. push_curl_entry(ce, pool);
  7278. ++pool->seq_getfails;
  7279. pool_died(pool);
  7280. next_pool = select_pool(!opt_fail_only);
  7281. if (pool == next_pool) {
  7282. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  7283. sleep(5);
  7284. } else {
  7285. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  7286. pool = next_pool;
  7287. }
  7288. goto retry;
  7289. }
  7290. if (ts >= max_staged)
  7291. pool_tclear(pool, &pool->lagging);
  7292. if (pool_tclear(pool, &pool->idle))
  7293. pool_resus(pool);
  7294. applog(LOG_DEBUG, "Generated getwork work");
  7295. stage_work(work);
  7296. push_curl_entry(ce, pool);
  7297. }
  7298. return 0;
  7299. }