miner.c 359 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922
  1. /*
  2. * Copyright 2011-2014 Con Kolivas
  3. * Copyright 2011-2014 Luke Dashjr
  4. * Copyright 2014 Nate Woolls
  5. * Copyright 2012-2014 Andrew Smith
  6. * Copyright 2010 Jeff Garzik
  7. *
  8. * This program is free software; you can redistribute it and/or modify it
  9. * under the terms of the GNU General Public License as published by the Free
  10. * Software Foundation; either version 3 of the License, or (at your option)
  11. * any later version. See COPYING for more details.
  12. */
  13. #include "config.h"
  14. #ifdef HAVE_CURSES
  15. #ifdef USE_UNICODE
  16. #define PDC_WIDE
  17. #endif
  18. // Must be before stdbool, since pdcurses typedefs bool :/
  19. #include <curses.h>
  20. #endif
  21. #include <ctype.h>
  22. #include <float.h>
  23. #include <limits.h>
  24. #include <locale.h>
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #include <stdbool.h>
  29. #include <stdint.h>
  30. #include <unistd.h>
  31. #include <sys/time.h>
  32. #include <time.h>
  33. #include <math.h>
  34. #include <stdarg.h>
  35. #include <assert.h>
  36. #include <signal.h>
  37. #include <wctype.h>
  38. #include <sys/stat.h>
  39. #include <sys/types.h>
  40. #include <dirent.h>
  41. #ifdef HAVE_PWD_H
  42. #include <pwd.h>
  43. #endif
  44. #ifndef WIN32
  45. #include <sys/resource.h>
  46. #include <sys/socket.h>
  47. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  48. #include <libudev.h>
  49. #include <sys/epoll.h>
  50. #define HAVE_BFG_HOTPLUG
  51. #endif
  52. #else
  53. #include <winsock2.h>
  54. #include <windows.h>
  55. #include <dbt.h>
  56. #define HAVE_BFG_HOTPLUG
  57. #endif
  58. #include <ccan/opt/opt.h>
  59. #include <jansson.h>
  60. #include <curl/curl.h>
  61. #include <libgen.h>
  62. #include <sha2.h>
  63. #include <utlist.h>
  64. #include <blkmaker.h>
  65. #include <blkmaker_jansson.h>
  66. #include <blktemplate.h>
  67. #include <libbase58.h>
  68. #include "compat.h"
  69. #include "deviceapi.h"
  70. #include "logging.h"
  71. #include "miner.h"
  72. #include "adl.h"
  73. #include "driver-cpu.h"
  74. #include "driver-opencl.h"
  75. #include "util.h"
  76. #ifdef USE_AVALON
  77. #include "driver-avalon.h"
  78. #endif
  79. #ifdef HAVE_BFG_LOWLEVEL
  80. #include "lowlevel.h"
  81. #endif
  82. #if defined(unix) || defined(__APPLE__)
  83. #include <errno.h>
  84. #include <fcntl.h>
  85. #include <sys/wait.h>
  86. #endif
  87. #ifdef USE_SCRYPT
  88. #include "malgo/scrypt.h"
  89. #endif
  90. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_NANOFURY) || defined(USE_X6500) || defined(USE_ZTEX)
  91. # define USE_FPGA
  92. #endif
  93. enum bfg_quit_summary {
  94. BQS_DEFAULT,
  95. BQS_NONE,
  96. BQS_DEVS,
  97. BQS_PROCS,
  98. BQS_DETAILED,
  99. };
  100. struct strategies strategies[] = {
  101. { "Failover" },
  102. { "Round Robin" },
  103. { "Rotate" },
  104. { "Load Balance" },
  105. { "Balance" },
  106. };
  107. #define packagename bfgminer_name_space_ver
  108. bool opt_protocol;
  109. bool opt_dev_protocol;
  110. static bool opt_benchmark, opt_benchmark_intense;
  111. static bool want_longpoll = true;
  112. static bool want_gbt = true;
  113. static bool want_getwork = true;
  114. #if BLKMAKER_VERSION > 1
  115. static bool opt_load_bitcoin_conf = true;
  116. static uint32_t coinbase_script_block_id;
  117. static uint32_t template_nonce;
  118. #endif
  119. #if BLKMAKER_VERSION > 0
  120. char *opt_coinbase_sig;
  121. #endif
  122. static enum bfg_quit_summary opt_quit_summary = BQS_DEFAULT;
  123. static bool include_serial_in_statline;
  124. char *request_target_str;
  125. float request_pdiff = 1.0;
  126. double request_bdiff;
  127. static bool want_stratum = true;
  128. int opt_skip_checks;
  129. bool want_per_device_stats;
  130. bool use_syslog;
  131. bool opt_quiet_work_updates = true;
  132. bool opt_quiet;
  133. bool opt_realquiet;
  134. int loginput_size;
  135. bool opt_compact;
  136. bool opt_show_procs;
  137. const int opt_cutofftemp = 95;
  138. int opt_hysteresis = 3;
  139. static int opt_retries = -1;
  140. int opt_fail_pause = 5;
  141. int opt_log_interval = 20;
  142. int opt_queue = 1;
  143. int opt_scantime = 60;
  144. int opt_expiry = 120;
  145. int opt_expiry_lp = 3600;
  146. unsigned long long global_hashrate;
  147. static bool opt_unittest = false;
  148. unsigned unittest_failures;
  149. unsigned long global_quota_gcd = 1;
  150. time_t last_getwork;
  151. #ifdef USE_OPENCL
  152. int opt_dynamic_interval = 7;
  153. int nDevs;
  154. int opt_g_threads = -1;
  155. #endif
  156. #ifdef USE_SCRYPT
  157. static char detect_algo = 1;
  158. #else
  159. static char detect_algo;
  160. #endif
  161. bool opt_restart = true;
  162. #ifdef USE_LIBMICROHTTPD
  163. #include "httpsrv.h"
  164. int httpsrv_port = -1;
  165. #endif
  166. #ifdef USE_LIBEVENT
  167. int stratumsrv_port = -1;
  168. #endif
  169. const
  170. int rescan_delay_ms = 1000;
  171. #ifdef HAVE_BFG_HOTPLUG
  172. bool opt_hotplug = 1;
  173. const
  174. int hotplug_delay_ms = 100;
  175. #else
  176. const bool opt_hotplug;
  177. #endif
  178. struct string_elist *scan_devices;
  179. static struct string_elist *opt_set_device_list;
  180. bool opt_force_dev_init;
  181. static struct string_elist *opt_devices_enabled_list;
  182. static bool opt_display_devs;
  183. int total_devices;
  184. struct cgpu_info **devices;
  185. int total_devices_new;
  186. struct cgpu_info **devices_new;
  187. bool have_opencl;
  188. int opt_n_threads = -1;
  189. int mining_threads;
  190. int base_queue;
  191. int num_processors;
  192. #ifdef HAVE_CURSES
  193. bool use_curses = true;
  194. #else
  195. bool use_curses;
  196. #endif
  197. int last_logstatusline_len;
  198. #ifdef HAVE_LIBUSB
  199. bool have_libusb;
  200. #endif
  201. static bool opt_submit_stale = true;
  202. static float opt_shares;
  203. static int opt_submit_threads = 0x40;
  204. bool opt_fail_only;
  205. int opt_fail_switch_delay = 300;
  206. bool opt_autofan;
  207. bool opt_autoengine;
  208. bool opt_noadl;
  209. char *opt_api_allow = NULL;
  210. char *opt_api_groups;
  211. char *opt_api_description = PACKAGE_STRING;
  212. int opt_api_port = 4028;
  213. bool opt_api_listen;
  214. bool opt_api_mcast;
  215. char *opt_api_mcast_addr = API_MCAST_ADDR;
  216. char *opt_api_mcast_code = API_MCAST_CODE;
  217. char *opt_api_mcast_des = "";
  218. int opt_api_mcast_port = 4028;
  219. bool opt_api_network;
  220. bool opt_delaynet;
  221. bool opt_disable_pool;
  222. bool opt_disable_client_reconnect = false;
  223. static bool no_work;
  224. bool opt_worktime;
  225. bool opt_weighed_stats;
  226. char *opt_kernel_path;
  227. char *cgminer_path;
  228. #if defined(USE_BITFORCE)
  229. bool opt_bfl_noncerange;
  230. #endif
  231. #define QUIET (opt_quiet || opt_realquiet)
  232. struct thr_info *control_thr;
  233. struct thr_info **mining_thr;
  234. static int watchpool_thr_id;
  235. static int watchdog_thr_id;
  236. #ifdef HAVE_CURSES
  237. static int input_thr_id;
  238. #endif
  239. int gpur_thr_id;
  240. static int api_thr_id;
  241. static int total_control_threads;
  242. pthread_mutex_t hash_lock;
  243. static pthread_mutex_t *stgd_lock;
  244. pthread_mutex_t console_lock;
  245. cglock_t ch_lock;
  246. static pthread_rwlock_t blk_lock;
  247. static pthread_mutex_t sshare_lock;
  248. pthread_rwlock_t netacc_lock;
  249. pthread_rwlock_t mining_thr_lock;
  250. pthread_rwlock_t devices_lock;
  251. static pthread_mutex_t lp_lock;
  252. static pthread_cond_t lp_cond;
  253. pthread_cond_t gws_cond;
  254. bool shutting_down;
  255. double total_rolling;
  256. double total_mhashes_done;
  257. static struct timeval total_tv_start, total_tv_end;
  258. static struct timeval miner_started;
  259. cglock_t control_lock;
  260. pthread_mutex_t stats_lock;
  261. static pthread_mutex_t submitting_lock;
  262. static int total_submitting;
  263. static struct work *submit_waiting;
  264. notifier_t submit_waiting_notifier;
  265. int hw_errors;
  266. int total_accepted, total_rejected;
  267. int total_getworks, total_stale, total_discarded;
  268. uint64_t total_bytes_rcvd, total_bytes_sent;
  269. double total_diff1, total_bad_diff1;
  270. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  271. static int staged_rollable, staged_spare;
  272. unsigned int new_blocks;
  273. unsigned int found_blocks;
  274. unsigned int local_work;
  275. unsigned int total_go, total_ro;
  276. struct pool **pools;
  277. static struct pool *currentpool = NULL;
  278. int total_pools, enabled_pools;
  279. enum pool_strategy pool_strategy = POOL_FAILOVER;
  280. int opt_rotate_period;
  281. static int total_urls, total_users, total_passes;
  282. static
  283. #ifndef HAVE_CURSES
  284. const
  285. #endif
  286. bool curses_active;
  287. #ifdef HAVE_CURSES
  288. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  289. const
  290. #endif
  291. short default_bgcolor = COLOR_BLACK;
  292. static int attr_title = A_BOLD;
  293. #endif
  294. static
  295. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  296. bool use_unicode;
  297. static
  298. bool have_unicode_degrees;
  299. static
  300. wchar_t unicode_micro = 'u';
  301. #else
  302. const bool use_unicode;
  303. static
  304. const bool have_unicode_degrees;
  305. #ifdef HAVE_CURSES
  306. static
  307. const char unicode_micro = 'u';
  308. #endif
  309. #endif
  310. #ifdef HAVE_CURSES
  311. #define U8_BAD_START "\xef\x80\x81"
  312. #define U8_BAD_END "\xef\x80\x80"
  313. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  314. /* logstart is where the log window should start */
  315. static int devcursor, logstart, logcursor;
  316. bool selecting_device;
  317. unsigned selected_device;
  318. #endif
  319. static int max_lpdigits;
  320. // current_hash was replaced with goal->current_goal_detail
  321. // current_block_id was replaced with blkchain->currentblk->block_id
  322. static char datestamp[40];
  323. static char best_share[ALLOC_H2B_SHORTV] = "0";
  324. double best_diff = 0;
  325. struct mining_algorithm *mining_algorithms;
  326. struct mining_goal_info *mining_goals;
  327. int active_goals = 1;
  328. int swork_id;
  329. /* For creating a hash database of stratum shares submitted that have not had
  330. * a response yet */
  331. struct stratum_share {
  332. UT_hash_handle hh;
  333. bool block;
  334. struct work *work;
  335. int id;
  336. };
  337. static struct stratum_share *stratum_shares = NULL;
  338. char *opt_socks_proxy = NULL;
  339. static const char def_conf[] = "bfgminer.conf";
  340. static bool config_loaded;
  341. static int include_count;
  342. #define JSON_INCLUDE_CONF "include"
  343. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  344. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  345. #define JSON_MAX_DEPTH 10
  346. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  347. #define JSON_WEB_ERROR "WEB config err"
  348. char *cmd_idle, *cmd_sick, *cmd_dead;
  349. #if defined(unix) || defined(__APPLE__)
  350. static char *opt_stderr_cmd = NULL;
  351. static int forkpid;
  352. #endif // defined(unix)
  353. #ifdef HAVE_CHROOT
  354. char *chroot_dir;
  355. #endif
  356. #ifdef HAVE_PWD_H
  357. char *opt_setuid;
  358. #endif
  359. struct sigaction termhandler, inthandler;
  360. struct thread_q *getq;
  361. static int total_work;
  362. static bool staged_full;
  363. struct work *staged_work = NULL;
  364. struct schedtime {
  365. bool enable;
  366. struct tm tm;
  367. };
  368. struct schedtime schedstart;
  369. struct schedtime schedstop;
  370. bool sched_paused;
  371. static bool time_before(struct tm *tm1, struct tm *tm2)
  372. {
  373. if (tm1->tm_hour < tm2->tm_hour)
  374. return true;
  375. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  376. return true;
  377. return false;
  378. }
  379. static bool should_run(void)
  380. {
  381. struct tm tm;
  382. time_t tt;
  383. bool within_range;
  384. if (!schedstart.enable && !schedstop.enable)
  385. return true;
  386. tt = time(NULL);
  387. localtime_r(&tt, &tm);
  388. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  389. if (time_before(&schedstop.tm, &schedstart.tm))
  390. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  391. else
  392. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  393. if (within_range && !schedstop.enable)
  394. /* This is a once off event with no stop time set */
  395. schedstart.enable = false;
  396. return within_range;
  397. }
  398. void get_datestamp(char *f, size_t fsiz, time_t tt)
  399. {
  400. struct tm _tm;
  401. struct tm *tm = &_tm;
  402. if (tt == INVALID_TIMESTAMP)
  403. tt = time(NULL);
  404. localtime_r(&tt, tm);
  405. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  406. tm->tm_year + 1900,
  407. tm->tm_mon + 1,
  408. tm->tm_mday,
  409. tm->tm_hour,
  410. tm->tm_min,
  411. tm->tm_sec);
  412. }
  413. static
  414. void get_timestamp(char *f, size_t fsiz, time_t tt)
  415. {
  416. struct tm _tm;
  417. struct tm *tm = &_tm;
  418. localtime_r(&tt, tm);
  419. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  420. tm->tm_hour,
  421. tm->tm_min,
  422. tm->tm_sec);
  423. }
  424. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  425. static char exit_buf[512];
  426. static void applog_and_exit(const char *fmt, ...)
  427. {
  428. va_list ap;
  429. va_start(ap, fmt);
  430. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  431. va_end(ap);
  432. _applog(LOG_ERR, exit_buf);
  433. exit(1);
  434. }
  435. static
  436. float drv_min_nonce_diff(const struct device_drv * const drv, struct cgpu_info * const proc, const struct mining_algorithm * const malgo)
  437. {
  438. if (drv->drv_min_nonce_diff)
  439. return drv->drv_min_nonce_diff(proc, malgo);
  440. #ifdef USE_SHA256D
  441. return (malgo->algo == POW_SHA256D) ? 1. : -1.;
  442. #else
  443. return -1.;
  444. #endif
  445. }
  446. char *devpath_to_devid(const char *devpath)
  447. {
  448. #ifndef WIN32
  449. if (devpath[0] != '/')
  450. return NULL;
  451. struct stat my_stat;
  452. if (stat(devpath, &my_stat))
  453. return NULL;
  454. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  455. memcpy(devs, "dev_t:", 6);
  456. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  457. #else
  458. if (!strncmp(devpath, "\\\\.\\", 4))
  459. devpath += 4;
  460. if (strncasecmp(devpath, "COM", 3) || !devpath[3])
  461. return NULL;
  462. devpath += 3;
  463. char *p;
  464. strtol(devpath, &p, 10);
  465. if (p[0])
  466. return NULL;
  467. const int sz = (p - devpath);
  468. char *devs = malloc(4 + sz + 1);
  469. sprintf(devs, "com:%s", devpath);
  470. #endif
  471. return devs;
  472. }
  473. static
  474. bool devpaths_match(const char * const ap, const char * const bp)
  475. {
  476. char * const a = devpath_to_devid(ap);
  477. if (!a)
  478. return false;
  479. char * const b = devpath_to_devid(bp);
  480. bool rv = false;
  481. if (b)
  482. {
  483. rv = !strcmp(a, b);
  484. free(b);
  485. }
  486. free(a);
  487. return rv;
  488. }
  489. static
  490. int proc_letter_to_number(const char *s, const char ** const rem)
  491. {
  492. int n = 0, c;
  493. for ( ; s[0]; ++s)
  494. {
  495. if (unlikely(n > INT_MAX / 26))
  496. break;
  497. c = tolower(s[0]) - 'a';
  498. if (unlikely(c < 0 || c > 25))
  499. break;
  500. if (unlikely(INT_MAX - c < n))
  501. break;
  502. n = (n * 26) + c;
  503. }
  504. *rem = s;
  505. return n;
  506. }
  507. static
  508. bool cgpu_match(const char * const pattern, const struct cgpu_info * const cgpu)
  509. {
  510. // all - matches anything
  511. // d0 - matches all processors of device 0
  512. // d0-3 - matches all processors of device 0, 1, 2, or 3
  513. // d0a - matches first processor of device 0
  514. // 0 - matches processor 0
  515. // 0-4 - matches processors 0, 1, 2, 3, or 4
  516. // ___ - matches all processors on all devices using driver/name ___
  517. // ___0 - matches all processors of 0th device using driver/name ___
  518. // ___0a - matches first processor of 0th device using driver/name ___
  519. // @* - matches device with serial or path *
  520. // @*@a - matches first processor of device with serial or path *
  521. // ___@* - matches device with serial or path * using driver/name ___
  522. if (!strcasecmp(pattern, "all"))
  523. return true;
  524. const struct device_drv * const drv = cgpu->drv;
  525. const char *p = pattern, *p2;
  526. size_t L;
  527. int n, i, c = -1;
  528. int n2;
  529. int proc_first = -1, proc_last = -1;
  530. struct cgpu_info *device;
  531. if (!(strncasecmp(drv->dname, p, (L = strlen(drv->dname)))
  532. && strncasecmp(drv-> name, p, (L = strlen(drv-> name)))))
  533. // dname or name
  534. p = &pattern[L];
  535. else
  536. if (p[0] == 'd' && (isdigit(p[1]) || p[1] == '-'))
  537. // d#
  538. ++p;
  539. else
  540. if (isdigit(p[0]) || p[0] == '@' || p[0] == '-')
  541. // # or @
  542. {}
  543. else
  544. return false;
  545. L = p - pattern;
  546. while (isspace(p[0]))
  547. ++p;
  548. if (p[0] == '@')
  549. {
  550. // Serial/path
  551. const char * const ser = &p[1];
  552. for (p = ser; p[0] != '@' && p[0] != '\0'; ++p)
  553. {}
  554. p2 = (p[0] == '@') ? &p[1] : p;
  555. const size_t serlen = (p - ser);
  556. p = "";
  557. n = n2 = 0;
  558. const char * const devpath = cgpu->device_path ?: "";
  559. const char * const devser = cgpu->dev_serial ?: "";
  560. if ((!strncmp(devpath, ser, serlen)) && devpath[serlen] == '\0')
  561. {} // Match
  562. else
  563. if ((!strncmp(devser, ser, serlen)) && devser[serlen] == '\0')
  564. {} // Match
  565. else
  566. {
  567. char devpath2[serlen + 1];
  568. memcpy(devpath2, ser, serlen);
  569. devpath2[serlen] = '\0';
  570. if (!devpaths_match(devpath, ser))
  571. return false;
  572. }
  573. }
  574. else
  575. {
  576. if (isdigit(p[0]))
  577. n = strtol(p, (void*)&p2, 0);
  578. else
  579. {
  580. n = 0;
  581. p2 = p;
  582. }
  583. if (p2[0] == '-')
  584. {
  585. ++p2;
  586. if (p2[0] && isdigit(p2[0]))
  587. n2 = strtol(p2, (void*)&p2, 0);
  588. else
  589. n2 = INT_MAX;
  590. }
  591. else
  592. n2 = n;
  593. if (p == pattern)
  594. {
  595. if (!p[0])
  596. return true;
  597. if (p2 && p2[0])
  598. goto invsyntax;
  599. for (i = n; i <= n2; ++i)
  600. {
  601. if (i >= total_devices)
  602. break;
  603. if (cgpu == devices[i])
  604. return true;
  605. }
  606. return false;
  607. }
  608. }
  609. if (p2[0])
  610. {
  611. proc_first = proc_letter_to_number(&p2[0], &p2);
  612. if (p2[0] == '-')
  613. {
  614. ++p2;
  615. if (p2[0])
  616. proc_last = proc_letter_to_number(p2, &p2);
  617. else
  618. proc_last = INT_MAX;
  619. }
  620. else
  621. proc_last = proc_first;
  622. if (p2[0])
  623. goto invsyntax;
  624. }
  625. if (L > 1 || tolower(pattern[0]) != 'd' || !p[0])
  626. {
  627. if ((L == 3 && !strncasecmp(pattern, drv->name, 3)) ||
  628. (!L) ||
  629. (L == strlen(drv->dname) && !strncasecmp(pattern, drv->dname, L)))
  630. {} // Matched name or dname
  631. else
  632. return false;
  633. if (p[0] && (cgpu->device_id < n || cgpu->device_id > n2))
  634. return false;
  635. if (proc_first != -1 && (cgpu->proc_id < proc_first || cgpu->proc_id > proc_last))
  636. return false;
  637. return true;
  638. }
  639. // d#
  640. c = -1;
  641. for (i = 0; ; ++i)
  642. {
  643. if (i == total_devices)
  644. return false;
  645. if (devices[i]->device != devices[i])
  646. continue;
  647. ++c;
  648. if (c < n)
  649. continue;
  650. if (c > n2)
  651. break;
  652. for (device = devices[i]; device; device = device->next_proc)
  653. {
  654. if (proc_first != -1 && (device->proc_id < proc_first || device->proc_id > proc_last))
  655. continue;
  656. if (device == cgpu)
  657. return true;
  658. }
  659. }
  660. return false;
  661. invsyntax:
  662. applog(LOG_WARNING, "%s: Invalid syntax: %s", __func__, pattern);
  663. return false;
  664. }
  665. #define TEST_CGPU_MATCH(pattern) \
  666. if (!cgpu_match(pattern, &cgpu)) \
  667. { \
  668. ++unittest_failures; \
  669. applog(LOG_ERR, "%s: Pattern \"%s\" should have matched!", __func__, pattern); \
  670. } \
  671. // END TEST_CGPU_MATCH
  672. #define TEST_CGPU_NOMATCH(pattern) \
  673. if (cgpu_match(pattern, &cgpu)) \
  674. { \
  675. ++unittest_failures; \
  676. applog(LOG_ERR, "%s: Pattern \"%s\" should NOT have matched!", __func__, pattern); \
  677. } \
  678. // END TEST_CGPU_MATCH
  679. static __maybe_unused
  680. void test_cgpu_match()
  681. {
  682. struct device_drv drv = {
  683. .dname = "test",
  684. .name = "TST",
  685. };
  686. struct cgpu_info cgpu = {
  687. .drv = &drv,
  688. .device = &cgpu,
  689. .device_id = 1,
  690. .proc_id = 1,
  691. .proc_repr = "TST 1b",
  692. }, cgpu0a = {
  693. .drv = &drv,
  694. .device = &cgpu0a,
  695. .device_id = 0,
  696. .proc_id = 0,
  697. .proc_repr = "TST 0a",
  698. }, cgpu1a = {
  699. .drv = &drv,
  700. .device = &cgpu0a,
  701. .device_id = 1,
  702. .proc_id = 0,
  703. .proc_repr = "TST 1a",
  704. };
  705. struct cgpu_info *devices_list[3] = {&cgpu0a, &cgpu1a, &cgpu,};
  706. devices = devices_list;
  707. total_devices = 3;
  708. TEST_CGPU_MATCH("all")
  709. TEST_CGPU_MATCH("d1")
  710. TEST_CGPU_NOMATCH("d2")
  711. TEST_CGPU_MATCH("d0-5")
  712. TEST_CGPU_NOMATCH("d0-0")
  713. TEST_CGPU_NOMATCH("d2-5")
  714. TEST_CGPU_MATCH("d-1")
  715. TEST_CGPU_MATCH("d1-")
  716. TEST_CGPU_NOMATCH("d-0")
  717. TEST_CGPU_NOMATCH("d2-")
  718. TEST_CGPU_MATCH("2")
  719. TEST_CGPU_NOMATCH("3")
  720. TEST_CGPU_MATCH("1-2")
  721. TEST_CGPU_MATCH("2-3")
  722. TEST_CGPU_NOMATCH("1-1")
  723. TEST_CGPU_NOMATCH("3-4")
  724. TEST_CGPU_MATCH("TST")
  725. TEST_CGPU_MATCH("test")
  726. TEST_CGPU_MATCH("tst")
  727. TEST_CGPU_MATCH("TEST")
  728. TEST_CGPU_NOMATCH("TSF")
  729. TEST_CGPU_NOMATCH("TS")
  730. TEST_CGPU_NOMATCH("TSTF")
  731. TEST_CGPU_MATCH("TST1")
  732. TEST_CGPU_MATCH("test1")
  733. TEST_CGPU_MATCH("TST0-1")
  734. TEST_CGPU_MATCH("TST 1")
  735. TEST_CGPU_MATCH("TST 1-2")
  736. TEST_CGPU_MATCH("TEST 1-2")
  737. TEST_CGPU_NOMATCH("TST2")
  738. TEST_CGPU_NOMATCH("TST2-3")
  739. TEST_CGPU_NOMATCH("TST0-0")
  740. TEST_CGPU_MATCH("TST1b")
  741. TEST_CGPU_MATCH("tst1b")
  742. TEST_CGPU_NOMATCH("TST1c")
  743. TEST_CGPU_NOMATCH("TST1bb")
  744. TEST_CGPU_MATCH("TST0-1b")
  745. TEST_CGPU_NOMATCH("TST0-1c")
  746. TEST_CGPU_MATCH("TST1a-d")
  747. TEST_CGPU_NOMATCH("TST1a-a")
  748. TEST_CGPU_NOMATCH("TST1-a")
  749. TEST_CGPU_NOMATCH("TST1c-z")
  750. TEST_CGPU_NOMATCH("TST1c-")
  751. TEST_CGPU_MATCH("@")
  752. TEST_CGPU_NOMATCH("@abc")
  753. TEST_CGPU_MATCH("@@b")
  754. TEST_CGPU_NOMATCH("@@c")
  755. TEST_CGPU_MATCH("TST@")
  756. TEST_CGPU_NOMATCH("TST@abc")
  757. TEST_CGPU_MATCH("TST@@b")
  758. TEST_CGPU_NOMATCH("TST@@c")
  759. TEST_CGPU_MATCH("TST@@b-f")
  760. TEST_CGPU_NOMATCH("TST@@c-f")
  761. TEST_CGPU_NOMATCH("TST@@-a")
  762. cgpu.device_path = "/dev/test";
  763. cgpu.dev_serial = "testy";
  764. TEST_CGPU_MATCH("TST@/dev/test")
  765. TEST_CGPU_MATCH("TST@testy")
  766. TEST_CGPU_NOMATCH("TST@")
  767. TEST_CGPU_NOMATCH("TST@/dev/test5@b")
  768. TEST_CGPU_NOMATCH("TST@testy3@b")
  769. TEST_CGPU_MATCH("TST@/dev/test@b")
  770. TEST_CGPU_MATCH("TST@testy@b")
  771. TEST_CGPU_NOMATCH("TST@/dev/test@c")
  772. TEST_CGPU_NOMATCH("TST@testy@c")
  773. cgpu.device_path = "usb:000:999";
  774. TEST_CGPU_MATCH("TST@usb:000:999")
  775. drv.dname = "test7";
  776. TEST_CGPU_MATCH("test7")
  777. TEST_CGPU_MATCH("TEST7")
  778. TEST_CGPU_NOMATCH("test&")
  779. TEST_CGPU_MATCH("test7 1-2")
  780. TEST_CGPU_MATCH("test7@testy@b")
  781. }
  782. static
  783. int cgpu_search(const char * const pattern, const int first)
  784. {
  785. int i;
  786. struct cgpu_info *cgpu;
  787. #define CHECK_CGPU_SEARCH do{ \
  788. cgpu = get_devices(i); \
  789. if (cgpu_match(pattern, cgpu)) \
  790. return i; \
  791. }while(0)
  792. for (i = first; i < total_devices; ++i)
  793. CHECK_CGPU_SEARCH;
  794. for (i = 0; i < first; ++i)
  795. CHECK_CGPU_SEARCH;
  796. #undef CHECK_CGPU_SEARCH
  797. return -1;
  798. }
  799. static pthread_mutex_t sharelog_lock;
  800. static FILE *sharelog_file = NULL;
  801. struct thr_info *get_thread(int thr_id)
  802. {
  803. struct thr_info *thr;
  804. rd_lock(&mining_thr_lock);
  805. thr = mining_thr[thr_id];
  806. rd_unlock(&mining_thr_lock);
  807. return thr;
  808. }
  809. static struct cgpu_info *get_thr_cgpu(int thr_id)
  810. {
  811. struct thr_info *thr = get_thread(thr_id);
  812. return thr->cgpu;
  813. }
  814. struct cgpu_info *get_devices(int id)
  815. {
  816. struct cgpu_info *cgpu;
  817. rd_lock(&devices_lock);
  818. cgpu = devices[id];
  819. rd_unlock(&devices_lock);
  820. return cgpu;
  821. }
  822. static pthread_mutex_t noncelog_lock = PTHREAD_MUTEX_INITIALIZER;
  823. static FILE *noncelog_file = NULL;
  824. static
  825. void noncelog(const struct work * const work)
  826. {
  827. const int thr_id = work->thr_id;
  828. const struct cgpu_info *proc = get_thr_cgpu(thr_id);
  829. char buf[0x200], hash[65], data[161], midstate[65];
  830. int rv;
  831. size_t ret;
  832. bin2hex(hash, work->hash, 32);
  833. bin2hex(data, work->data, 80);
  834. bin2hex(midstate, work->midstate, 32);
  835. // timestamp,proc,hash,data,midstate
  836. rv = snprintf(buf, sizeof(buf), "%lu,%s,%s,%s,%s\n",
  837. (unsigned long)time(NULL), proc->proc_repr_ns,
  838. hash, data, midstate);
  839. if (unlikely(rv < 1))
  840. {
  841. applog(LOG_ERR, "noncelog printf error");
  842. return;
  843. }
  844. mutex_lock(&noncelog_lock);
  845. ret = fwrite(buf, rv, 1, noncelog_file);
  846. fflush(noncelog_file);
  847. mutex_unlock(&noncelog_lock);
  848. if (ret != 1)
  849. applog(LOG_ERR, "noncelog fwrite error");
  850. }
  851. static void sharelog(const char*disposition, const struct work*work)
  852. {
  853. char target[(sizeof(work->target) * 2) + 1];
  854. char hash[(sizeof(work->hash) * 2) + 1];
  855. char data[(sizeof(work->data) * 2) + 1];
  856. struct cgpu_info *cgpu;
  857. unsigned long int t;
  858. struct pool *pool;
  859. int thr_id, rv;
  860. char s[1024];
  861. size_t ret;
  862. if (!sharelog_file)
  863. return;
  864. thr_id = work->thr_id;
  865. cgpu = get_thr_cgpu(thr_id);
  866. pool = work->pool;
  867. t = work->ts_getwork + timer_elapsed(&work->tv_getwork, &work->tv_work_found);
  868. bin2hex(target, work->target, sizeof(work->target));
  869. bin2hex(hash, work->hash, sizeof(work->hash));
  870. bin2hex(data, work->data, sizeof(work->data));
  871. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  872. 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);
  873. if (rv >= (int)(sizeof(s)))
  874. s[sizeof(s) - 1] = '\0';
  875. else if (rv < 0) {
  876. applog(LOG_ERR, "sharelog printf error");
  877. return;
  878. }
  879. mutex_lock(&sharelog_lock);
  880. ret = fwrite(s, rv, 1, sharelog_file);
  881. fflush(sharelog_file);
  882. mutex_unlock(&sharelog_lock);
  883. if (ret != 1)
  884. applog(LOG_ERR, "sharelog fwrite error");
  885. }
  886. #ifdef HAVE_CURSES
  887. static void switch_logsize(void);
  888. #endif
  889. static void hotplug_trigger();
  890. void goal_set_malgo(struct mining_goal_info * const goal, struct mining_algorithm * const malgo)
  891. {
  892. if (goal->malgo == malgo)
  893. return;
  894. if (goal->malgo)
  895. --goal->malgo->goal_refs;
  896. if (malgo->goal_refs++)
  897. // First time using a new mining algorithm may means we need to add mining hardware to support it
  898. // api_thr_id is used as an ugly hack to determine if mining has started - if not, we do NOT want to try to hotplug anything (let the initial detect handle it)
  899. if (opt_hotplug && api_thr_id)
  900. hotplug_trigger();
  901. goal->malgo = malgo;
  902. }
  903. struct mining_algorithm *mining_algorithm_by_alias(const char * const alias)
  904. {
  905. struct mining_algorithm *malgo;
  906. LL_FOREACH(mining_algorithms, malgo)
  907. {
  908. if (match_strtok(malgo->aliases, "|", alias))
  909. return malgo;
  910. }
  911. return NULL;
  912. }
  913. #ifdef USE_SCRYPT
  914. extern struct mining_algorithm malgo_scrypt;
  915. static
  916. const char *set_malgo_scrypt()
  917. {
  918. goal_set_malgo(get_mining_goal("default"), &malgo_scrypt);
  919. return NULL;
  920. }
  921. #endif
  922. static
  923. int mining_goals_name_cmp(const struct mining_goal_info * const a, const struct mining_goal_info * const b)
  924. {
  925. // default always goes first
  926. if (a->is_default)
  927. return -1;
  928. if (b->is_default)
  929. return 1;
  930. return strcmp(a->name, b->name);
  931. }
  932. static
  933. void blkchain_init_block(struct blockchain_info * const blkchain)
  934. {
  935. struct block_info * const dummy_block = calloc(sizeof(*dummy_block), 1);
  936. memset(dummy_block->prevblkhash, 0, 0x20);
  937. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(dummy_block->prevblkhash), dummy_block);
  938. blkchain->currentblk = dummy_block;
  939. }
  940. extern struct mining_algorithm malgo_sha256d;
  941. struct mining_goal_info *get_mining_goal(const char * const name)
  942. {
  943. static unsigned next_goal_id;
  944. struct mining_goal_info *goal;
  945. HASH_FIND_STR(mining_goals, name, goal);
  946. if (!goal)
  947. {
  948. struct blockchain_info * const blkchain = malloc(sizeof(*blkchain) + sizeof(*goal));
  949. goal = (void*)(&blkchain[1]);
  950. *blkchain = (struct blockchain_info){
  951. .currentblk = NULL,
  952. };
  953. blkchain_init_block(blkchain);
  954. *goal = (struct mining_goal_info){
  955. .id = next_goal_id++,
  956. .name = strdup(name),
  957. .is_default = !strcmp(name, "default"),
  958. .blkchain = blkchain,
  959. .current_diff = 0xFFFFFFFFFFFFFFFFULL,
  960. };
  961. #ifdef USE_SHA256D
  962. goal_set_malgo(goal, &malgo_sha256d);
  963. #else
  964. // NOTE: Basically random default
  965. goal_set_malgo(goal, mining_algorithms);
  966. #endif
  967. HASH_ADD_KEYPTR(hh, mining_goals, goal->name, strlen(goal->name), goal);
  968. HASH_SORT(mining_goals, mining_goals_name_cmp);
  969. #ifdef HAVE_CURSES
  970. devcursor = 7 + active_goals;
  971. switch_logsize();
  972. #endif
  973. }
  974. return goal;
  975. }
  976. void mining_goal_reset(struct mining_goal_info * const goal)
  977. {
  978. struct blockchain_info * const blkchain = goal->blkchain;
  979. struct block_info *blkinfo, *tmpblkinfo;
  980. HASH_ITER(hh, blkchain->blocks, blkinfo, tmpblkinfo)
  981. {
  982. HASH_DEL(blkchain->blocks, blkinfo);
  983. free(blkinfo);
  984. }
  985. blkchain_init_block(blkchain);
  986. }
  987. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  988. /* Adjust all the pools' quota to the greatest common denominator after a pool
  989. * has been added or the quotas changed. */
  990. void adjust_quota_gcd(void)
  991. {
  992. unsigned long gcd, lowest_quota = ~0UL, quota;
  993. struct pool *pool;
  994. int i;
  995. for (i = 0; i < total_pools; i++) {
  996. pool = pools[i];
  997. quota = pool->quota;
  998. if (!quota)
  999. continue;
  1000. if (quota < lowest_quota)
  1001. lowest_quota = quota;
  1002. }
  1003. if (likely(lowest_quota < ~0UL)) {
  1004. gcd = lowest_quota;
  1005. for (i = 0; i < total_pools; i++) {
  1006. pool = pools[i];
  1007. quota = pool->quota;
  1008. if (!quota)
  1009. continue;
  1010. while (quota % gcd)
  1011. gcd--;
  1012. }
  1013. } else
  1014. gcd = 1;
  1015. for (i = 0; i < total_pools; i++) {
  1016. pool = pools[i];
  1017. pool->quota_used *= global_quota_gcd;
  1018. pool->quota_used /= gcd;
  1019. pool->quota_gcd = pool->quota / gcd;
  1020. }
  1021. global_quota_gcd = gcd;
  1022. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  1023. }
  1024. /* Return value is ignored if not called from add_pool_details */
  1025. struct pool *add_pool2(struct mining_goal_info * const goal)
  1026. {
  1027. struct pool *pool;
  1028. pool = calloc(sizeof(struct pool), 1);
  1029. if (!pool)
  1030. quit(1, "Failed to malloc pool in add_pool");
  1031. pool->pool_no = pool->prio = total_pools;
  1032. mutex_init(&pool->last_work_lock);
  1033. mutex_init(&pool->pool_lock);
  1034. mutex_init(&pool->pool_test_lock);
  1035. if (unlikely(pthread_cond_init(&pool->cr_cond, bfg_condattr)))
  1036. quit(1, "Failed to pthread_cond_init in add_pool");
  1037. cglock_init(&pool->data_lock);
  1038. mutex_init(&pool->stratum_lock);
  1039. timer_unset(&pool->swork.tv_transparency);
  1040. pool->swork.pool = pool;
  1041. pool->goal = goal;
  1042. pool->idle = true;
  1043. /* Make sure the pool doesn't think we've been idle since time 0 */
  1044. pool->tv_idle.tv_sec = ~0UL;
  1045. cgtime(&pool->cgminer_stats.start_tv);
  1046. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  1047. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  1048. pool->rpc_proxy = NULL;
  1049. pool->quota = 1;
  1050. pool->sock = INVSOCK;
  1051. pool->lp_socket = CURL_SOCKET_BAD;
  1052. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  1053. pools[total_pools++] = pool;
  1054. if (opt_benchmark)
  1055. {
  1056. // Immediately remove it
  1057. remove_pool(pool);
  1058. return pool;
  1059. }
  1060. adjust_quota_gcd();
  1061. if (!currentpool)
  1062. currentpool = pool;
  1063. enable_pool(pool);
  1064. return pool;
  1065. }
  1066. static
  1067. void pool_set_uri(struct pool * const pool, char * const uri)
  1068. {
  1069. pool->rpc_url = uri;
  1070. pool->pool_diff_effective_retroactively = uri_get_param_bool2(uri, "retrodiff");
  1071. }
  1072. static
  1073. bool pool_diff_effective_retroactively(struct pool * const pool)
  1074. {
  1075. if (pool->pool_diff_effective_retroactively != BTS_UNKNOWN) {
  1076. return pool->pool_diff_effective_retroactively;
  1077. }
  1078. // By default, we enable retrodiff for stratum pools since some servers implement mining.set_difficulty in this way
  1079. // Note that share_result will explicitly disable BTS_UNKNOWN -> BTS_FALSE if a retrodiff share is rejected specifically for its failure to meet the target.
  1080. return pool->stratum_active;
  1081. }
  1082. /* Pool variant of test and set */
  1083. static bool pool_tset(struct pool *pool, bool *var)
  1084. {
  1085. bool ret;
  1086. mutex_lock(&pool->pool_lock);
  1087. ret = *var;
  1088. *var = true;
  1089. mutex_unlock(&pool->pool_lock);
  1090. return ret;
  1091. }
  1092. bool pool_tclear(struct pool *pool, bool *var)
  1093. {
  1094. bool ret;
  1095. mutex_lock(&pool->pool_lock);
  1096. ret = *var;
  1097. *var = false;
  1098. mutex_unlock(&pool->pool_lock);
  1099. return ret;
  1100. }
  1101. struct pool *current_pool(void)
  1102. {
  1103. struct pool *pool;
  1104. cg_rlock(&control_lock);
  1105. pool = currentpool;
  1106. cg_runlock(&control_lock);
  1107. return pool;
  1108. }
  1109. #if defined(USE_CPUMINING) && !defined(USE_SHA256D)
  1110. static
  1111. char *arg_ignored(const char * const arg)
  1112. {
  1113. return NULL;
  1114. }
  1115. #endif
  1116. static
  1117. char *set_bool_ignore_arg(const char * const arg, bool * const b)
  1118. {
  1119. return opt_set_bool(b);
  1120. }
  1121. char *set_int_range(const char *arg, int *i, int min, int max)
  1122. {
  1123. char *err = opt_set_intval(arg, i);
  1124. if (err)
  1125. return err;
  1126. if (*i < min || *i > max)
  1127. return "Value out of range";
  1128. return NULL;
  1129. }
  1130. static char *set_int_0_to_9999(const char *arg, int *i)
  1131. {
  1132. return set_int_range(arg, i, 0, 9999);
  1133. }
  1134. static char *set_int_1_to_65535(const char *arg, int *i)
  1135. {
  1136. return set_int_range(arg, i, 1, 65535);
  1137. }
  1138. static char *set_int_0_to_10(const char *arg, int *i)
  1139. {
  1140. return set_int_range(arg, i, 0, 10);
  1141. }
  1142. static char *set_int_1_to_10(const char *arg, int *i)
  1143. {
  1144. return set_int_range(arg, i, 1, 10);
  1145. }
  1146. char *set_strdup(const char *arg, char **p)
  1147. {
  1148. *p = strdup((char *)arg);
  1149. return NULL;
  1150. }
  1151. #if BLKMAKER_VERSION > 1
  1152. static
  1153. char *set_b58addr(const char * const arg, bytes_t * const b)
  1154. {
  1155. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  1156. if (!scriptsz)
  1157. return "Invalid address";
  1158. char *script = malloc(scriptsz);
  1159. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  1160. free(script);
  1161. return "Failed to convert address to script";
  1162. }
  1163. bytes_assimilate_raw(b, script, scriptsz, scriptsz);
  1164. return NULL;
  1165. }
  1166. static char *set_generate_addr2(struct mining_goal_info *, const char *);
  1167. static
  1168. char *set_generate_addr(char *arg)
  1169. {
  1170. char * const colon = strchr(arg, ':');
  1171. struct mining_goal_info *goal;
  1172. if (colon)
  1173. {
  1174. colon[0] = '\0';
  1175. goal = get_mining_goal(arg);
  1176. arg = &colon[1];
  1177. }
  1178. else
  1179. goal = get_mining_goal("default");
  1180. return set_generate_addr2(goal, arg);
  1181. }
  1182. static
  1183. char *set_generate_addr2(struct mining_goal_info * const goal, const char * const arg)
  1184. {
  1185. bytes_t newscript = BYTES_INIT;
  1186. char *estr = set_b58addr(arg, &newscript);
  1187. if (estr)
  1188. {
  1189. bytes_free(&newscript);
  1190. return estr;
  1191. }
  1192. if (!goal->generation_script)
  1193. {
  1194. goal->generation_script = malloc(sizeof(*goal->generation_script));
  1195. bytes_init(goal->generation_script);
  1196. }
  1197. bytes_assimilate(goal->generation_script, &newscript);
  1198. bytes_free(&newscript);
  1199. return NULL;
  1200. }
  1201. #endif
  1202. static
  1203. char *set_quit_summary(const char * const arg)
  1204. {
  1205. if (!(strcasecmp(arg, "none") && strcasecmp(arg, "no")))
  1206. opt_quit_summary = BQS_NONE;
  1207. else
  1208. if (!(strcasecmp(arg, "devs") && strcasecmp(arg, "devices")))
  1209. opt_quit_summary = BQS_DEVS;
  1210. else
  1211. if (!(strcasecmp(arg, "procs") && strcasecmp(arg, "processors") && strcasecmp(arg, "chips") && strcasecmp(arg, "cores")))
  1212. opt_quit_summary = BQS_PROCS;
  1213. else
  1214. if (!(strcasecmp(arg, "detailed") && strcasecmp(arg, "detail") && strcasecmp(arg, "all")))
  1215. opt_quit_summary = BQS_DETAILED;
  1216. else
  1217. return "Quit summary must be one of none/devs/procs/detailed";
  1218. return NULL;
  1219. }
  1220. static void pdiff_target_leadzero(void *, double);
  1221. char *set_request_diff(const char *arg, float *p)
  1222. {
  1223. unsigned char target[32];
  1224. char *e = opt_set_floatval(arg, p);
  1225. if (e)
  1226. return e;
  1227. request_bdiff = (double)*p * 0.9999847412109375;
  1228. pdiff_target_leadzero(target, *p);
  1229. request_target_str = malloc(65);
  1230. bin2hex(request_target_str, target, 32);
  1231. return NULL;
  1232. }
  1233. #ifdef NEED_BFG_LOWL_VCOM
  1234. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1235. #ifdef WIN32
  1236. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1237. {
  1238. char dev[PATH_MAX];
  1239. char *devp = dev;
  1240. size_t bufLen = 0x100;
  1241. tryagain: ;
  1242. char buf[bufLen];
  1243. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1244. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1245. bufLen *= 2;
  1246. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1247. goto tryagain;
  1248. }
  1249. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1250. }
  1251. size_t tLen;
  1252. memcpy(devp, "\\\\.\\", 4);
  1253. devp = &devp[4];
  1254. for (char *t = buf; *t; t += tLen) {
  1255. tLen = strlen(t) + 1;
  1256. if (strncmp("COM", t, 3))
  1257. continue;
  1258. memcpy(devp, t, tLen);
  1259. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1260. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1261. }
  1262. }
  1263. #else
  1264. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1265. {
  1266. char dev[PATH_MAX];
  1267. char *devp = dev;
  1268. DIR *D;
  1269. struct dirent *de;
  1270. const char devdir[] = "/dev";
  1271. const size_t devdirlen = sizeof(devdir) - 1;
  1272. char *devpath = devp;
  1273. char *devfile = devpath + devdirlen + 1;
  1274. D = opendir(devdir);
  1275. if (!D)
  1276. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1277. memcpy(devpath, devdir, devdirlen);
  1278. devpath[devdirlen] = '/';
  1279. while ( (de = readdir(D)) ) {
  1280. if (!strncmp(de->d_name, "cu.", 3)
  1281. //don't probe Bluetooth devices - causes bus errors and segfaults
  1282. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1283. goto trydev;
  1284. if (strncmp(de->d_name, "tty", 3))
  1285. continue;
  1286. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1287. continue;
  1288. trydev:
  1289. strcpy(devfile, de->d_name);
  1290. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1291. }
  1292. closedir(D);
  1293. }
  1294. #endif
  1295. #endif
  1296. static char *add_serial(const char *arg)
  1297. {
  1298. string_elist_add(arg, &scan_devices);
  1299. return NULL;
  1300. }
  1301. static
  1302. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1303. {
  1304. string_elist_add(arg, elist);
  1305. return NULL;
  1306. }
  1307. bool get_intrange(const char *arg, int *val1, int *val2)
  1308. {
  1309. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1310. char *p, *p2;
  1311. *val1 = strtol(arg, &p, 0);
  1312. if (arg == p)
  1313. // Zero-length ending number, invalid
  1314. return false;
  1315. while (true)
  1316. {
  1317. if (!p[0])
  1318. {
  1319. *val2 = *val1;
  1320. return true;
  1321. }
  1322. if (p[0] == '-')
  1323. break;
  1324. if (!isspace(p[0]))
  1325. // Garbage, invalid
  1326. return false;
  1327. ++p;
  1328. }
  1329. p2 = &p[1];
  1330. *val2 = strtol(p2, &p, 0);
  1331. if (p2 == p)
  1332. // Zero-length ending number, invalid
  1333. return false;
  1334. while (true)
  1335. {
  1336. if (!p[0])
  1337. return true;
  1338. if (!isspace(p[0]))
  1339. // Garbage, invalid
  1340. return false;
  1341. ++p;
  1342. }
  1343. }
  1344. static
  1345. void _test_intrange(const char *s, const int v[2])
  1346. {
  1347. int a[2];
  1348. if (!get_intrange(s, &a[0], &a[1]))
  1349. {
  1350. ++unittest_failures;
  1351. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1352. }
  1353. for (int i = 0; i < 2; ++i)
  1354. if (unlikely(a[i] != v[i]))
  1355. {
  1356. ++unittest_failures;
  1357. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1358. }
  1359. }
  1360. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1361. static
  1362. void _test_intrange_fail(const char *s)
  1363. {
  1364. int a[2];
  1365. if (get_intrange(s, &a[0], &a[1]))
  1366. {
  1367. ++unittest_failures;
  1368. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1369. }
  1370. }
  1371. static
  1372. void test_intrange()
  1373. {
  1374. _test_intrange("-1--2", -1, -2);
  1375. _test_intrange("-1-2", -1, 2);
  1376. _test_intrange("1--2", 1, -2);
  1377. _test_intrange("1-2", 1, 2);
  1378. _test_intrange("111-222", 111, 222);
  1379. _test_intrange(" 11 - 22 ", 11, 22);
  1380. _test_intrange("+11-+22", 11, 22);
  1381. _test_intrange("-1", -1, -1);
  1382. _test_intrange_fail("all");
  1383. _test_intrange_fail("1-");
  1384. _test_intrange_fail("");
  1385. _test_intrange_fail("1-54x");
  1386. }
  1387. static char *set_devices(char *arg)
  1388. {
  1389. if (*arg) {
  1390. if (*arg == '?') {
  1391. opt_display_devs = true;
  1392. return NULL;
  1393. }
  1394. } else
  1395. return "Invalid device parameters";
  1396. string_elist_add(arg, &opt_devices_enabled_list);
  1397. return NULL;
  1398. }
  1399. static char *set_balance(enum pool_strategy *strategy)
  1400. {
  1401. *strategy = POOL_BALANCE;
  1402. return NULL;
  1403. }
  1404. static char *set_loadbalance(enum pool_strategy *strategy)
  1405. {
  1406. *strategy = POOL_LOADBALANCE;
  1407. return NULL;
  1408. }
  1409. static char *set_rotate(const char *arg, int *i)
  1410. {
  1411. pool_strategy = POOL_ROTATE;
  1412. return set_int_range(arg, i, 0, 9999);
  1413. }
  1414. static char *set_rr(enum pool_strategy *strategy)
  1415. {
  1416. *strategy = POOL_ROUNDROBIN;
  1417. return NULL;
  1418. }
  1419. static
  1420. char *set_benchmark_intense()
  1421. {
  1422. opt_benchmark = true;
  1423. opt_benchmark_intense = true;
  1424. return NULL;
  1425. }
  1426. /* Detect that url is for a stratum protocol either via the presence of
  1427. * stratum+tcp or by detecting a stratum server response */
  1428. bool detect_stratum(struct pool *pool, char *url)
  1429. {
  1430. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1431. return false;
  1432. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1433. pool_set_uri(pool, strdup(url));
  1434. pool->has_stratum = true;
  1435. pool->stratum_url = pool->sockaddr_url;
  1436. return true;
  1437. }
  1438. return false;
  1439. }
  1440. static struct pool *add_url(void)
  1441. {
  1442. total_urls++;
  1443. if (total_urls > total_pools)
  1444. add_pool();
  1445. return pools[total_urls - 1];
  1446. }
  1447. static void setup_url(struct pool *pool, char *arg)
  1448. {
  1449. if (detect_stratum(pool, arg))
  1450. return;
  1451. opt_set_charp(arg, &pool->rpc_url);
  1452. if (strncmp(arg, "http://", 7) &&
  1453. strncmp(arg, "https://", 8)) {
  1454. const size_t L = strlen(arg);
  1455. char *httpinput;
  1456. httpinput = malloc(8 + L);
  1457. if (!httpinput)
  1458. quit(1, "Failed to malloc httpinput");
  1459. sprintf(httpinput, "http://%s", arg);
  1460. pool_set_uri(pool, httpinput);
  1461. }
  1462. }
  1463. static char *set_url(char *arg)
  1464. {
  1465. struct pool *pool = add_url();
  1466. setup_url(pool, arg);
  1467. return NULL;
  1468. }
  1469. static char *set_quota(char *arg)
  1470. {
  1471. char *semicolon = strchr(arg, ';'), *url;
  1472. int len, qlen, quota;
  1473. struct pool *pool;
  1474. if (!semicolon)
  1475. return "No semicolon separated quota;URL pair found";
  1476. len = strlen(arg);
  1477. *semicolon = '\0';
  1478. qlen = strlen(arg);
  1479. if (!qlen)
  1480. return "No parameter for quota found";
  1481. len -= qlen + 1;
  1482. if (len < 1)
  1483. return "No parameter for URL found";
  1484. quota = atoi(arg);
  1485. if (quota < 0)
  1486. return "Invalid negative parameter for quota set";
  1487. url = arg + qlen + 1;
  1488. pool = add_url();
  1489. setup_url(pool, url);
  1490. pool->quota = quota;
  1491. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1492. adjust_quota_gcd();
  1493. return NULL;
  1494. }
  1495. static char *set_user(const char *arg)
  1496. {
  1497. struct pool *pool;
  1498. total_users++;
  1499. if (total_users > total_pools)
  1500. add_pool();
  1501. pool = pools[total_users - 1];
  1502. opt_set_charp(arg, &pool->rpc_user);
  1503. return NULL;
  1504. }
  1505. static char *set_pass(const char *arg)
  1506. {
  1507. struct pool *pool;
  1508. total_passes++;
  1509. if (total_passes > total_pools)
  1510. add_pool();
  1511. pool = pools[total_passes - 1];
  1512. opt_set_charp(arg, &pool->rpc_pass);
  1513. return NULL;
  1514. }
  1515. static char *set_userpass(const char *arg)
  1516. {
  1517. struct pool *pool;
  1518. char *updup;
  1519. if (total_users != total_passes)
  1520. return "User + pass options must be balanced before userpass";
  1521. ++total_users;
  1522. ++total_passes;
  1523. if (total_users > total_pools)
  1524. add_pool();
  1525. pool = pools[total_users - 1];
  1526. updup = strdup(arg);
  1527. opt_set_charp(arg, &pool->rpc_userpass);
  1528. pool->rpc_user = updup;
  1529. pool->rpc_pass = strchr(updup, ':');
  1530. if (pool->rpc_pass)
  1531. pool->rpc_pass++[0] = '\0';
  1532. else
  1533. pool->rpc_pass = &updup[strlen(updup)];
  1534. return NULL;
  1535. }
  1536. static char *set_cbcaddr(char *arg)
  1537. {
  1538. struct pool *pool;
  1539. char *p, *addr;
  1540. bytes_t target_script = BYTES_INIT;
  1541. if (!total_pools)
  1542. return "Define pool first, then the --coinbase-check-addr list";
  1543. pool = pools[total_pools - 1];
  1544. /* NOTE: 'x' is a new prefix which leads both mainnet and testnet address, we would
  1545. * need support it later, but now leave the code just so.
  1546. *
  1547. * Regarding details of address prefix 'x', check the below URL:
  1548. * https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Serialization_format
  1549. */
  1550. pool->cb_param.testnet = (arg[0] != '1' && arg[0] != '3' && arg[0] != 'x');
  1551. for (; (addr = strtok_r(arg, ",", &p)); arg = NULL)
  1552. {
  1553. struct bytes_hashtbl *ah;
  1554. if (set_b58addr(addr, &target_script))
  1555. /* No bother to free memory since we are going to exit anyway */
  1556. return "Invalid address in --coinbase-check-address list";
  1557. HASH_FIND(hh, pool->cb_param.scripts, bytes_buf(&target_script), bytes_len(&target_script), ah);
  1558. if (!ah)
  1559. {
  1560. /* Note: for the below allocated memory we have good way to release its memory
  1561. * since we can't be sure there are no reference to the pool struct when remove_pool()
  1562. * get called.
  1563. *
  1564. * We just hope the remove_pool() would not be called many many times during
  1565. * the whole running life of this program.
  1566. */
  1567. ah = malloc(sizeof(*ah));
  1568. bytes_init(&ah->b);
  1569. bytes_assimilate(&ah->b, &target_script);
  1570. HASH_ADD(hh, pool->cb_param.scripts, b.buf, bytes_len(&ah->b), ah);
  1571. }
  1572. }
  1573. bytes_free(&target_script);
  1574. return NULL;
  1575. }
  1576. static char *set_cbctotal(const char *arg)
  1577. {
  1578. struct pool *pool;
  1579. if (!total_pools)
  1580. return "Define pool first, then the --coinbase-check-total argument";
  1581. pool = pools[total_pools - 1];
  1582. pool->cb_param.total = atoll(arg);
  1583. if (pool->cb_param.total < 0)
  1584. return "The total payout amount in coinbase should be greater than 0";
  1585. return NULL;
  1586. }
  1587. static char *set_cbcperc(const char *arg)
  1588. {
  1589. struct pool *pool;
  1590. if (!total_pools)
  1591. return "Define pool first, then the --coinbase-check-percent argument";
  1592. pool = pools[total_pools - 1];
  1593. if (!pool->cb_param.scripts)
  1594. return "Define --coinbase-check-addr list first, then the --coinbase-check-total argument";
  1595. pool->cb_param.perc = atof(arg) / 100;
  1596. if (pool->cb_param.perc < 0.0 || pool->cb_param.perc > 1.0)
  1597. return "The percentage should be between 0 and 100";
  1598. return NULL;
  1599. }
  1600. static
  1601. const char *goal_set(struct mining_goal_info * const goal, const char * const optname, const char * const newvalue, bytes_t * const replybuf, enum bfg_set_device_replytype * const out_success)
  1602. {
  1603. *out_success = SDR_ERR;
  1604. if (!(strcasecmp(optname, "malgo") && strcasecmp(optname, "algo")))
  1605. {
  1606. if (!newvalue)
  1607. return "Goal option 'malgo' requires a value (eg, SHA256d)";
  1608. struct mining_algorithm * const new_malgo = mining_algorithm_by_alias(newvalue);
  1609. if (!new_malgo)
  1610. return "Unrecognised mining algorithm";
  1611. goal_set_malgo(goal, new_malgo);
  1612. goto success;
  1613. }
  1614. #if BLKMAKER_VERSION > 1
  1615. if (match_strtok("generate-to|generate-to-addr|generate-to-address|genaddress|genaddr|gen-address|gen-addr|generate-address|generate-addr|coinbase-addr|coinbase-address|coinbase-payout|cbaddress|cbaddr|cb-address|cb-addr|payout", "|", optname))
  1616. {
  1617. if (!newvalue)
  1618. return "Missing value for 'generate-to' goal option";
  1619. const char * const emsg = set_generate_addr2(goal, newvalue);
  1620. if (emsg)
  1621. return emsg;
  1622. goto success;
  1623. }
  1624. #endif
  1625. *out_success = SDR_UNKNOWN;
  1626. return "Unknown goal option";
  1627. success:
  1628. *out_success = SDR_OK;
  1629. return NULL;
  1630. }
  1631. // May leak replybuf if returning an error
  1632. static
  1633. const char *set_goal_params(struct mining_goal_info * const goal, char *arg)
  1634. {
  1635. bytes_t replybuf = BYTES_INIT;
  1636. for (char *param, *nextptr; (param = strtok_r(arg, ",", &nextptr)); arg = NULL)
  1637. {
  1638. char *val = strchr(param, '=');
  1639. if (val)
  1640. val++[0] = '\0';
  1641. enum bfg_set_device_replytype success;
  1642. const char * const emsg = goal_set(goal, param, val, &replybuf, &success);
  1643. if (success != SDR_OK)
  1644. return emsg ?: "Error setting goal param";
  1645. }
  1646. bytes_free(&replybuf);
  1647. return NULL;
  1648. }
  1649. static
  1650. const char *set_pool_goal(const char * const arg)
  1651. {
  1652. struct pool *pool;
  1653. if (!total_pools)
  1654. return "Usage of --pool-goal before pools are defined does not make sense";
  1655. pool = pools[total_pools - 1];
  1656. char *param = strchr(arg, ':');
  1657. if (param)
  1658. param++[0] = '\0';
  1659. pool->goal = get_mining_goal(arg);
  1660. if (param)
  1661. return set_goal_params(pool->goal, param);
  1662. return NULL;
  1663. }
  1664. static char *set_pool_priority(const char *arg)
  1665. {
  1666. struct pool *pool;
  1667. if (!total_pools)
  1668. return "Usage of --pool-priority before pools are defined does not make sense";
  1669. pool = pools[total_pools - 1];
  1670. opt_set_intval(arg, &pool->prio);
  1671. return NULL;
  1672. }
  1673. static char *set_pool_proxy(const char *arg)
  1674. {
  1675. struct pool *pool;
  1676. if (!total_pools)
  1677. return "Usage of --pool-proxy before pools are defined does not make sense";
  1678. if (!our_curl_supports_proxy_uris())
  1679. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1680. pool = pools[total_pools - 1];
  1681. opt_set_charp(arg, &pool->rpc_proxy);
  1682. return NULL;
  1683. }
  1684. static char *set_pool_force_rollntime(const char *arg)
  1685. {
  1686. struct pool *pool;
  1687. if (!total_pools)
  1688. return "Usage of --force-rollntime before pools are defined does not make sense";
  1689. pool = pools[total_pools - 1];
  1690. opt_set_intval(arg, &pool->force_rollntime);
  1691. return NULL;
  1692. }
  1693. static char *enable_debug(bool *flag)
  1694. {
  1695. *flag = true;
  1696. opt_debug_console = true;
  1697. /* Turn on verbose output, too. */
  1698. opt_log_output = true;
  1699. return NULL;
  1700. }
  1701. static char *set_schedtime(const char *arg, struct schedtime *st)
  1702. {
  1703. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1704. {
  1705. if (strcasecmp(arg, "now"))
  1706. return "Invalid time set, should be HH:MM";
  1707. } else
  1708. schedstop.tm.tm_sec = 0;
  1709. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1710. return "Invalid time set.";
  1711. st->enable = true;
  1712. return NULL;
  1713. }
  1714. static
  1715. char *set_log_file(char *arg)
  1716. {
  1717. char *r = "";
  1718. long int i = strtol(arg, &r, 10);
  1719. int fd, stderr_fd = fileno(stderr);
  1720. if ((!*r) && i >= 0 && i <= INT_MAX)
  1721. fd = i;
  1722. else
  1723. if (!strcmp(arg, "-"))
  1724. {
  1725. fd = fileno(stdout);
  1726. if (unlikely(fd == -1))
  1727. return "Standard output missing for log-file";
  1728. }
  1729. else
  1730. {
  1731. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1732. if (unlikely(fd == -1))
  1733. return "Failed to open log-file";
  1734. }
  1735. close(stderr_fd);
  1736. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1737. return "Failed to dup2 for log-file";
  1738. close(fd);
  1739. return NULL;
  1740. }
  1741. static
  1742. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1743. {
  1744. char *r = "";
  1745. long int i = strtol(arg, &r, 10);
  1746. static char *err = NULL;
  1747. const size_t errbufsz = 0x100;
  1748. free(err);
  1749. err = NULL;
  1750. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1751. *F = fdopen((int)i, mode);
  1752. if (!*F)
  1753. {
  1754. err = malloc(errbufsz);
  1755. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1756. (int)i, purpose);
  1757. return err;
  1758. }
  1759. } else if (!strcmp(arg, "-")) {
  1760. *F = (mode[0] == 'a') ? stdout : stdin;
  1761. if (!*F)
  1762. {
  1763. err = malloc(errbufsz);
  1764. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1765. (mode[0] == 'a') ? "out" : "in", purpose);
  1766. return err;
  1767. }
  1768. } else {
  1769. *F = fopen(arg, mode);
  1770. if (!*F)
  1771. {
  1772. err = malloc(errbufsz);
  1773. snprintf(err, errbufsz, "Failed to open %s for %s",
  1774. arg, purpose);
  1775. return err;
  1776. }
  1777. }
  1778. return NULL;
  1779. }
  1780. static char *set_noncelog(char *arg)
  1781. {
  1782. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1783. }
  1784. static char *set_sharelog(char *arg)
  1785. {
  1786. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1787. }
  1788. static
  1789. void _add_set_device_option(const char * const func, const char * const buf)
  1790. {
  1791. applog(LOG_DEBUG, "%s: Using --set-device %s", func, buf);
  1792. string_elist_add(buf, &opt_set_device_list);
  1793. }
  1794. #define add_set_device_option(...) do{ \
  1795. char _tmp1718[0x100]; \
  1796. snprintf(_tmp1718, sizeof(_tmp1718), __VA_ARGS__); \
  1797. _add_set_device_option(__func__, _tmp1718); \
  1798. }while(0)
  1799. char *set_temp_cutoff(char *arg)
  1800. {
  1801. if (strchr(arg, ','))
  1802. return "temp-cutoff no longer supports comma-delimited syntax, use --set-device for better control";
  1803. applog(LOG_WARNING, "temp-cutoff is deprecated! Use --set-device for better control");
  1804. add_set_device_option("all:temp-cutoff=%s", arg);
  1805. return NULL;
  1806. }
  1807. char *set_temp_target(char *arg)
  1808. {
  1809. if (strchr(arg, ','))
  1810. return "temp-target no longer supports comma-delimited syntax, use --set-device for better control";
  1811. applog(LOG_WARNING, "temp-target is deprecated! Use --set-device for better control");
  1812. add_set_device_option("all:temp-target=%s", arg);
  1813. return NULL;
  1814. }
  1815. #ifdef USE_OPENCL
  1816. static
  1817. char *set_no_opencl_binaries(__maybe_unused void * const dummy)
  1818. {
  1819. applog(LOG_WARNING, "The --no-opencl-binaries option is deprecated! Use --set-device OCL:binary=no");
  1820. add_set_device_option("OCL:binary=no");
  1821. return NULL;
  1822. }
  1823. #endif
  1824. static
  1825. char *disable_pool_redirect(__maybe_unused void * const dummy)
  1826. {
  1827. opt_disable_client_reconnect = true;
  1828. want_stratum = false;
  1829. return NULL;
  1830. }
  1831. static char *set_api_allow(const char *arg)
  1832. {
  1833. opt_set_charp(arg, &opt_api_allow);
  1834. return NULL;
  1835. }
  1836. static char *set_api_groups(const char *arg)
  1837. {
  1838. opt_set_charp(arg, &opt_api_groups);
  1839. return NULL;
  1840. }
  1841. static char *set_api_description(const char *arg)
  1842. {
  1843. opt_set_charp(arg, &opt_api_description);
  1844. return NULL;
  1845. }
  1846. static char *set_api_mcast_des(const char *arg)
  1847. {
  1848. opt_set_charp(arg, &opt_api_mcast_des);
  1849. return NULL;
  1850. }
  1851. #ifdef USE_ICARUS
  1852. extern const struct bfg_set_device_definition icarus_set_device_funcs[];
  1853. static char *set_icarus_options(const char *arg)
  1854. {
  1855. if (strchr(arg, ','))
  1856. return "icarus-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1857. applog(LOG_WARNING, "icarus-options is deprecated! See README.FPGA for better control");
  1858. char *opts = strdup(arg), *argdup;
  1859. argdup = opts;
  1860. const struct bfg_set_device_definition *sdf = icarus_set_device_funcs;
  1861. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1862. char *saveptr, *opt;
  1863. for (int i = 0; i < 4; ++i, ++sdf)
  1864. {
  1865. opt = strtok_r(opts, ":", &saveptr);
  1866. opts = NULL;
  1867. if (!opt)
  1868. break;
  1869. if (!opt[0])
  1870. continue;
  1871. for (int j = 0; j < 4; ++j)
  1872. add_set_device_option("%s:%s=%s", drivers[j], sdf->optname, opt);
  1873. }
  1874. free(argdup);
  1875. return NULL;
  1876. }
  1877. static char *set_icarus_timing(const char *arg)
  1878. {
  1879. if (strchr(arg, ','))
  1880. return "icarus-timing no longer supports comma-delimited syntax, see README.FPGA for better control";
  1881. applog(LOG_WARNING, "icarus-timing is deprecated! See README.FPGA for better control");
  1882. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1883. for (int j = 0; j < 4; ++j)
  1884. add_set_device_option("%s:timing=%s", drivers[j], arg);
  1885. return NULL;
  1886. }
  1887. #endif
  1888. #ifdef USE_AVALON
  1889. extern const struct bfg_set_device_definition avalon_set_device_funcs[];
  1890. static char *set_avalon_options(const char *arg)
  1891. {
  1892. if (strchr(arg, ','))
  1893. return "avalon-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1894. applog(LOG_WARNING, "avalon-options is deprecated! See README.FPGA for better control");
  1895. char *opts = strdup(arg), *argdup;
  1896. argdup = opts;
  1897. const struct bfg_set_device_definition *sdf = avalon_set_device_funcs;
  1898. char *saveptr, *opt;
  1899. for (int i = 0; i < 5; ++i, ++sdf)
  1900. {
  1901. opt = strtok_r(opts, ":", &saveptr);
  1902. opts = NULL;
  1903. if (!opt)
  1904. break;
  1905. if (!opt[0])
  1906. continue;
  1907. add_set_device_option("avalon:%s=%s", sdf->optname, opt);
  1908. }
  1909. free(argdup);
  1910. return NULL;
  1911. }
  1912. #endif
  1913. #ifdef USE_KLONDIKE
  1914. static char *set_klondike_options(const char *arg)
  1915. {
  1916. int hashclock;
  1917. double temptarget;
  1918. switch (sscanf(arg, "%d:%lf", &hashclock, &temptarget))
  1919. {
  1920. default:
  1921. return "Unrecognised --klondike-options";
  1922. case 2:
  1923. add_set_device_option("klondike:temp-target=%lf", temptarget);
  1924. // fallthru
  1925. case 1:
  1926. add_set_device_option("klondike:clock=%d", hashclock);
  1927. }
  1928. applog(LOG_WARNING, "klondike-options is deprecated! Use --set-device for better control");
  1929. return NULL;
  1930. }
  1931. #endif
  1932. __maybe_unused
  1933. static char *set_null(const char __maybe_unused *arg)
  1934. {
  1935. return NULL;
  1936. }
  1937. /* These options are available from config file or commandline */
  1938. static struct opt_table opt_config_table[] = {
  1939. #ifdef USE_CPUMINING
  1940. #ifdef USE_SHA256D
  1941. OPT_WITH_ARG("--algo",
  1942. set_algo, show_algo, &opt_algo,
  1943. "Specify sha256 implementation for CPU mining:\n"
  1944. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1945. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1946. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1947. #ifdef WANT_SSE2_4WAY
  1948. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1949. #endif
  1950. #ifdef WANT_VIA_PADLOCK
  1951. "\n\tvia\t\tVIA padlock implementation"
  1952. #endif
  1953. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1954. #ifdef WANT_CRYPTOPP_ASM32
  1955. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1956. #endif
  1957. #ifdef WANT_X8632_SSE2
  1958. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1959. #endif
  1960. #ifdef WANT_X8664_SSE2
  1961. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1962. #endif
  1963. #ifdef WANT_X8664_SSE4
  1964. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1965. #endif
  1966. #ifdef WANT_ALTIVEC_4WAY
  1967. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1968. #endif
  1969. ),
  1970. OPT_WITH_ARG("-a",
  1971. set_algo, show_algo, &opt_algo,
  1972. opt_hidden),
  1973. #else
  1974. // NOTE: Silently ignoring option, since it is plausable a non-SHA256d miner was using it just to skip benchmarking
  1975. OPT_WITH_ARG("--algo|-a", arg_ignored, NULL, NULL, opt_hidden),
  1976. #endif /* USE_SHA256D */
  1977. #endif /* USE_CPUMINING */
  1978. OPT_WITH_ARG("--api-allow",
  1979. set_api_allow, NULL, NULL,
  1980. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1981. OPT_WITH_ARG("--api-description",
  1982. set_api_description, NULL, NULL,
  1983. "Description placed in the API status header, default: BFGMiner version"),
  1984. OPT_WITH_ARG("--api-groups",
  1985. set_api_groups, NULL, NULL,
  1986. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1987. OPT_WITHOUT_ARG("--api-listen",
  1988. opt_set_bool, &opt_api_listen,
  1989. "Enable API, default: disabled"),
  1990. OPT_WITHOUT_ARG("--api-mcast",
  1991. opt_set_bool, &opt_api_mcast,
  1992. "Enable API Multicast listener, default: disabled"),
  1993. OPT_WITH_ARG("--api-mcast-addr",
  1994. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  1995. "API Multicast listen address"),
  1996. OPT_WITH_ARG("--api-mcast-code",
  1997. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  1998. "Code expected in the API Multicast message, don't use '-'"),
  1999. OPT_WITH_ARG("--api-mcast-des",
  2000. set_api_mcast_des, NULL, NULL,
  2001. "Description appended to the API Multicast reply, default: ''"),
  2002. OPT_WITH_ARG("--api-mcast-port",
  2003. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  2004. "API Multicast listen port"),
  2005. OPT_WITHOUT_ARG("--api-network",
  2006. opt_set_bool, &opt_api_network,
  2007. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  2008. OPT_WITH_ARG("--api-port",
  2009. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  2010. "Port number of miner API"),
  2011. #ifdef HAVE_ADL
  2012. OPT_WITHOUT_ARG("--auto-fan",
  2013. opt_set_bool, &opt_autofan,
  2014. opt_hidden),
  2015. OPT_WITHOUT_ARG("--auto-gpu",
  2016. opt_set_bool, &opt_autoengine,
  2017. opt_hidden),
  2018. #endif
  2019. OPT_WITHOUT_ARG("--balance",
  2020. set_balance, &pool_strategy,
  2021. "Change multipool strategy from failover to even share balance"),
  2022. OPT_WITHOUT_ARG("--benchmark",
  2023. opt_set_bool, &opt_benchmark,
  2024. "Run BFGMiner in benchmark mode - produces no shares"),
  2025. OPT_WITHOUT_ARG("--benchmark-intense",
  2026. set_benchmark_intense, &opt_benchmark_intense,
  2027. "Run BFGMiner in intensive benchmark mode - produces no shares"),
  2028. #if defined(USE_BITFORCE)
  2029. OPT_WITHOUT_ARG("--bfl-range",
  2030. opt_set_bool, &opt_bfl_noncerange,
  2031. "Use nonce range on bitforce devices if supported"),
  2032. #endif
  2033. #ifdef HAVE_CHROOT
  2034. OPT_WITH_ARG("--chroot-dir",
  2035. opt_set_charp, NULL, &chroot_dir,
  2036. "Chroot to a directory right after startup"),
  2037. #endif
  2038. OPT_WITH_ARG("--cmd-idle",
  2039. opt_set_charp, NULL, &cmd_idle,
  2040. "Execute a command when a device is allowed to be idle (rest or wait)"),
  2041. OPT_WITH_ARG("--cmd-sick",
  2042. opt_set_charp, NULL, &cmd_sick,
  2043. "Execute a command when a device is declared sick"),
  2044. OPT_WITH_ARG("--cmd-dead",
  2045. opt_set_charp, NULL, &cmd_dead,
  2046. "Execute a command when a device is declared dead"),
  2047. #if BLKMAKER_VERSION > 0
  2048. OPT_WITH_ARG("--coinbase-sig",
  2049. set_strdup, NULL, &opt_coinbase_sig,
  2050. "Set coinbase signature when possible"),
  2051. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  2052. set_strdup, NULL, &opt_coinbase_sig,
  2053. opt_hidden),
  2054. #endif
  2055. #ifdef HAVE_CURSES
  2056. OPT_WITHOUT_ARG("--compact",
  2057. opt_set_bool, &opt_compact,
  2058. "Use compact display without per device statistics"),
  2059. #endif
  2060. #ifdef USE_CPUMINING
  2061. OPT_WITH_ARG("--cpu-threads",
  2062. force_nthreads_int, opt_show_intval, &opt_n_threads,
  2063. "Number of miner CPU threads"),
  2064. OPT_WITH_ARG("-t",
  2065. force_nthreads_int, opt_show_intval, &opt_n_threads,
  2066. opt_hidden),
  2067. #endif
  2068. OPT_WITHOUT_ARG("--debug|-D",
  2069. enable_debug, &opt_debug,
  2070. "Enable debug output"),
  2071. OPT_WITHOUT_ARG("--debuglog",
  2072. opt_set_bool, &opt_debug,
  2073. "Enable debug logging"),
  2074. OPT_WITHOUT_ARG("--device-protocol-dump",
  2075. opt_set_bool, &opt_dev_protocol,
  2076. "Verbose dump of device protocol-level activities"),
  2077. OPT_WITH_ARG("--device|-d",
  2078. set_devices, NULL, NULL,
  2079. "Enable only devices matching pattern (default: all)"),
  2080. OPT_WITHOUT_ARG("--disable-rejecting",
  2081. opt_set_bool, &opt_disable_pool,
  2082. "Automatically disable pools that continually reject shares"),
  2083. #ifdef USE_LIBMICROHTTPD
  2084. OPT_WITH_ARG("--http-port",
  2085. opt_set_intval, opt_show_intval, &httpsrv_port,
  2086. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  2087. #endif
  2088. OPT_WITH_ARG("--expiry",
  2089. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  2090. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  2091. OPT_WITH_ARG("-E",
  2092. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  2093. opt_hidden),
  2094. OPT_WITH_ARG("--expiry-lp",
  2095. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  2096. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  2097. OPT_WITHOUT_ARG("--failover-only",
  2098. opt_set_bool, &opt_fail_only,
  2099. "Don't leak work to backup pools when primary pool is lagging"),
  2100. OPT_WITH_ARG("--failover-switch-delay",
  2101. set_int_1_to_65535, opt_show_intval, &opt_fail_switch_delay,
  2102. "Delay in seconds before switching back to a failed pool"),
  2103. #ifdef USE_FPGA
  2104. OPT_WITHOUT_ARG("--force-dev-init",
  2105. opt_set_bool, &opt_force_dev_init,
  2106. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  2107. #endif
  2108. #if BLKMAKER_VERSION > 1
  2109. OPT_WITH_ARG("--generate-to",
  2110. set_generate_addr, NULL, NULL,
  2111. "Set an address to generate to for solo mining"),
  2112. OPT_WITH_ARG("--generate-to-addr|--generate-to-address|--genaddress|--genaddr|--gen-address|--gen-addr|--generate-address|--generate-addr|--coinbase-addr|--coinbase-address|--coinbase-payout|--cbaddress|--cbaddr|--cb-address|--cb-addr|--payout",
  2113. set_generate_addr, NULL, NULL,
  2114. opt_hidden),
  2115. #endif
  2116. #ifdef USE_OPENCL
  2117. OPT_WITH_ARG("--gpu-dyninterval",
  2118. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  2119. opt_hidden),
  2120. OPT_WITH_ARG("--gpu-platform",
  2121. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  2122. "Select OpenCL platform ID to use for GPU mining"),
  2123. OPT_WITH_ARG("--gpu-threads|-g",
  2124. set_gpu_threads, opt_show_intval, &opt_g_threads,
  2125. opt_hidden),
  2126. #ifdef HAVE_ADL
  2127. OPT_WITH_ARG("--gpu-engine",
  2128. set_gpu_engine, NULL, NULL,
  2129. opt_hidden),
  2130. OPT_WITH_ARG("--gpu-fan",
  2131. set_gpu_fan, NULL, NULL,
  2132. opt_hidden),
  2133. OPT_WITH_ARG("--gpu-map",
  2134. set_gpu_map, NULL, NULL,
  2135. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  2136. OPT_WITH_ARG("--gpu-memclock",
  2137. set_gpu_memclock, NULL, NULL,
  2138. opt_hidden),
  2139. OPT_WITH_ARG("--gpu-memdiff",
  2140. set_gpu_memdiff, NULL, NULL,
  2141. opt_hidden),
  2142. OPT_WITH_ARG("--gpu-powertune",
  2143. set_gpu_powertune, NULL, NULL,
  2144. opt_hidden),
  2145. OPT_WITHOUT_ARG("--gpu-reorder",
  2146. opt_set_bool, &opt_reorder,
  2147. "Attempt to reorder GPU devices according to PCI Bus ID"),
  2148. OPT_WITH_ARG("--gpu-vddc",
  2149. set_gpu_vddc, NULL, NULL,
  2150. opt_hidden),
  2151. #endif
  2152. #ifdef USE_SCRYPT
  2153. OPT_WITH_ARG("--lookup-gap",
  2154. set_lookup_gap, NULL, NULL,
  2155. opt_hidden),
  2156. #endif
  2157. OPT_WITH_ARG("--intensity|-I",
  2158. set_intensity, NULL, NULL,
  2159. opt_hidden),
  2160. #endif
  2161. #if defined(USE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  2162. OPT_WITH_ARG("--kernel-path",
  2163. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2164. "Specify a path to where bitstream and kernel files are"),
  2165. OPT_WITH_ARG("-K",
  2166. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2167. opt_hidden),
  2168. #endif
  2169. #ifdef USE_OPENCL
  2170. OPT_WITH_ARG("--kernel|-k",
  2171. set_kernel, NULL, NULL,
  2172. opt_hidden),
  2173. #endif
  2174. #ifdef USE_ICARUS
  2175. OPT_WITH_ARG("--icarus-options",
  2176. set_icarus_options, NULL, NULL,
  2177. opt_hidden),
  2178. OPT_WITH_ARG("--icarus-timing",
  2179. set_icarus_timing, NULL, NULL,
  2180. opt_hidden),
  2181. #endif
  2182. #ifdef USE_AVALON
  2183. OPT_WITH_ARG("--avalon-options",
  2184. set_avalon_options, NULL, NULL,
  2185. opt_hidden),
  2186. #endif
  2187. #ifdef USE_KLONDIKE
  2188. OPT_WITH_ARG("--klondike-options",
  2189. set_klondike_options, NULL, NULL,
  2190. "Set klondike options clock:temptarget"),
  2191. #endif
  2192. OPT_WITHOUT_ARG("--load-balance",
  2193. set_loadbalance, &pool_strategy,
  2194. "Change multipool strategy from failover to quota based balance"),
  2195. OPT_WITH_ARG("--log|-l",
  2196. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  2197. "Interval in seconds between log output"),
  2198. OPT_WITH_ARG("--log-file|-L",
  2199. set_log_file, NULL, NULL,
  2200. "Append log file for output messages"),
  2201. OPT_WITH_ARG("--logfile",
  2202. set_log_file, NULL, NULL,
  2203. opt_hidden),
  2204. OPT_WITHOUT_ARG("--log-microseconds",
  2205. opt_set_bool, &opt_log_microseconds,
  2206. "Include microseconds in log output"),
  2207. #if defined(unix) || defined(__APPLE__)
  2208. OPT_WITH_ARG("--monitor|-m",
  2209. opt_set_charp, NULL, &opt_stderr_cmd,
  2210. "Use custom pipe cmd for output messages"),
  2211. #endif // defined(unix)
  2212. OPT_WITHOUT_ARG("--net-delay",
  2213. opt_set_bool, &opt_delaynet,
  2214. "Impose small delays in networking to avoid overloading slow routers"),
  2215. OPT_WITHOUT_ARG("--no-adl",
  2216. opt_set_bool, &opt_noadl,
  2217. #ifdef HAVE_ADL
  2218. "Disable the ATI display library used for monitoring and setting GPU parameters"
  2219. #else
  2220. opt_hidden
  2221. #endif
  2222. ),
  2223. OPT_WITHOUT_ARG("--no-gbt",
  2224. opt_set_invbool, &want_gbt,
  2225. "Disable getblocktemplate support"),
  2226. OPT_WITHOUT_ARG("--no-getwork",
  2227. opt_set_invbool, &want_getwork,
  2228. "Disable getwork support"),
  2229. OPT_WITHOUT_ARG("--no-hotplug",
  2230. #ifdef HAVE_BFG_HOTPLUG
  2231. opt_set_invbool, &opt_hotplug,
  2232. "Disable hotplug detection"
  2233. #else
  2234. set_null, &opt_hotplug,
  2235. opt_hidden
  2236. #endif
  2237. ),
  2238. OPT_WITHOUT_ARG("--no-local-bitcoin",
  2239. #if BLKMAKER_VERSION > 1
  2240. opt_set_invbool, &opt_load_bitcoin_conf,
  2241. "Disable adding pools for local bitcoin RPC servers"),
  2242. #else
  2243. set_null, NULL, opt_hidden),
  2244. #endif
  2245. OPT_WITHOUT_ARG("--no-longpoll",
  2246. opt_set_invbool, &want_longpoll,
  2247. "Disable X-Long-Polling support"),
  2248. OPT_WITHOUT_ARG("--no-pool-disable",
  2249. opt_set_invbool, &opt_disable_pool,
  2250. opt_hidden),
  2251. OPT_WITHOUT_ARG("--no-client-reconnect",
  2252. opt_set_invbool, &opt_disable_client_reconnect,
  2253. opt_hidden),
  2254. OPT_WITHOUT_ARG("--no-pool-redirect",
  2255. disable_pool_redirect, NULL,
  2256. "Ignore pool requests to redirect to another server"),
  2257. OPT_WITHOUT_ARG("--no-restart",
  2258. opt_set_invbool, &opt_restart,
  2259. "Do not attempt to restart devices that hang"
  2260. ),
  2261. OPT_WITHOUT_ARG("--no-show-processors",
  2262. opt_set_invbool, &opt_show_procs,
  2263. opt_hidden),
  2264. OPT_WITHOUT_ARG("--no-show-procs",
  2265. opt_set_invbool, &opt_show_procs,
  2266. opt_hidden),
  2267. OPT_WITHOUT_ARG("--no-stratum",
  2268. opt_set_invbool, &want_stratum,
  2269. "Disable Stratum detection"),
  2270. OPT_WITHOUT_ARG("--no-submit-stale",
  2271. opt_set_invbool, &opt_submit_stale,
  2272. "Don't submit shares if they are detected as stale"),
  2273. #ifdef USE_OPENCL
  2274. OPT_WITHOUT_ARG("--no-opencl-binaries",
  2275. set_no_opencl_binaries, NULL,
  2276. opt_hidden),
  2277. #endif
  2278. OPT_WITHOUT_ARG("--no-unicode",
  2279. #ifdef USE_UNICODE
  2280. opt_set_invbool, &use_unicode,
  2281. "Don't use Unicode characters in TUI"
  2282. #else
  2283. set_null, &use_unicode,
  2284. opt_hidden
  2285. #endif
  2286. ),
  2287. OPT_WITH_ARG("--noncelog",
  2288. set_noncelog, NULL, NULL,
  2289. "Create log of all nonces found"),
  2290. OPT_WITH_ARG("--pass|-p",
  2291. set_pass, NULL, NULL,
  2292. "Password for bitcoin JSON-RPC server"),
  2293. OPT_WITHOUT_ARG("--per-device-stats",
  2294. opt_set_bool, &want_per_device_stats,
  2295. "Force verbose mode and output per-device statistics"),
  2296. OPT_WITH_ARG("--userpass|-O",
  2297. set_userpass, NULL, NULL,
  2298. "Username:Password pair for bitcoin JSON-RPC server"),
  2299. OPT_WITH_ARG("--pool-goal",
  2300. set_pool_goal, NULL, NULL,
  2301. "Named goal for the previous-defined pool"),
  2302. OPT_WITH_ARG("--pool-priority",
  2303. set_pool_priority, NULL, NULL,
  2304. "Priority for just the previous-defined pool"),
  2305. OPT_WITH_ARG("--pool-proxy|-x",
  2306. set_pool_proxy, NULL, NULL,
  2307. "Proxy URI to use for connecting to just the previous-defined pool"),
  2308. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  2309. set_pool_force_rollntime, NULL, NULL,
  2310. opt_hidden),
  2311. OPT_WITHOUT_ARG("--protocol-dump|-P",
  2312. opt_set_bool, &opt_protocol,
  2313. "Verbose dump of protocol-level activities"),
  2314. OPT_WITH_ARG("--queue|-Q",
  2315. set_int_0_to_9999, opt_show_intval, &opt_queue,
  2316. "Minimum number of work items to have queued (0+)"),
  2317. OPT_WITHOUT_ARG("--quiet|-q",
  2318. opt_set_bool, &opt_quiet,
  2319. "Disable logging output, display status and errors"),
  2320. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  2321. opt_set_bool, &opt_quiet_work_updates,
  2322. opt_hidden),
  2323. OPT_WITH_ARG("--quit-summary",
  2324. set_quit_summary, NULL, NULL,
  2325. "Summary printed when you quit: none/devs/procs/detailed"),
  2326. OPT_WITH_ARG("--quota|-U",
  2327. set_quota, NULL, NULL,
  2328. "quota;URL combination for server with load-balance strategy quotas"),
  2329. OPT_WITHOUT_ARG("--real-quiet",
  2330. opt_set_bool, &opt_realquiet,
  2331. "Disable all output"),
  2332. OPT_WITH_ARG("--request-diff",
  2333. set_request_diff, opt_show_floatval, &request_pdiff,
  2334. "Request a specific difficulty from pools"),
  2335. OPT_WITH_ARG("--retries",
  2336. opt_set_intval, opt_show_intval, &opt_retries,
  2337. "Number of times to retry failed submissions before giving up (-1 means never)"),
  2338. OPT_WITH_ARG("--retry-pause",
  2339. set_null, NULL, NULL,
  2340. opt_hidden),
  2341. OPT_WITH_ARG("--rotate",
  2342. set_rotate, opt_show_intval, &opt_rotate_period,
  2343. "Change multipool strategy from failover to regularly rotate at N minutes"),
  2344. OPT_WITHOUT_ARG("--round-robin",
  2345. set_rr, &pool_strategy,
  2346. "Change multipool strategy from failover to round robin on failure"),
  2347. OPT_WITH_ARG("--scan|-S",
  2348. add_serial, NULL, NULL,
  2349. "Configure how to scan for mining devices"),
  2350. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  2351. add_serial, NULL, NULL,
  2352. opt_hidden),
  2353. OPT_WITH_ARG("--scan-time",
  2354. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2355. "Upper bound on time spent scanning current work, in seconds"),
  2356. OPT_WITH_ARG("-s",
  2357. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2358. opt_hidden),
  2359. OPT_WITH_ARG("--scantime",
  2360. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2361. opt_hidden),
  2362. OPT_WITH_ARG("--sched-start",
  2363. set_schedtime, NULL, &schedstart,
  2364. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  2365. OPT_WITH_ARG("--sched-stop",
  2366. set_schedtime, NULL, &schedstop,
  2367. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  2368. #ifdef USE_SCRYPT
  2369. OPT_WITHOUT_ARG("--scrypt",
  2370. set_malgo_scrypt, NULL,
  2371. "Use the scrypt algorithm for mining (non-bitcoin)"),
  2372. #endif
  2373. OPT_WITH_ARG("--set-device|--set",
  2374. opt_string_elist_add, NULL, &opt_set_device_list,
  2375. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  2376. #if defined(USE_SCRYPT) && defined(USE_OPENCL)
  2377. OPT_WITH_ARG("--shaders",
  2378. set_shaders, NULL, NULL,
  2379. opt_hidden),
  2380. #endif
  2381. #ifdef HAVE_PWD_H
  2382. OPT_WITH_ARG("--setuid",
  2383. opt_set_charp, NULL, &opt_setuid,
  2384. "Username of an unprivileged user to run as"),
  2385. #endif
  2386. OPT_WITH_ARG("--sharelog",
  2387. set_sharelog, NULL, NULL,
  2388. "Append share log to file"),
  2389. OPT_WITH_ARG("--shares",
  2390. opt_set_floatval, NULL, &opt_shares,
  2391. "Quit after mining 2^32 * N hashes worth of shares (default: unlimited)"),
  2392. OPT_WITHOUT_ARG("--show-processors",
  2393. opt_set_bool, &opt_show_procs,
  2394. "Show per processor statistics in summary"),
  2395. OPT_WITHOUT_ARG("--show-procs",
  2396. opt_set_bool, &opt_show_procs,
  2397. opt_hidden),
  2398. OPT_WITH_ARG("--skip-security-checks",
  2399. set_int_0_to_9999, NULL, &opt_skip_checks,
  2400. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  2401. OPT_WITH_ARG("--socks-proxy",
  2402. opt_set_charp, NULL, &opt_socks_proxy,
  2403. "Set socks proxy (host:port)"),
  2404. #ifdef USE_LIBEVENT
  2405. OPT_WITH_ARG("--stratum-port",
  2406. opt_set_intval, opt_show_intval, &stratumsrv_port,
  2407. "Port number to listen on for stratum miners (-1 means disabled)"),
  2408. #endif
  2409. OPT_WITHOUT_ARG("--submit-stale",
  2410. opt_set_bool, &opt_submit_stale,
  2411. opt_hidden),
  2412. OPT_WITH_ARG("--submit-threads",
  2413. opt_set_intval, opt_show_intval, &opt_submit_threads,
  2414. "Minimum number of concurrent share submissions (default: 64)"),
  2415. #ifdef HAVE_SYSLOG_H
  2416. OPT_WITHOUT_ARG("--syslog",
  2417. opt_set_bool, &use_syslog,
  2418. "Use system log for output messages (default: standard error)"),
  2419. #endif
  2420. OPT_WITH_ARG("--temp-cutoff",
  2421. set_temp_cutoff, NULL, &opt_cutofftemp,
  2422. opt_hidden),
  2423. OPT_WITH_ARG("--temp-hysteresis",
  2424. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2425. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2426. #ifdef HAVE_ADL
  2427. OPT_WITH_ARG("--temp-overheat",
  2428. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2429. opt_hidden),
  2430. #endif
  2431. OPT_WITH_ARG("--temp-target",
  2432. set_temp_target, NULL, NULL,
  2433. opt_hidden),
  2434. OPT_WITHOUT_ARG("--text-only|-T",
  2435. opt_set_invbool, &use_curses,
  2436. #ifdef HAVE_CURSES
  2437. "Disable ncurses formatted screen output"
  2438. #else
  2439. opt_hidden
  2440. #endif
  2441. ),
  2442. #if defined(USE_SCRYPT) && defined(USE_OPENCL)
  2443. OPT_WITH_ARG("--thread-concurrency",
  2444. set_thread_concurrency, NULL, NULL,
  2445. opt_hidden),
  2446. #endif
  2447. #ifdef USE_UNICODE
  2448. OPT_WITHOUT_ARG("--unicode",
  2449. opt_set_bool, &use_unicode,
  2450. "Use Unicode characters in TUI"),
  2451. #endif
  2452. OPT_WITH_ARG("--url|-o",
  2453. set_url, NULL, NULL,
  2454. "URL for bitcoin JSON-RPC server"),
  2455. OPT_WITH_ARG("--user|-u",
  2456. set_user, NULL, NULL,
  2457. "Username for bitcoin JSON-RPC server"),
  2458. #ifdef USE_OPENCL
  2459. OPT_WITH_ARG("--vectors|-v",
  2460. set_vector, NULL, NULL,
  2461. opt_hidden),
  2462. #endif
  2463. OPT_WITHOUT_ARG("--verbose",
  2464. opt_set_bool, &opt_log_output,
  2465. "Log verbose output to stderr as well as status output"),
  2466. OPT_WITHOUT_ARG("--verbose-work-updates|--verbose-work-update",
  2467. opt_set_invbool, &opt_quiet_work_updates,
  2468. opt_hidden),
  2469. OPT_WITHOUT_ARG("--weighed-stats",
  2470. opt_set_bool, &opt_weighed_stats,
  2471. "Display statistics weighed to difficulty 1"),
  2472. #ifdef USE_OPENCL
  2473. OPT_WITH_ARG("--worksize|-w",
  2474. set_worksize, NULL, NULL,
  2475. opt_hidden),
  2476. #endif
  2477. OPT_WITHOUT_ARG("--unittest",
  2478. opt_set_bool, &opt_unittest, opt_hidden),
  2479. OPT_WITH_ARG("--coinbase-check-addr",
  2480. set_cbcaddr, NULL, NULL,
  2481. "A list of address to check against in coinbase payout list received from the previous-defined pool, separated by ','"),
  2482. OPT_WITH_ARG("--cbcheck-addr|--cbc-addr|--cbcaddr",
  2483. set_cbcaddr, NULL, NULL,
  2484. opt_hidden),
  2485. OPT_WITH_ARG("--coinbase-check-total",
  2486. set_cbctotal, NULL, NULL,
  2487. "The least total payout amount expected in coinbase received from the previous-defined pool"),
  2488. OPT_WITH_ARG("--cbcheck-total|--cbc-total|--cbctotal",
  2489. set_cbctotal, NULL, NULL,
  2490. opt_hidden),
  2491. OPT_WITH_ARG("--coinbase-check-percent",
  2492. set_cbcperc, NULL, NULL,
  2493. "The least benefit percentage expected for the sum of addr(s) listed in --cbaddr argument for previous-defined pool"),
  2494. OPT_WITH_ARG("--cbcheck-percent|--cbc-percent|--cbcpercent|--cbcperc",
  2495. set_cbcperc, NULL, NULL,
  2496. opt_hidden),
  2497. OPT_WITHOUT_ARG("--worktime",
  2498. opt_set_bool, &opt_worktime,
  2499. "Display extra work time debug information"),
  2500. OPT_WITH_ARG("--pools",
  2501. opt_set_bool, NULL, NULL, opt_hidden),
  2502. OPT_ENDTABLE
  2503. };
  2504. static char *load_config(const char *arg, void __maybe_unused *unused);
  2505. static char *parse_config(json_t *config, bool fileconf, int * const fileconf_load_p)
  2506. {
  2507. static char err_buf[200];
  2508. struct opt_table *opt;
  2509. json_t *val;
  2510. if (fileconf && !*fileconf_load_p)
  2511. *fileconf_load_p = 1;
  2512. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2513. char *p, *name, *sp;
  2514. /* We don't handle subtables. */
  2515. assert(!(opt->type & OPT_SUBTABLE));
  2516. if (!opt->names)
  2517. continue;
  2518. /* Pull apart the option name(s). */
  2519. name = strdup(opt->names);
  2520. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2521. char *err = "Invalid value";
  2522. /* Ignore short options. */
  2523. if (p[1] != '-')
  2524. continue;
  2525. val = json_object_get(config, p+2);
  2526. if (!val)
  2527. continue;
  2528. if (opt->type & OPT_HASARG) {
  2529. if (json_is_string(val)) {
  2530. err = opt->cb_arg(json_string_value(val),
  2531. opt->u.arg);
  2532. } else if (json_is_number(val)) {
  2533. char buf[256], *p, *q;
  2534. snprintf(buf, 256, "%f", json_number_value(val));
  2535. if ( (p = strchr(buf, '.')) ) {
  2536. // Trim /\.0*$/ to work properly with integer-only arguments
  2537. q = p;
  2538. while (*(++q) == '0') {}
  2539. if (*q == '\0')
  2540. *p = '\0';
  2541. }
  2542. err = opt->cb_arg(buf, opt->u.arg);
  2543. } else if (json_is_array(val)) {
  2544. int n, size = json_array_size(val);
  2545. err = NULL;
  2546. for (n = 0; n < size && !err; n++) {
  2547. if (json_is_string(json_array_get(val, n)))
  2548. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2549. else if (json_is_object(json_array_get(val, n)))
  2550. err = parse_config(json_array_get(val, n), false, fileconf_load_p);
  2551. }
  2552. }
  2553. } else if (opt->type & OPT_NOARG) {
  2554. if (json_is_true(val))
  2555. err = opt->cb(opt->u.arg);
  2556. else if (json_is_boolean(val)) {
  2557. if (opt->cb == (void*)opt_set_bool)
  2558. err = opt_set_invbool(opt->u.arg);
  2559. else if (opt->cb == (void*)opt_set_invbool)
  2560. err = opt_set_bool(opt->u.arg);
  2561. }
  2562. }
  2563. if (err) {
  2564. /* Allow invalid values to be in configuration
  2565. * file, just skipping over them provided the
  2566. * JSON is still valid after that. */
  2567. if (fileconf) {
  2568. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2569. *fileconf_load_p = -1;
  2570. } else {
  2571. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2572. p, err);
  2573. free(name);
  2574. return err_buf;
  2575. }
  2576. }
  2577. }
  2578. free(name);
  2579. }
  2580. val = json_object_get(config, JSON_INCLUDE_CONF);
  2581. if (val && json_is_string(val))
  2582. return load_config(json_string_value(val), NULL);
  2583. return NULL;
  2584. }
  2585. struct bfg_loaded_configfile *bfg_loaded_configfiles;
  2586. char conf_web1[] = "http://";
  2587. char conf_web2[] = "https://";
  2588. static char *load_web_config(const char *arg)
  2589. {
  2590. json_t *val;
  2591. CURL *curl;
  2592. struct bfg_loaded_configfile *cfginfo;
  2593. curl = curl_easy_init();
  2594. if (unlikely(!curl))
  2595. quithere(1, "CURL initialisation failed");
  2596. val = json_web_config(curl, arg);
  2597. curl_easy_cleanup(curl);
  2598. if (!val || !json_is_object(val))
  2599. return JSON_WEB_ERROR;
  2600. cfginfo = malloc(sizeof(*cfginfo));
  2601. *cfginfo = (struct bfg_loaded_configfile){
  2602. .filename = strdup(arg),
  2603. };
  2604. LL_APPEND(bfg_loaded_configfiles, cfginfo);
  2605. config_loaded = true;
  2606. return parse_config(val, true, &cfginfo->fileconf_load);
  2607. }
  2608. static char *load_config(const char *arg, void __maybe_unused *unused)
  2609. {
  2610. json_error_t err;
  2611. json_t *config;
  2612. char *json_error;
  2613. size_t siz;
  2614. struct bfg_loaded_configfile *cfginfo;
  2615. if (strncasecmp(arg, conf_web1, sizeof(conf_web1)-1) == 0 ||
  2616. strncasecmp(arg, conf_web2, sizeof(conf_web2)-1) == 0)
  2617. return load_web_config(arg);
  2618. cfginfo = malloc(sizeof(*cfginfo));
  2619. *cfginfo = (struct bfg_loaded_configfile){
  2620. .filename = strdup(arg),
  2621. };
  2622. LL_APPEND(bfg_loaded_configfiles, cfginfo);
  2623. if (++include_count > JSON_MAX_DEPTH)
  2624. return JSON_MAX_DEPTH_ERR;
  2625. #if JANSSON_MAJOR_VERSION > 1
  2626. config = json_load_file(arg, 0, &err);
  2627. #else
  2628. config = json_load_file(arg, &err);
  2629. #endif
  2630. if (!json_is_object(config)) {
  2631. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2632. json_error = malloc(siz);
  2633. if (!json_error)
  2634. quit(1, "Malloc failure in json error");
  2635. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2636. return json_error;
  2637. }
  2638. config_loaded = true;
  2639. /* Parse the config now, so we can override it. That can keep pointers
  2640. * so don't free config object. */
  2641. return parse_config(config, true, &cfginfo->fileconf_load);
  2642. }
  2643. static
  2644. bool _load_default_configs(const char * const filepath, void * __maybe_unused userp)
  2645. {
  2646. bool * const found_defcfg_p = userp;
  2647. *found_defcfg_p = true;
  2648. load_config(filepath, NULL);
  2649. // Regardless of status of loading the config file, we should continue loading other defaults
  2650. return false;
  2651. }
  2652. static void load_default_config(void)
  2653. {
  2654. bool found_defcfg = false;
  2655. appdata_file_call("BFGMiner", def_conf, _load_default_configs, &found_defcfg);
  2656. if (!found_defcfg)
  2657. {
  2658. // No BFGMiner config, try Cgminer's...
  2659. appdata_file_call("cgminer", "cgminer.conf", _load_default_configs, &found_defcfg);
  2660. }
  2661. }
  2662. extern const char *opt_argv0;
  2663. static
  2664. void bfg_versioninfo(void)
  2665. {
  2666. puts(packagename);
  2667. printf(" Lowlevel:%s\n", BFG_LOWLLIST);
  2668. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2669. printf(" Algorithms:%s\n", BFG_ALGOLIST);
  2670. printf(" Options:%s\n", BFG_OPTLIST);
  2671. }
  2672. static char *opt_verusage_and_exit(const char *extra)
  2673. {
  2674. bfg_versioninfo();
  2675. printf("%s", opt_usage(opt_argv0, extra));
  2676. fflush(stdout);
  2677. exit(0);
  2678. }
  2679. static
  2680. const char *my_opt_version_and_exit(void)
  2681. {
  2682. bfg_versioninfo();
  2683. fflush(stdout);
  2684. exit(0);
  2685. }
  2686. /* These options are parsed before anything else */
  2687. static struct opt_table opt_early_table[] = {
  2688. // Default config is loaded in command line order, like a regular config
  2689. OPT_EARLY_WITH_ARG("--config|-c|--default-config",
  2690. set_bool_ignore_arg, NULL, &config_loaded,
  2691. opt_hidden),
  2692. OPT_EARLY_WITHOUT_ARG("--no-config|--no-default-config",
  2693. opt_set_bool, &config_loaded,
  2694. "Inhibit loading default config file"),
  2695. OPT_ENDTABLE
  2696. };
  2697. /* These options are available from commandline only */
  2698. static struct opt_table opt_cmdline_table[] = {
  2699. OPT_WITH_ARG("--config|-c",
  2700. load_config, NULL, NULL,
  2701. "Load a JSON-format configuration file\n"
  2702. "See example.conf for an example configuration."),
  2703. OPT_EARLY_WITHOUT_ARG("--no-config",
  2704. opt_set_bool, &config_loaded,
  2705. opt_hidden),
  2706. OPT_EARLY_WITHOUT_ARG("--no-default-config",
  2707. opt_set_bool, &config_loaded,
  2708. "Inhibit loading default config file"),
  2709. OPT_WITHOUT_ARG("--default-config",
  2710. load_default_config, NULL,
  2711. "Always load the default config file"),
  2712. OPT_WITHOUT_ARG("--help|-h",
  2713. opt_verusage_and_exit, NULL,
  2714. "Print this message"),
  2715. #ifdef USE_OPENCL
  2716. OPT_WITHOUT_ARG("--ndevs|-n",
  2717. print_ndevs_and_exit, &nDevs,
  2718. opt_hidden),
  2719. #endif
  2720. OPT_WITHOUT_ARG("--version|-V",
  2721. my_opt_version_and_exit, NULL,
  2722. "Display version and exit"),
  2723. OPT_ENDTABLE
  2724. };
  2725. static bool jobj_binary(const json_t *obj, const char *key,
  2726. void *buf, size_t buflen, bool required)
  2727. {
  2728. const char *hexstr;
  2729. json_t *tmp;
  2730. tmp = json_object_get(obj, key);
  2731. if (unlikely(!tmp)) {
  2732. if (unlikely(required))
  2733. applog(LOG_ERR, "JSON key '%s' not found", key);
  2734. return false;
  2735. }
  2736. hexstr = json_string_value(tmp);
  2737. if (unlikely(!hexstr)) {
  2738. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2739. return false;
  2740. }
  2741. if (!hex2bin(buf, hexstr, buflen))
  2742. return false;
  2743. return true;
  2744. }
  2745. static void calc_midstate(struct work *work)
  2746. {
  2747. union {
  2748. unsigned char c[64];
  2749. uint32_t i[16];
  2750. } data;
  2751. swap32yes(&data.i[0], work->data, 16);
  2752. sha256_ctx ctx;
  2753. sha256_init(&ctx);
  2754. sha256_update(&ctx, data.c, 64);
  2755. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2756. swap32tole(work->midstate, work->midstate, 8);
  2757. }
  2758. static
  2759. struct bfg_tmpl_ref *tmpl_makeref(blktemplate_t * const tmpl)
  2760. {
  2761. struct bfg_tmpl_ref * const tr = malloc(sizeof(*tr));
  2762. *tr = (struct bfg_tmpl_ref){
  2763. .tmpl = tmpl,
  2764. .refcount = 1,
  2765. };
  2766. mutex_init(&tr->mutex);
  2767. return tr;
  2768. }
  2769. static
  2770. void tmpl_incref(struct bfg_tmpl_ref * const tr)
  2771. {
  2772. mutex_lock(&tr->mutex);
  2773. ++tr->refcount;
  2774. mutex_unlock(&tr->mutex);
  2775. }
  2776. void tmpl_decref(struct bfg_tmpl_ref * const tr)
  2777. {
  2778. mutex_lock(&tr->mutex);
  2779. bool free_tmpl = !--tr->refcount;
  2780. mutex_unlock(&tr->mutex);
  2781. if (free_tmpl)
  2782. {
  2783. blktmpl_free(tr->tmpl);
  2784. mutex_destroy(&tr->mutex);
  2785. free(tr);
  2786. }
  2787. }
  2788. static struct work *make_work(void)
  2789. {
  2790. struct work *work = calloc(1, sizeof(struct work));
  2791. if (unlikely(!work))
  2792. quit(1, "Failed to calloc work in make_work");
  2793. cg_wlock(&control_lock);
  2794. work->id = total_work++;
  2795. cg_wunlock(&control_lock);
  2796. return work;
  2797. }
  2798. /* This is the central place all work that is about to be retired should be
  2799. * cleaned to remove any dynamically allocated arrays within the struct */
  2800. void clean_work(struct work *work)
  2801. {
  2802. free(work->job_id);
  2803. bytes_free(&work->nonce2);
  2804. free(work->nonce1);
  2805. if (work->device_data_free_func)
  2806. work->device_data_free_func(work);
  2807. if (work->tr)
  2808. tmpl_decref(work->tr);
  2809. memset(work, 0, sizeof(struct work));
  2810. }
  2811. /* All dynamically allocated work structs should be freed here to not leak any
  2812. * ram from arrays allocated within the work struct */
  2813. void free_work(struct work *work)
  2814. {
  2815. clean_work(work);
  2816. free(work);
  2817. }
  2818. const char *bfg_workpadding_bin = "\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";
  2819. #define workpadding_bin bfg_workpadding_bin
  2820. static const size_t block_info_str_sz = 3 /* ... */ + 16 /* block hash segment */ + 1;
  2821. static
  2822. void block_info_str(char * const out, const struct block_info * const blkinfo)
  2823. {
  2824. unsigned char hash_swap[32];
  2825. swap256(hash_swap, blkinfo->prevblkhash);
  2826. swap32tole(hash_swap, hash_swap, 32 / 4);
  2827. memset(out, '.', 3);
  2828. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2829. if (blkinfo->height > 0 && blkinfo->height < 1000000)
  2830. {
  2831. bin2hex(&out[3], &hash_swap[0x1c], 4);
  2832. snprintf(&out[11], block_info_str_sz-11, " #%6u", blkinfo->height);
  2833. }
  2834. else
  2835. bin2hex(&out[3], &hash_swap[0x18], 8);
  2836. }
  2837. #ifdef HAVE_CURSES
  2838. static void update_block_display(bool);
  2839. #endif
  2840. // Must only be called with ch_lock held!
  2841. static
  2842. void __update_block_title(struct mining_goal_info * const goal)
  2843. {
  2844. struct blockchain_info * const blkchain = goal->blkchain;
  2845. if (!goal->current_goal_detail)
  2846. goal->current_goal_detail = malloc(block_info_str_sz);
  2847. block_info_str(goal->current_goal_detail, blkchain->currentblk);
  2848. #ifdef HAVE_CURSES
  2849. update_block_display(false);
  2850. #endif
  2851. }
  2852. static struct block_info *block_exists(const struct blockchain_info *, const void *);
  2853. static
  2854. void have_block_height(struct mining_goal_info * const goal, const void * const prevblkhash, uint32_t blkheight)
  2855. {
  2856. struct blockchain_info * const blkchain = goal->blkchain;
  2857. struct block_info * const blkinfo = block_exists(blkchain, prevblkhash);
  2858. if ((!blkinfo) || blkinfo->height)
  2859. return;
  2860. uint32_t block_id = ((uint32_t*)prevblkhash)[0];
  2861. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2862. cg_wlock(&ch_lock);
  2863. blkinfo->height = blkheight;
  2864. if (blkinfo == blkchain->currentblk)
  2865. {
  2866. blkchain->currentblk_subsidy = 5000000000LL >> (blkheight / 210000);
  2867. __update_block_title(goal);
  2868. }
  2869. cg_wunlock(&ch_lock);
  2870. }
  2871. static
  2872. void pool_set_opaque(struct pool *pool, bool opaque)
  2873. {
  2874. if (pool->swork.opaque == opaque)
  2875. return;
  2876. pool->swork.opaque = opaque;
  2877. if (opaque)
  2878. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2879. pool->pool_no);
  2880. else
  2881. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2882. pool->pool_no);
  2883. }
  2884. bool pool_may_redirect_to(struct pool * const pool, const char * const uri)
  2885. {
  2886. if (uri_get_param_bool(pool->rpc_url, "redirect", false))
  2887. return true;
  2888. return match_domains(pool->rpc_url, strlen(pool->rpc_url), uri, strlen(uri));
  2889. }
  2890. void pool_check_coinbase(struct pool * const pool, const uint8_t * const cbtxn, const size_t cbtxnsz)
  2891. {
  2892. if (uri_get_param_bool(pool->rpc_url, "skipcbcheck", false))
  2893. {}
  2894. else
  2895. if (!check_coinbase(cbtxn, cbtxnsz, &pool->cb_param))
  2896. {
  2897. if (pool->enabled == POOL_ENABLED)
  2898. {
  2899. applog(LOG_ERR, "Pool %d misbehaving (%s), disabling!", pool->pool_no, "coinbase check");
  2900. disable_pool(pool, POOL_MISBEHAVING);
  2901. }
  2902. }
  2903. else
  2904. if (pool->enabled == POOL_MISBEHAVING)
  2905. {
  2906. applog(LOG_NOTICE, "Pool %d no longer misbehaving, re-enabling!", pool->pool_no);
  2907. enable_pool(pool);
  2908. }
  2909. }
  2910. void set_simple_ntime_roll_limit(struct ntime_roll_limits * const nrl, const uint32_t ntime_base, const int ntime_roll, const struct timeval * const tvp_ref)
  2911. {
  2912. const int offsets = max(ntime_roll, 60);
  2913. *nrl = (struct ntime_roll_limits){
  2914. .min = ntime_base,
  2915. .max = ntime_base + ntime_roll,
  2916. .tv_ref = *tvp_ref,
  2917. .minoff = -offsets,
  2918. .maxoff = offsets,
  2919. };
  2920. }
  2921. void work_set_simple_ntime_roll_limit(struct work * const work, const int ntime_roll, const struct timeval * const tvp_ref)
  2922. {
  2923. set_simple_ntime_roll_limit(&work->ntime_roll_limits, upk_u32be(work->data, 0x44), ntime_roll, tvp_ref);
  2924. }
  2925. int work_ntime_range(struct work * const work, const struct timeval * const tvp_earliest, const struct timeval * const tvp_latest, const int desired_roll)
  2926. {
  2927. const struct ntime_roll_limits * const nrl = &work->ntime_roll_limits;
  2928. const uint32_t ref_ntime = work_get_ntime(work);
  2929. const int earliest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_earliest);
  2930. const int latest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_latest);
  2931. // minimum ntime is the latest possible result (add a second to spare) adjusted for minimum offset (or fixed minimum ntime)
  2932. uint32_t min_ntime = max(nrl->min, ref_ntime + latest_elapsed+1 + nrl->minoff);
  2933. // maximum ntime is the earliest possible result adjusted for maximum offset (or fixed maximum ntime)
  2934. uint32_t max_ntime = min(nrl->max, ref_ntime + earliest_elapsed + nrl->maxoff);
  2935. if (max_ntime < min_ntime)
  2936. return -1;
  2937. if (max_ntime - min_ntime > desired_roll)
  2938. {
  2939. // Adjust min_ntime upward for accuracy, when possible
  2940. const int mid_elapsed = ((latest_elapsed - earliest_elapsed) / 2) + earliest_elapsed;
  2941. uint32_t ideal_ntime = ref_ntime + mid_elapsed;
  2942. if (ideal_ntime > min_ntime)
  2943. min_ntime = min(ideal_ntime, max_ntime - desired_roll);
  2944. }
  2945. work_set_ntime(work, min_ntime);
  2946. return max_ntime - min_ntime;
  2947. }
  2948. #if BLKMAKER_VERSION > 1
  2949. static
  2950. bool goal_has_at_least_one_getcbaddr(const struct mining_goal_info * const goal)
  2951. {
  2952. for (int i = 0; i < total_pools; ++i)
  2953. {
  2954. struct pool * const pool = pools[i];
  2955. if (uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2956. return true;
  2957. }
  2958. return false;
  2959. }
  2960. static
  2961. void refresh_bitcoind_address(struct mining_goal_info * const goal, const bool fresh)
  2962. {
  2963. struct blockchain_info * const blkchain = goal->blkchain;
  2964. if (!goal_has_at_least_one_getcbaddr(goal))
  2965. return;
  2966. char getcbaddr_req[60];
  2967. CURL *curl = NULL;
  2968. json_t *json, *j2;
  2969. const char *s, *s2;
  2970. bytes_t newscript = BYTES_INIT;
  2971. snprintf(getcbaddr_req, sizeof(getcbaddr_req), "{\"method\":\"get%saddress\",\"id\":0,\"params\":[\"BFGMiner\"]}", fresh ? "new" : "account");
  2972. for (int i = 0; i < total_pools; ++i)
  2973. {
  2974. struct pool * const pool = pools[i];
  2975. if (!uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2976. continue;
  2977. if (pool->goal != goal)
  2978. continue;
  2979. applog(LOG_DEBUG, "Refreshing coinbase address from pool %d", pool->pool_no);
  2980. if (!curl)
  2981. {
  2982. curl = curl_easy_init();
  2983. if (unlikely(!curl))
  2984. {
  2985. applogfail(LOG_ERR, "curl_easy_init");
  2986. break;
  2987. }
  2988. }
  2989. json = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, getcbaddr_req, false, false, NULL, pool, true);
  2990. if (unlikely((!json) || !json_is_null( (j2 = json_object_get(json, "error")) )))
  2991. {
  2992. const char *estrc;
  2993. char *estr = NULL;
  2994. if (!(json && j2))
  2995. estrc = NULL;
  2996. else
  2997. {
  2998. estrc = json_string_value(j2);
  2999. if (!estrc)
  3000. estrc = estr = json_dumps_ANY(j2, JSON_ENSURE_ASCII | JSON_SORT_KEYS);
  3001. }
  3002. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, estrc);
  3003. free(estr);
  3004. json_decref(json);
  3005. continue;
  3006. }
  3007. s = bfg_json_obj_string(json, "result", NULL);
  3008. if (unlikely(!s))
  3009. {
  3010. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, "(return value was not a String)");
  3011. json_decref(json);
  3012. continue;
  3013. }
  3014. s2 = set_b58addr(s, &newscript);
  3015. if (unlikely(s2))
  3016. {
  3017. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 's', pool->pool_no, s2);
  3018. json_decref(json);
  3019. continue;
  3020. }
  3021. if (goal->generation_script)
  3022. {
  3023. if (bytes_eq(&newscript, goal->generation_script))
  3024. {
  3025. applog(LOG_DEBUG, "Pool %d returned coinbase address already in use (%s)", pool->pool_no, s);
  3026. json_decref(json);
  3027. break;
  3028. }
  3029. }
  3030. else
  3031. {
  3032. goal->generation_script = malloc(sizeof(*goal->generation_script));
  3033. bytes_init(goal->generation_script);
  3034. }
  3035. bytes_assimilate(goal->generation_script, &newscript);
  3036. coinbase_script_block_id = blkchain->currentblk->block_id;
  3037. applog(LOG_NOTICE, "Now using coinbase address %s, provided by pool %d", s, pool->pool_no);
  3038. json_decref(json);
  3039. break;
  3040. }
  3041. bytes_free(&newscript);
  3042. if (curl)
  3043. curl_easy_cleanup(curl);
  3044. }
  3045. #endif
  3046. #define GBT_XNONCESZ (sizeof(uint32_t))
  3047. #if BLKMAKER_VERSION > 4
  3048. #define blkmk_append_coinbase_safe(tmpl, append, appendsz) \
  3049. blkmk_append_coinbase_safe2(tmpl, append, appendsz, GBT_XNONCESZ, false)
  3050. #endif
  3051. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  3052. {
  3053. json_t *res_val = json_object_get(val, "result");
  3054. json_t *tmp_val;
  3055. bool ret = false;
  3056. struct timeval tv_now;
  3057. if (unlikely(detect_algo == 1)) {
  3058. json_t *tmp = json_object_get(res_val, "algorithm");
  3059. const char *v = tmp ? json_string_value(tmp) : "";
  3060. if (strncasecmp(v, "scrypt", 6))
  3061. detect_algo = 2;
  3062. }
  3063. timer_set_now(&tv_now);
  3064. if (work->tr)
  3065. {
  3066. blktemplate_t * const tmpl = work->tr->tmpl;
  3067. const char *err = blktmpl_add_jansson(tmpl, res_val, tv_now.tv_sec);
  3068. if (err) {
  3069. applog(LOG_ERR, "blktmpl error: %s", err);
  3070. return false;
  3071. }
  3072. work->rolltime = blkmk_time_left(tmpl, tv_now.tv_sec);
  3073. #if BLKMAKER_VERSION > 1
  3074. struct mining_goal_info * const goal = pool->goal;
  3075. const uint32_t tmpl_block_id = ((uint32_t*)tmpl->prevblk)[0];
  3076. if ((!tmpl->cbtxn) && coinbase_script_block_id != tmpl_block_id)
  3077. refresh_bitcoind_address(goal, false);
  3078. if (goal->generation_script)
  3079. {
  3080. bool newcb;
  3081. #if BLKMAKER_VERSION > 2
  3082. blkmk_init_generation2(tmpl, bytes_buf(goal->generation_script), bytes_len(goal->generation_script), &newcb);
  3083. #else
  3084. newcb = !tmpl->cbtxn;
  3085. blkmk_init_generation(tmpl, bytes_buf(goal->generation_script), bytes_len(goal->generation_script));
  3086. #endif
  3087. if (newcb)
  3088. {
  3089. ssize_t ae = blkmk_append_coinbase_safe(tmpl, &template_nonce, sizeof(template_nonce));
  3090. if (ae < (ssize_t)sizeof(template_nonce))
  3091. 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);
  3092. ++template_nonce;
  3093. }
  3094. }
  3095. #endif
  3096. #if BLKMAKER_VERSION > 0
  3097. {
  3098. ssize_t ae = blkmk_append_coinbase_safe(tmpl, opt_coinbase_sig, 101);
  3099. static bool appenderr = false;
  3100. if (ae <= 0) {
  3101. if (opt_coinbase_sig) {
  3102. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  3103. appenderr = true;
  3104. }
  3105. } else if (ae >= 3 || opt_coinbase_sig) {
  3106. const char *cbappend = opt_coinbase_sig;
  3107. const char * const full = bfgminer_name_space_ver;
  3108. char *need_free = NULL;
  3109. if (!cbappend) {
  3110. if ((size_t)ae >= sizeof(full) - 1)
  3111. cbappend = full;
  3112. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  3113. {
  3114. const char *pos = strchr(full, '-');
  3115. size_t sz = (pos - full);
  3116. if (pos && ae > sz)
  3117. {
  3118. cbappend = need_free = malloc(sz + 1);
  3119. memcpy(need_free, full, sz);
  3120. need_free[sz] = '\0';
  3121. }
  3122. else
  3123. cbappend = PACKAGE;
  3124. }
  3125. else
  3126. cbappend = "BFG";
  3127. }
  3128. size_t cbappendsz = strlen(cbappend);
  3129. static bool truncatewarning = false;
  3130. if (cbappendsz <= (size_t)ae) {
  3131. if (cbappendsz < (size_t)ae)
  3132. // If we have space, include the trailing \0
  3133. ++cbappendsz;
  3134. ae = cbappendsz;
  3135. truncatewarning = false;
  3136. } else {
  3137. char *tmp = malloc(ae + 1);
  3138. memcpy(tmp, opt_coinbase_sig, ae);
  3139. tmp[ae] = '\0';
  3140. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  3141. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  3142. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  3143. free(tmp);
  3144. truncatewarning = true;
  3145. }
  3146. ae = blkmk_append_coinbase_safe(tmpl, cbappend, ae);
  3147. free(need_free);
  3148. if (ae <= 0) {
  3149. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  3150. appenderr = true;
  3151. } else
  3152. appenderr = false;
  3153. }
  3154. }
  3155. #endif
  3156. if (blkmk_get_data(tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  3157. return false;
  3158. swap32yes(work->data, work->data, 80 / 4);
  3159. memcpy(&work->data[80], workpadding_bin, 48);
  3160. work->ntime_roll_limits = (struct ntime_roll_limits){
  3161. .min = tmpl->mintime,
  3162. .max = tmpl->maxtime,
  3163. .tv_ref = tv_now,
  3164. .minoff = tmpl->mintimeoff,
  3165. .maxoff = tmpl->maxtimeoff,
  3166. };
  3167. const struct blktmpl_longpoll_req *lp;
  3168. if ((lp = blktmpl_get_longpoll(tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  3169. free(pool->lp_id);
  3170. pool->lp_id = strdup(lp->id);
  3171. #if 0 /* This just doesn't work :( */
  3172. curl_socket_t sock = pool->lp_socket;
  3173. if (sock != CURL_SOCKET_BAD) {
  3174. pool->lp_socket = CURL_SOCKET_BAD;
  3175. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  3176. shutdown(sock, SHUT_RDWR);
  3177. }
  3178. #endif
  3179. }
  3180. }
  3181. else
  3182. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  3183. applog(LOG_ERR, "JSON inval data");
  3184. return false;
  3185. }
  3186. else
  3187. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  3188. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  3189. // Calculate it ourselves
  3190. applog(LOG_DEBUG, "Calculating midstate locally");
  3191. calc_midstate(work);
  3192. }
  3193. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  3194. applog(LOG_ERR, "JSON inval target");
  3195. return false;
  3196. }
  3197. if (work->tr)
  3198. {
  3199. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  3200. {
  3201. int p = (sizeof(work->target) - 1) - i;
  3202. unsigned char c = work->target[i];
  3203. work->target[i] = work->target[p];
  3204. work->target[p] = c;
  3205. }
  3206. }
  3207. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  3208. struct mining_goal_info * const goal = pool->goal;
  3209. uint32_t blkheight = json_number_value(tmp_val);
  3210. const void * const prevblkhash = &work->data[4];
  3211. have_block_height(goal, prevblkhash, blkheight);
  3212. }
  3213. memset(work->hash, 0, sizeof(work->hash));
  3214. work->tv_staged = tv_now;
  3215. #if BLKMAKER_VERSION > 4
  3216. if (work->tr)
  3217. {
  3218. blktemplate_t * const tmpl = work->tr->tmpl;
  3219. uint8_t buf[80];
  3220. int16_t expire;
  3221. uint8_t *cbtxn;
  3222. size_t cbtxnsz;
  3223. size_t cbextranonceoffset;
  3224. int branchcount;
  3225. libblkmaker_hash_t *branches;
  3226. if (blkmk_get_mdata(tmpl, buf, sizeof(buf), tv_now.tv_sec, &expire, &cbtxn, &cbtxnsz, &cbextranonceoffset, &branchcount, &branches, GBT_XNONCESZ, false))
  3227. {
  3228. struct stratum_work * const swork = &pool->swork;
  3229. const size_t branchdatasz = branchcount * 0x20;
  3230. pool_check_coinbase(pool, cbtxn, cbtxnsz);
  3231. cg_wlock(&pool->data_lock);
  3232. swork->tr = work->tr;
  3233. bytes_assimilate_raw(&swork->coinbase, cbtxn, cbtxnsz, cbtxnsz);
  3234. swork->nonce2_offset = cbextranonceoffset;
  3235. bytes_assimilate_raw(&swork->merkle_bin, branches, branchdatasz, branchdatasz);
  3236. swork->merkles = branchcount;
  3237. memcpy(swork->header1, &buf[0], 36);
  3238. swork->ntime = le32toh(*(uint32_t *)(&buf[68]));
  3239. swork->tv_received = tv_now;
  3240. memcpy(swork->diffbits, &buf[72], 4);
  3241. memcpy(swork->target, work->target, sizeof(swork->target));
  3242. free(swork->job_id);
  3243. swork->job_id = NULL;
  3244. swork->clean = true;
  3245. swork->work_restart_id = pool->work_restart_id;
  3246. // FIXME: Do something with expire
  3247. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  3248. pool->nonce2 = 0;
  3249. cg_wunlock(&pool->data_lock);
  3250. }
  3251. else
  3252. applog(LOG_DEBUG, "blkmk_get_mdata failed for pool %u", pool->pool_no);
  3253. }
  3254. #endif // BLKMAKER_VERSION > 4
  3255. pool_set_opaque(pool, !work->tr);
  3256. ret = true;
  3257. return ret;
  3258. }
  3259. /* Returns whether the pool supports local work generation or not. */
  3260. static bool pool_localgen(struct pool *pool)
  3261. {
  3262. return (pool->last_work_copy || pool->has_stratum);
  3263. }
  3264. int dev_from_id(int thr_id)
  3265. {
  3266. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  3267. return cgpu->device_id;
  3268. }
  3269. /* Create an exponentially decaying average over the opt_log_interval */
  3270. void decay_time(double *f, double fadd, double fsecs)
  3271. {
  3272. double ftotal, fprop;
  3273. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  3274. ftotal = 1.0 + fprop;
  3275. *f += (fadd * fprop);
  3276. *f /= ftotal;
  3277. }
  3278. static
  3279. int __total_staged(const bool include_spares)
  3280. {
  3281. int tot = HASH_COUNT(staged_work);
  3282. if (!include_spares)
  3283. tot -= staged_spare;
  3284. return tot;
  3285. }
  3286. static int total_staged(const bool include_spares)
  3287. {
  3288. int ret;
  3289. mutex_lock(stgd_lock);
  3290. ret = __total_staged(include_spares);
  3291. mutex_unlock(stgd_lock);
  3292. return ret;
  3293. }
  3294. #ifdef HAVE_CURSES
  3295. WINDOW *mainwin, *statuswin, *logwin;
  3296. #endif
  3297. double total_secs = 1.0;
  3298. #ifdef HAVE_CURSES
  3299. static char statusline[256];
  3300. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  3301. static int statusy;
  3302. static int devsummaryYOffset;
  3303. static int total_lines;
  3304. #endif
  3305. #ifdef USE_OPENCL
  3306. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  3307. #endif
  3308. struct cgpu_info *cpus;
  3309. bool _bfg_console_cancel_disabled;
  3310. int _bfg_console_prev_cancelstate;
  3311. #ifdef HAVE_CURSES
  3312. #define lock_curses() bfg_console_lock()
  3313. #define unlock_curses() bfg_console_unlock()
  3314. static bool curses_active_locked(void)
  3315. {
  3316. bool ret;
  3317. lock_curses();
  3318. ret = curses_active;
  3319. if (!ret)
  3320. unlock_curses();
  3321. return ret;
  3322. }
  3323. // Cancellable getch
  3324. int my_cancellable_getch(void)
  3325. {
  3326. // This only works because the macro only hits direct getch() calls
  3327. typedef int (*real_getch_t)(void);
  3328. const real_getch_t real_getch = __real_getch;
  3329. int type, rv;
  3330. bool sct;
  3331. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  3332. rv = real_getch();
  3333. if (sct)
  3334. pthread_setcanceltype(type, &type);
  3335. return rv;
  3336. }
  3337. #ifdef PDCURSES
  3338. static
  3339. int bfg_wresize(WINDOW *win, int lines, int columns)
  3340. {
  3341. int rv = wresize(win, lines, columns);
  3342. int x, y;
  3343. getyx(win, y, x);
  3344. if (unlikely(y >= lines || x >= columns))
  3345. {
  3346. if (y >= lines)
  3347. y = lines - 1;
  3348. if (x >= columns)
  3349. x = columns - 1;
  3350. wmove(win, y, x);
  3351. }
  3352. return rv;
  3353. }
  3354. #else
  3355. # define bfg_wresize wresize
  3356. #endif
  3357. #endif
  3358. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  3359. {
  3360. va_list ap;
  3361. size_t presz = strlen(buf);
  3362. va_start(ap, fmt);
  3363. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  3364. va_end(ap);
  3365. }
  3366. double stats_elapsed(struct cgminer_stats *stats)
  3367. {
  3368. struct timeval now;
  3369. double elapsed;
  3370. if (stats->start_tv.tv_sec == 0)
  3371. elapsed = total_secs;
  3372. else {
  3373. cgtime(&now);
  3374. elapsed = tdiff(&now, &stats->start_tv);
  3375. }
  3376. if (elapsed < 1.0)
  3377. elapsed = 1.0;
  3378. return elapsed;
  3379. }
  3380. bool drv_ready(struct cgpu_info *cgpu)
  3381. {
  3382. switch (cgpu->status) {
  3383. case LIFE_INIT:
  3384. case LIFE_DEAD2:
  3385. return false;
  3386. default:
  3387. return true;
  3388. }
  3389. }
  3390. double cgpu_utility(struct cgpu_info *cgpu)
  3391. {
  3392. double dev_runtime = cgpu_runtime(cgpu);
  3393. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  3394. }
  3395. #define suffix_string(val, buf, bufsiz, sigdigits) do{ \
  3396. _Static_assert(sigdigits == 0, "suffix_string only supported with sigdigits==0"); \
  3397. format_unit3(buf, bufsiz, FUP_DIFF, "", H2B_SHORTV, val, -1); \
  3398. }while(0)
  3399. static float
  3400. utility_to_hashrate(double utility)
  3401. {
  3402. return utility * 0x4444444;
  3403. }
  3404. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  3405. static const int _unitbase = 4;
  3406. static
  3407. void pick_unit(float hashrate, unsigned char *unit)
  3408. {
  3409. unsigned char i;
  3410. if (hashrate == 0 || !isfinite(hashrate))
  3411. {
  3412. if (*unit < _unitbase)
  3413. *unit = _unitbase;
  3414. return;
  3415. }
  3416. hashrate *= 1e12;
  3417. for (i = 0; i < *unit; ++i)
  3418. hashrate /= 1e3;
  3419. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  3420. while (hashrate >= 999.95)
  3421. {
  3422. hashrate /= 1e3;
  3423. if (likely(_unitchar[*unit] != '?'))
  3424. ++*unit;
  3425. }
  3426. }
  3427. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  3428. enum h2bs_fmt {
  3429. H2B_NOUNIT, // "xxx.x"
  3430. H2B_SHORT, // "xxx.xMH/s"
  3431. H2B_SPACED, // "xxx.x MH/s"
  3432. H2B_SHORTV, // Like H2B_SHORT, but omit space for base unit
  3433. };
  3434. enum bfu_floatprec {
  3435. FUP_INTEGER,
  3436. FUP_HASHES,
  3437. FUP_BTC,
  3438. FUP_DIFF,
  3439. };
  3440. static
  3441. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  3442. {
  3443. char *s = buf;
  3444. unsigned char prec, i, unit;
  3445. int rv = 0;
  3446. if (unitin == -1)
  3447. {
  3448. unit = 0;
  3449. hashrate_pick_unit(hashrate, &unit);
  3450. }
  3451. else
  3452. unit = unitin;
  3453. hashrate *= 1e12;
  3454. for (i = 0; i < unit; ++i)
  3455. hashrate /= 1000;
  3456. switch (fprec)
  3457. {
  3458. case FUP_HASHES:
  3459. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  3460. if (hashrate >= 99.995 || unit < 6)
  3461. prec = 1;
  3462. else
  3463. prec = 2;
  3464. _SNP("%5.*f", prec, hashrate);
  3465. break;
  3466. case FUP_INTEGER:
  3467. _SNP("%3d", (int)hashrate);
  3468. break;
  3469. case FUP_BTC:
  3470. if (hashrate >= 99.995)
  3471. prec = 0;
  3472. else
  3473. prec = 2;
  3474. _SNP("%5.*f", prec, hashrate);
  3475. break;
  3476. case FUP_DIFF:
  3477. if (unit > _unitbase)
  3478. _SNP("%.3g", hashrate);
  3479. else
  3480. _SNP("%u", (unsigned int)hashrate);
  3481. }
  3482. if (fmt != H2B_NOUNIT)
  3483. {
  3484. char uc[3] = {_unitchar[unit], '\0'};
  3485. switch (fmt) {
  3486. case H2B_SPACED:
  3487. _SNP(" ");
  3488. default:
  3489. break;
  3490. case H2B_SHORTV:
  3491. if (isspace(uc[0]))
  3492. uc[0] = '\0';
  3493. }
  3494. if (uc[0] == '\xb5')
  3495. // Convert to UTF-8
  3496. snprintf(uc, sizeof(uc), "%s", U8_MICRO);
  3497. _SNP("%s%s", uc, measurement);
  3498. }
  3499. return rv;
  3500. }
  3501. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  3502. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  3503. static
  3504. char *_multi_format_unit(char **buflist, size_t *bufszlist, bool floatprec, const char *measurement, enum h2bs_fmt fmt, const char *delim, int count, const float *numbers, bool isarray)
  3505. {
  3506. unsigned char unit = 0;
  3507. bool allzero = true;
  3508. int i;
  3509. size_t delimsz = 0;
  3510. char *buf = buflist[0];
  3511. size_t bufsz = bufszlist[0];
  3512. size_t itemwidth = (floatprec ? 5 : 3);
  3513. if (!isarray)
  3514. delimsz = strlen(delim);
  3515. for (i = 0; i < count; ++i)
  3516. if (numbers[i] != 0)
  3517. {
  3518. pick_unit(numbers[i], &unit);
  3519. allzero = false;
  3520. }
  3521. if (allzero)
  3522. unit = _unitbase;
  3523. --count;
  3524. for (i = 0; i < count; ++i)
  3525. {
  3526. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  3527. if (isarray)
  3528. {
  3529. buf = buflist[i + 1];
  3530. bufsz = bufszlist[i + 1];
  3531. }
  3532. else
  3533. {
  3534. buf += itemwidth;
  3535. bufsz -= itemwidth;
  3536. if (delimsz > bufsz)
  3537. delimsz = bufsz;
  3538. memcpy(buf, delim, delimsz);
  3539. buf += delimsz;
  3540. bufsz -= delimsz;
  3541. }
  3542. }
  3543. // Last entry has the unit
  3544. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  3545. return buflist[0];
  3546. }
  3547. #define multi_format_unit2(buf, bufsz, floatprec, measurement, fmt, delim, count, ...) _multi_format_unit((char *[]){buf}, (size_t[]){bufsz}, floatprec, measurement, fmt, delim, count, (float[]){ __VA_ARGS__ }, false)
  3548. #define multi_format_unit_array2(buflist, bufszlist, floatprec, measurement, fmt, count, ...) (void)_multi_format_unit(buflist, bufszlist, floatprec, measurement, fmt, NULL, count, (float[]){ __VA_ARGS__ }, true)
  3549. static
  3550. int percentf3(char * const buf, size_t sz, double p, const double t)
  3551. {
  3552. char *s = buf;
  3553. int rv = 0;
  3554. if (!p)
  3555. _SNP("none");
  3556. else
  3557. if (t <= p)
  3558. _SNP("100%%");
  3559. else
  3560. {
  3561. p /= t;
  3562. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  3563. _SNP(".%02.0f%%", p * 10000); // ".01%"
  3564. else
  3565. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  3566. _SNP("%.1f%%", p * 100); // "9.1%"
  3567. else
  3568. _SNP("%3.0f%%", p * 100); // " 99%"
  3569. }
  3570. return rv;
  3571. }
  3572. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  3573. static
  3574. void test_decimal_width()
  3575. {
  3576. // The pipe character at end of each line should perfectly line up
  3577. char printbuf[512];
  3578. char testbuf1[64];
  3579. char testbuf2[64];
  3580. char testbuf3[64];
  3581. char testbuf4[64];
  3582. double testn;
  3583. int width;
  3584. int saved;
  3585. // Hotspots around 0.1 and 0.01
  3586. saved = -1;
  3587. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  3588. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  3589. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  3590. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  3591. if (unlikely((saved != -1) && (width != saved))) {
  3592. ++unittest_failures;
  3593. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  3594. applog(LOG_ERR, "%s", printbuf);
  3595. }
  3596. saved = width;
  3597. }
  3598. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  3599. saved = -1;
  3600. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  3601. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3602. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3603. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3604. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  3605. width = utf8_strlen(printbuf);
  3606. if (unlikely((saved != -1) && (width != saved))) {
  3607. ++unittest_failures;
  3608. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  3609. applog(LOG_ERR, "%s", printbuf);
  3610. }
  3611. saved = width;
  3612. }
  3613. // Hotspot around unit transition boundary in pick_unit
  3614. saved = -1;
  3615. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  3616. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3617. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3618. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3619. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  3620. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  3621. width = utf8_strlen(printbuf);
  3622. if (unlikely((saved != -1) && (width != saved))) {
  3623. ++unittest_failures;
  3624. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  3625. applog(LOG_ERR, "%s", printbuf);
  3626. }
  3627. saved = width;
  3628. }
  3629. }
  3630. #ifdef HAVE_CURSES
  3631. static void adj_width(int var, int *length);
  3632. #endif
  3633. #ifdef HAVE_CURSES
  3634. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  3635. static
  3636. void format_statline(char *buf, size_t bufsz, const char *cHr, const char *aHr, const char *uHr, int accepted, int rejected, int stale, double wnotaccepted, double waccepted, int hwerrs, double bad_diff1, double allnonces)
  3637. {
  3638. char rejpcbuf[6];
  3639. char bnbuf[6];
  3640. adj_width(accepted, &awidth);
  3641. adj_width(rejected, &rwidth);
  3642. adj_width(stale, &swidth);
  3643. adj_width(hwerrs, &hwwidth);
  3644. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3645. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  3646. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  3647. cHr, aHr, uHr,
  3648. awidth, accepted,
  3649. rwidth, rejected,
  3650. swidth, stale,
  3651. rejpcbuf,
  3652. hwwidth, hwerrs,
  3653. bnbuf
  3654. );
  3655. }
  3656. static
  3657. const char *pool_proto_str(const struct pool * const pool)
  3658. {
  3659. if (pool->idle)
  3660. return "Dead ";
  3661. if (pool->has_stratum)
  3662. return "Strtm";
  3663. if (pool->lp_url && pool->proto != pool->lp_proto)
  3664. return "Mixed";
  3665. switch (pool->proto)
  3666. {
  3667. case PLP_GETBLOCKTEMPLATE:
  3668. return " GBT ";
  3669. case PLP_GETWORK:
  3670. return "GWork";
  3671. default:
  3672. return "Alive";
  3673. }
  3674. }
  3675. #endif
  3676. static inline
  3677. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  3678. {
  3679. if (!(use_unicode && have_unicode_degrees))
  3680. maybe_unicode = false;
  3681. if (temp && *temp > 0.)
  3682. if (maybe_unicode)
  3683. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  3684. else
  3685. snprintf(buf, bufsz, "%4.1fC", *temp);
  3686. else
  3687. {
  3688. if (temp)
  3689. snprintf(buf, bufsz, " ");
  3690. if (maybe_unicode)
  3691. tailsprintf(buf, bufsz, " ");
  3692. }
  3693. tailsprintf(buf, bufsz, " | ");
  3694. }
  3695. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  3696. {
  3697. #ifndef HAVE_CURSES
  3698. assert(for_curses == false);
  3699. #endif
  3700. struct device_drv *drv = cgpu->drv;
  3701. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  3702. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[max(ALLOC_H2B_SHORT, ALLOC_H2B_SPACED)+3+1];
  3703. char rejpcbuf[6];
  3704. char bnbuf[6];
  3705. double dev_runtime;
  3706. if (!opt_show_procs)
  3707. cgpu = cgpu->device;
  3708. dev_runtime = cgpu_runtime(cgpu);
  3709. double rolling, mhashes;
  3710. int accepted, rejected, stale;
  3711. double waccepted;
  3712. double wnotaccepted;
  3713. int hwerrs;
  3714. double bad_diff1, good_diff1;
  3715. rolling = mhashes = waccepted = wnotaccepted = 0;
  3716. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  3717. {
  3718. struct cgpu_info *slave = cgpu;
  3719. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  3720. {
  3721. slave->utility = slave->accepted / dev_runtime * 60;
  3722. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  3723. rolling += drv->get_proc_rolling_hashrate ? drv->get_proc_rolling_hashrate(slave) : slave->rolling;
  3724. mhashes += slave->total_mhashes;
  3725. if (opt_weighed_stats)
  3726. {
  3727. accepted += slave->diff_accepted;
  3728. rejected += slave->diff_rejected;
  3729. stale += slave->diff_stale;
  3730. }
  3731. else
  3732. {
  3733. accepted += slave->accepted;
  3734. rejected += slave->rejected;
  3735. stale += slave->stale;
  3736. }
  3737. waccepted += slave->diff_accepted;
  3738. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  3739. hwerrs += slave->hw_errors;
  3740. bad_diff1 += slave->bad_diff1;
  3741. good_diff1 += slave->diff1;
  3742. if (opt_show_procs)
  3743. break;
  3744. }
  3745. }
  3746. double wtotal = (waccepted + wnotaccepted);
  3747. multi_format_unit_array2(
  3748. ((char*[]){cHr, aHr, uHr}),
  3749. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  3750. true, "h/s", hashrate_style,
  3751. 3,
  3752. 1e6*rolling,
  3753. 1e6*mhashes / dev_runtime,
  3754. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  3755. // Processor representation
  3756. #ifdef HAVE_CURSES
  3757. if (for_curses)
  3758. {
  3759. if (opt_show_procs)
  3760. snprintf(buf, bufsz, " %*s: ", -(5 + max_lpdigits), cgpu->proc_repr);
  3761. else
  3762. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  3763. }
  3764. else
  3765. #endif
  3766. {
  3767. if (opt_show_procs)
  3768. snprintf(buf, bufsz, "%*s ", -(5 + max_lpdigits), cgpu->proc_repr_ns);
  3769. else
  3770. snprintf(buf, bufsz, "%-5s ", cgpu->dev_repr_ns);
  3771. }
  3772. if (include_serial_in_statline && cgpu->dev_serial)
  3773. tailsprintf(buf, bufsz, "[serial=%s] ", cgpu->dev_serial);
  3774. if (unlikely(cgpu->status == LIFE_INIT))
  3775. {
  3776. tailsprintf(buf, bufsz, "Initializing...");
  3777. return;
  3778. }
  3779. {
  3780. const size_t bufln = strlen(buf);
  3781. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3782. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3783. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3784. else
  3785. {
  3786. float temp = cgpu->temp;
  3787. if (!opt_show_procs)
  3788. {
  3789. // Find the highest temperature of all processors
  3790. struct cgpu_info *proc = cgpu;
  3791. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3792. if (proc->temp > temp)
  3793. temp = proc->temp;
  3794. }
  3795. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3796. }
  3797. }
  3798. #ifdef HAVE_CURSES
  3799. if (for_curses)
  3800. {
  3801. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3802. const char *cHrStats;
  3803. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3804. bool all_dead = true, all_off = true, all_rdrv = true;
  3805. struct cgpu_info *proc = cgpu;
  3806. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3807. {
  3808. switch (cHrStatsI) {
  3809. default:
  3810. if (proc->status == LIFE_WAIT)
  3811. cHrStatsI = 5;
  3812. case 5:
  3813. if (proc->deven == DEV_RECOVER_ERR)
  3814. cHrStatsI = 4;
  3815. case 4:
  3816. if (proc->deven == DEV_RECOVER)
  3817. cHrStatsI = 3;
  3818. case 3:
  3819. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3820. {
  3821. cHrStatsI = 1;
  3822. all_off = false;
  3823. }
  3824. else
  3825. {
  3826. if (likely(proc->deven == DEV_ENABLED))
  3827. all_off = false;
  3828. if (proc->deven != DEV_RECOVER_DRV)
  3829. all_rdrv = false;
  3830. }
  3831. case 1:
  3832. break;
  3833. }
  3834. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3835. all_dead = false;
  3836. if (opt_show_procs)
  3837. break;
  3838. }
  3839. if (unlikely(all_dead))
  3840. cHrStatsI = 0;
  3841. else
  3842. if (unlikely(all_off))
  3843. cHrStatsI = 2;
  3844. cHrStats = cHrStatsOpt[cHrStatsI];
  3845. if (cHrStatsI == 2 && all_rdrv)
  3846. cHrStats = " RST ";
  3847. format_statline(buf, bufsz,
  3848. cHrStats,
  3849. aHr, uHr,
  3850. accepted, rejected, stale,
  3851. wnotaccepted, waccepted,
  3852. hwerrs,
  3853. bad_diff1, bad_diff1 + good_diff1);
  3854. }
  3855. else
  3856. #endif
  3857. {
  3858. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3859. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3860. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3861. opt_log_interval,
  3862. cHr, aHr, uHr,
  3863. accepted,
  3864. rejected,
  3865. stale,
  3866. rejpcbuf,
  3867. hwerrs,
  3868. bnbuf
  3869. );
  3870. }
  3871. }
  3872. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3873. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3874. static void text_print_status(int thr_id)
  3875. {
  3876. struct cgpu_info *cgpu;
  3877. char logline[256];
  3878. cgpu = get_thr_cgpu(thr_id);
  3879. if (cgpu) {
  3880. get_statline(logline, sizeof(logline), cgpu);
  3881. printf("\n%s\r", logline);
  3882. fflush(stdout);
  3883. }
  3884. }
  3885. #ifdef HAVE_CURSES
  3886. static int attr_bad = A_BOLD;
  3887. #ifdef WIN32
  3888. #define swprintf snwprintf
  3889. #endif
  3890. static
  3891. void bfg_waddstr(WINDOW *win, const char *s)
  3892. {
  3893. const char *p = s;
  3894. int32_t w;
  3895. int wlen;
  3896. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3897. while (true)
  3898. {
  3899. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3900. {
  3901. // Printable ASCII
  3902. ++p;
  3903. }
  3904. if (p != s)
  3905. waddnstr(win, s, p - s);
  3906. w = utf8_decode(p, &wlen);
  3907. s = p += wlen;
  3908. switch(w)
  3909. {
  3910. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3911. case '\0':
  3912. return;
  3913. case 0xb5: // micro symbol
  3914. w = unicode_micro;
  3915. goto default_addch;
  3916. case 0xf000: // "bad" off
  3917. wattroff(win, attr_bad);
  3918. break;
  3919. case 0xf001: // "bad" on
  3920. wattron(win, attr_bad);
  3921. break;
  3922. #ifdef USE_UNICODE
  3923. case '|':
  3924. wadd_wch(win, WACS_VLINE);
  3925. break;
  3926. #endif
  3927. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3928. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3929. if (!use_unicode)
  3930. {
  3931. waddch(win, '-');
  3932. break;
  3933. }
  3934. #ifdef USE_UNICODE
  3935. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3936. break;
  3937. #endif
  3938. case 0x2022:
  3939. if (w > WCHAR_MAX || !iswprint(w))
  3940. w = '*';
  3941. default:
  3942. default_addch:
  3943. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3944. {
  3945. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3946. if (iswprint(REPLACEMENT_CHAR))
  3947. w = REPLACEMENT_CHAR;
  3948. else
  3949. #endif
  3950. w = '?';
  3951. }
  3952. {
  3953. #ifdef USE_UNICODE
  3954. wchar_t wbuf[0x10];
  3955. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3956. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3957. waddnwstr(win, wbuf, wbuflen);
  3958. #else
  3959. wprintw(win, "%lc", (wint_t)w);
  3960. #endif
  3961. }
  3962. }
  3963. }
  3964. }
  3965. static inline
  3966. void bfg_hline(WINDOW *win, int y)
  3967. {
  3968. int maxx, __maybe_unused maxy;
  3969. getmaxyx(win, maxy, maxx);
  3970. #ifdef USE_UNICODE
  3971. if (use_unicode)
  3972. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3973. else
  3974. #endif
  3975. mvwhline(win, y, 0, '-', maxx);
  3976. }
  3977. static
  3978. int bfg_win_linelen(WINDOW * const win)
  3979. {
  3980. int maxx;
  3981. int __maybe_unused y;
  3982. getmaxyx(win, y, maxx);
  3983. return maxx;
  3984. }
  3985. // Spaces until end of line, using current attributes (ie, not completely clear)
  3986. static
  3987. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3988. {
  3989. int x, maxx;
  3990. int __maybe_unused y;
  3991. getmaxyx(win, y, maxx);
  3992. getyx(win, y, x);
  3993. const int space_count = (maxx - x) - offset;
  3994. // Check for negative - terminal too narrow
  3995. if (space_count <= 0)
  3996. return;
  3997. char buf[space_count];
  3998. memset(buf, ' ', space_count);
  3999. waddnstr(win, buf, space_count);
  4000. }
  4001. static int menu_attr = A_REVERSE;
  4002. #define CURBUFSIZ 256
  4003. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  4004. char tmp42[CURBUFSIZ]; \
  4005. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  4006. wmove(win, y, x); \
  4007. bfg_waddstr(win, tmp42); \
  4008. } while (0)
  4009. #define cg_wprintw(win, fmt, ...) do { \
  4010. char tmp42[CURBUFSIZ]; \
  4011. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  4012. bfg_waddstr(win, tmp42); \
  4013. } while (0)
  4014. static
  4015. void update_block_display_line(const int blky, struct mining_goal_info *goal)
  4016. {
  4017. struct blockchain_info * const blkchain = goal->blkchain;
  4018. struct block_info * const blkinfo = blkchain->currentblk;
  4019. double income;
  4020. char incomestr[ALLOC_H2B_SHORT+6+1];
  4021. if (blkinfo->height)
  4022. {
  4023. income = goal->diff_accepted * 3600 * blkchain->currentblk_subsidy / total_secs / goal->current_diff;
  4024. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  4025. }
  4026. else
  4027. strcpy(incomestr, "?");
  4028. int linelen = bfg_win_linelen(statuswin);
  4029. wmove(statuswin, blky, 0);
  4030. bfg_waddstr(statuswin, " Block");
  4031. if (!goal->is_default)
  4032. linelen -= strlen(goal->name) + 1;
  4033. linelen -= 6; // " Block"
  4034. if (blkinfo->height && blkinfo->height < 1000000)
  4035. {
  4036. cg_wprintw(statuswin, " #%6u", blkinfo->height);
  4037. linelen -= 8;
  4038. }
  4039. bfg_waddstr(statuswin, ":");
  4040. if (linelen > 55)
  4041. bfg_waddstr(statuswin, " ");
  4042. if (linelen >= 65)
  4043. bfg_waddstr(statuswin, "...");
  4044. {
  4045. char hexpbh[0x11];
  4046. if (!(blkinfo->height && blkinfo->height < 1000000))
  4047. {
  4048. bin2hex(hexpbh, &blkinfo->prevblkhash[4], 4);
  4049. bfg_waddstr(statuswin, hexpbh);
  4050. }
  4051. bin2hex(hexpbh, &blkinfo->prevblkhash[0], 4);
  4052. bfg_waddstr(statuswin, hexpbh);
  4053. }
  4054. if (linelen >= 55)
  4055. bfg_waddstr(statuswin, " ");
  4056. cg_wprintw(statuswin, " Diff:%s", goal->current_diff_str);
  4057. if (linelen >= 69)
  4058. bfg_waddstr(statuswin, " ");
  4059. cg_wprintw(statuswin, "(%s) ", goal->net_hashrate);
  4060. if (linelen >= 62)
  4061. {
  4062. if (linelen >= 69)
  4063. bfg_waddstr(statuswin, " ");
  4064. bfg_waddstr(statuswin, "Started:");
  4065. }
  4066. else
  4067. bfg_waddstr(statuswin, "S:");
  4068. if (linelen >= 69)
  4069. bfg_waddstr(statuswin, " ");
  4070. bfg_waddstr(statuswin, blkchain->currentblk_first_seen_time_str);
  4071. if (linelen >= 69)
  4072. bfg_waddstr(statuswin, " ");
  4073. cg_wprintw(statuswin, " I:%s", incomestr);
  4074. if (!goal->is_default)
  4075. cg_wprintw(statuswin, " %s", goal->name);
  4076. wclrtoeol(statuswin);
  4077. }
  4078. static bool pool_actively_in_use(const struct pool *, const struct pool *);
  4079. static
  4080. void update_block_display(const bool within_console_lock)
  4081. {
  4082. struct mining_goal_info *goal, *tmpgoal;
  4083. int blky = 3, i, total_found_goals = 0;
  4084. if (!within_console_lock)
  4085. if (!curses_active_locked())
  4086. return;
  4087. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  4088. {
  4089. for (i = 0; i < total_pools; ++i)
  4090. {
  4091. struct pool * const pool = pools[i];
  4092. if (pool->goal == goal && pool_actively_in_use(pool, NULL))
  4093. break;
  4094. }
  4095. if (i >= total_pools)
  4096. // no pools using this goal, so it's probably stale anyway
  4097. continue;
  4098. update_block_display_line(blky++, goal);
  4099. ++total_found_goals;
  4100. }
  4101. // We cannot do resizing if called within someone else's console lock
  4102. if (within_console_lock)
  4103. return;
  4104. bfg_console_unlock();
  4105. if (total_found_goals != active_goals)
  4106. {
  4107. active_goals = total_found_goals;
  4108. devcursor = 7 + active_goals;
  4109. switch_logsize();
  4110. }
  4111. }
  4112. static bool pool_unworkable(const struct pool *);
  4113. /* Must be called with curses mutex lock held and curses_active */
  4114. static void curses_print_status(const int ts)
  4115. {
  4116. struct pool *pool = currentpool;
  4117. struct timeval now, tv;
  4118. float efficiency;
  4119. int logdiv;
  4120. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  4121. wattron(statuswin, attr_title);
  4122. const int linelen = bfg_win_linelen(statuswin);
  4123. int titlelen = 1 + strlen(PACKAGE) + 1 + strlen(bfgminer_ver) + 3 + 21 + 3 + 19;
  4124. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " ");
  4125. if (titlelen + 17 < linelen)
  4126. cg_wprintw(statuswin, "version ");
  4127. cg_wprintw(statuswin, "%s - ", bfgminer_ver);
  4128. if (titlelen + 9 < linelen)
  4129. cg_wprintw(statuswin, "Started: ");
  4130. else
  4131. if (titlelen + 7 <= linelen)
  4132. cg_wprintw(statuswin, "Start: ");
  4133. cg_wprintw(statuswin, "%s", datestamp);
  4134. timer_set_now(&now);
  4135. {
  4136. unsigned int days, hours;
  4137. div_t d;
  4138. timersub(&now, &miner_started, &tv);
  4139. d = div(tv.tv_sec, 86400);
  4140. days = d.quot;
  4141. d = div(d.rem, 3600);
  4142. hours = d.quot;
  4143. d = div(d.rem, 60);
  4144. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  4145. , days
  4146. , (days == 1) ? ' ' : 's'
  4147. , hours
  4148. , d.quot
  4149. , d.rem
  4150. );
  4151. }
  4152. bfg_wspctoeol(statuswin, 0);
  4153. wattroff(statuswin, attr_title);
  4154. wattron(statuswin, menu_attr);
  4155. wmove(statuswin, 1, 0);
  4156. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  4157. bfg_wspctoeol(statuswin, 14);
  4158. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  4159. wattroff(statuswin, menu_attr);
  4160. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && enabled_pools > 1) {
  4161. char poolinfo[20], poolinfo2[20];
  4162. int poolinfooff = 0, poolinfo2off, workable_pools = 0;
  4163. double lowdiff = DBL_MAX, highdiff = -1;
  4164. struct pool *lowdiff_pool = pools[0], *highdiff_pool = pools[0];
  4165. time_t oldest_work_restart = time(NULL) + 1;
  4166. struct pool *oldest_work_restart_pool = pools[0];
  4167. for (int i = 0; i < total_pools; ++i)
  4168. {
  4169. if (pool_unworkable(pools[i]))
  4170. continue;
  4171. // NOTE: Only set pool var when it's workable; if only one is, it gets used by single-pool code
  4172. pool = pools[i];
  4173. ++workable_pools;
  4174. if (poolinfooff < sizeof(poolinfo))
  4175. poolinfooff += snprintf(&poolinfo[poolinfooff], sizeof(poolinfo) - poolinfooff, "%u,", pool->pool_no);
  4176. struct cgminer_pool_stats * const pool_stats = &pool->cgminer_pool_stats;
  4177. if (pool_stats->last_diff < lowdiff)
  4178. {
  4179. lowdiff = pool_stats->last_diff;
  4180. lowdiff_pool = pool;
  4181. }
  4182. if (pool_stats->last_diff > highdiff)
  4183. {
  4184. highdiff = pool_stats->last_diff;
  4185. highdiff_pool = pool;
  4186. }
  4187. if (oldest_work_restart >= pool->work_restart_time)
  4188. {
  4189. oldest_work_restart = pool->work_restart_time;
  4190. oldest_work_restart_pool = pool;
  4191. }
  4192. }
  4193. if (unlikely(!workable_pools))
  4194. goto no_workable_pools;
  4195. if (workable_pools == 1)
  4196. goto one_workable_pool;
  4197. poolinfo2off = snprintf(poolinfo2, sizeof(poolinfo2), "%u (", workable_pools);
  4198. if (poolinfooff > sizeof(poolinfo2) - poolinfo2off - 1)
  4199. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s...)", (int)(sizeof(poolinfo2) - poolinfo2off - 5), poolinfo);
  4200. else
  4201. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s)%*s", (int)(poolinfooff - 1), poolinfo, (int)(sizeof(poolinfo2)), "");
  4202. cg_mvwprintw(statuswin, 2, 0, " Pools: %s Diff:%s%s%s %c LU:%s",
  4203. poolinfo2,
  4204. lowdiff_pool->diff,
  4205. (lowdiff == highdiff) ? "" : "-",
  4206. (lowdiff == highdiff) ? "" : highdiff_pool->diff,
  4207. pool->goal->have_longpoll ? '+' : '-',
  4208. oldest_work_restart_pool->work_restart_timestamp);
  4209. }
  4210. else
  4211. if (pool_unworkable(pool))
  4212. {
  4213. no_workable_pools: ;
  4214. wattron(statuswin, attr_bad);
  4215. cg_mvwprintw(statuswin, 2, 0, " (all pools are dead) ");
  4216. wattroff(statuswin, attr_bad);
  4217. }
  4218. else
  4219. {
  4220. one_workable_pool: ;
  4221. char pooladdr[19];
  4222. {
  4223. const char *rawaddr = pool->sockaddr_url;
  4224. BFGINIT(rawaddr, pool->rpc_url);
  4225. size_t pooladdrlen = strlen(rawaddr);
  4226. if (pooladdrlen > 20)
  4227. snprintf(pooladdr, sizeof(pooladdr), "...%s", &rawaddr[pooladdrlen - (sizeof(pooladdr) - 4)]);
  4228. else
  4229. snprintf(pooladdr, sizeof(pooladdr), "%*s", -(int)(sizeof(pooladdr) - 1), rawaddr);
  4230. }
  4231. cg_mvwprintw(statuswin, 2, 0, " Pool%2u: %s Diff:%s %c%s LU:%s User:%s",
  4232. pool->pool_no, pooladdr, pool->diff,
  4233. pool->goal->have_longpoll ? '+' : '-', pool_proto_str(pool),
  4234. pool->work_restart_timestamp,
  4235. pool->rpc_user);
  4236. }
  4237. wclrtoeol(statuswin);
  4238. update_block_display(true);
  4239. char bwstr[(ALLOC_H2B_SHORT*2)+3+1];
  4240. cg_mvwprintw(statuswin, devcursor - 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f BS:%s",
  4241. ts,
  4242. total_go + total_ro,
  4243. new_blocks,
  4244. total_submitting,
  4245. multi_format_unit2(bwstr, sizeof(bwstr),
  4246. false, "B/s", H2B_SHORT, "/", 2,
  4247. (float)(total_bytes_rcvd / total_secs),
  4248. (float)(total_bytes_sent / total_secs)),
  4249. efficiency,
  4250. best_share);
  4251. wclrtoeol(statuswin);
  4252. mvwaddstr(statuswin, devcursor - 3, 0, " ");
  4253. bfg_waddstr(statuswin, statusline);
  4254. wclrtoeol(statuswin);
  4255. int devdiv = devcursor - 2;
  4256. logdiv = statusy - 1;
  4257. bfg_hline(statuswin, devdiv);
  4258. bfg_hline(statuswin, logdiv);
  4259. #ifdef USE_UNICODE
  4260. if (use_unicode)
  4261. {
  4262. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  4263. if (opt_show_procs && !opt_compact)
  4264. offset += max_lpdigits; // proc letter(s)
  4265. if (have_unicode_degrees)
  4266. ++offset; // degrees symbol
  4267. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4268. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4269. offset += 24; // hashrates etc
  4270. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4271. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4272. }
  4273. #endif
  4274. }
  4275. static void adj_width(int var, int *length)
  4276. {
  4277. if ((int)(log10(var) + 1) > *length)
  4278. (*length)++;
  4279. }
  4280. static int dev_width;
  4281. static void curses_print_devstatus(struct cgpu_info *cgpu)
  4282. {
  4283. char logline[256];
  4284. int ypos;
  4285. if (opt_compact)
  4286. return;
  4287. /* Check this isn't out of the window size */
  4288. if (opt_show_procs)
  4289. ypos = cgpu->cgminer_id;
  4290. else
  4291. {
  4292. if (cgpu->proc_id)
  4293. return;
  4294. ypos = cgpu->device_line_id;
  4295. }
  4296. ypos += devsummaryYOffset;
  4297. if (ypos < 0)
  4298. return;
  4299. ypos += devcursor - 1;
  4300. if (ypos >= statusy - 1)
  4301. return;
  4302. if (wmove(statuswin, ypos, 0) == ERR)
  4303. return;
  4304. get_statline2(logline, sizeof(logline), cgpu, true);
  4305. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  4306. wattron(statuswin, A_REVERSE);
  4307. bfg_waddstr(statuswin, logline);
  4308. wattroff(statuswin, A_REVERSE);
  4309. wclrtoeol(statuswin);
  4310. }
  4311. static
  4312. void _refresh_devstatus(const bool already_have_lock) {
  4313. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  4314. int i;
  4315. if (unlikely(!total_devices))
  4316. {
  4317. const int ypos = devcursor - 1;
  4318. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  4319. {
  4320. wattron(statuswin, attr_bad);
  4321. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  4322. wclrtoeol(statuswin);
  4323. wattroff(statuswin, attr_bad);
  4324. }
  4325. }
  4326. for (i = 0; i < total_devices; i++)
  4327. curses_print_devstatus(get_devices(i));
  4328. touchwin(statuswin);
  4329. wrefresh(statuswin);
  4330. if (!already_have_lock)
  4331. unlock_curses();
  4332. }
  4333. }
  4334. #define refresh_devstatus() _refresh_devstatus(false)
  4335. #endif
  4336. static void print_status(int thr_id)
  4337. {
  4338. if (!curses_active)
  4339. text_print_status(thr_id);
  4340. }
  4341. #ifdef HAVE_CURSES
  4342. static
  4343. bool set_statusy(int maxy)
  4344. {
  4345. if (loginput_size)
  4346. {
  4347. maxy -= loginput_size;
  4348. if (maxy < 0)
  4349. maxy = 0;
  4350. }
  4351. if (logstart < maxy)
  4352. maxy = logstart;
  4353. if (statusy == maxy)
  4354. return false;
  4355. statusy = maxy;
  4356. logcursor = statusy;
  4357. return true;
  4358. }
  4359. /* Check for window resize. Called with curses mutex locked */
  4360. static inline void change_logwinsize(void)
  4361. {
  4362. int x, y, logx, logy;
  4363. getmaxyx(mainwin, y, x);
  4364. if (x < 80 || y < 25)
  4365. return;
  4366. if (y > statusy + 2 && statusy < logstart) {
  4367. set_statusy(y - 2);
  4368. mvwin(logwin, logcursor, 0);
  4369. bfg_wresize(statuswin, statusy, x);
  4370. }
  4371. y -= logcursor;
  4372. getmaxyx(logwin, logy, logx);
  4373. /* Detect screen size change */
  4374. if (x != logx || y != logy)
  4375. bfg_wresize(logwin, y, x);
  4376. }
  4377. static void check_winsizes(void)
  4378. {
  4379. if (!use_curses)
  4380. return;
  4381. if (curses_active_locked()) {
  4382. int y, x;
  4383. x = getmaxx(statuswin);
  4384. if (set_statusy(LINES - 2))
  4385. {
  4386. erase();
  4387. bfg_wresize(statuswin, statusy, x);
  4388. getmaxyx(mainwin, y, x);
  4389. y -= logcursor;
  4390. bfg_wresize(logwin, y, x);
  4391. mvwin(logwin, logcursor, 0);
  4392. }
  4393. unlock_curses();
  4394. }
  4395. }
  4396. static int device_line_id_count;
  4397. static void switch_logsize(void)
  4398. {
  4399. if (curses_active_locked()) {
  4400. if (opt_compact) {
  4401. logstart = devcursor - 1;
  4402. logcursor = logstart + 1;
  4403. } else {
  4404. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  4405. logstart = devcursor + total_lines;
  4406. logcursor = logstart;
  4407. }
  4408. unlock_curses();
  4409. }
  4410. check_winsizes();
  4411. update_block_display(false);
  4412. }
  4413. /* For mandatory printing when mutex is already locked */
  4414. void _wlog(const char *str)
  4415. {
  4416. static bool newline;
  4417. size_t end = strlen(str) - 1;
  4418. if (newline)
  4419. bfg_waddstr(logwin, "\n");
  4420. if (str[end] == '\n')
  4421. {
  4422. char *s;
  4423. newline = true;
  4424. s = alloca(end + 1);
  4425. memcpy(s, str, end);
  4426. s[end] = '\0';
  4427. str = s;
  4428. }
  4429. else
  4430. newline = false;
  4431. bfg_waddstr(logwin, str);
  4432. }
  4433. /* Mandatory printing */
  4434. void _wlogprint(const char *str)
  4435. {
  4436. if (curses_active_locked()) {
  4437. _wlog(str);
  4438. unlock_curses();
  4439. }
  4440. }
  4441. #endif
  4442. #ifdef HAVE_CURSES
  4443. bool _log_curses_only(int prio, const char *datetime, const char *str)
  4444. {
  4445. bool high_prio;
  4446. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  4447. if (curses_active)
  4448. {
  4449. if (!loginput_size || high_prio) {
  4450. wlog(" %s %s\n", datetime, str);
  4451. if (high_prio) {
  4452. touchwin(logwin);
  4453. wrefresh(logwin);
  4454. }
  4455. }
  4456. return true;
  4457. }
  4458. return false;
  4459. }
  4460. void clear_logwin(void)
  4461. {
  4462. if (curses_active_locked()) {
  4463. wclear(logwin);
  4464. unlock_curses();
  4465. }
  4466. }
  4467. void logwin_update(void)
  4468. {
  4469. if (curses_active_locked()) {
  4470. touchwin(logwin);
  4471. wrefresh(logwin);
  4472. unlock_curses();
  4473. }
  4474. }
  4475. #endif
  4476. void enable_pool(struct pool * const pool)
  4477. {
  4478. if (pool->enabled != POOL_ENABLED) {
  4479. mutex_lock(&lp_lock);
  4480. enabled_pools++;
  4481. pool->enabled = POOL_ENABLED;
  4482. pthread_cond_broadcast(&lp_cond);
  4483. mutex_unlock(&lp_lock);
  4484. if (pool->prio < current_pool()->prio)
  4485. switch_pools(pool);
  4486. }
  4487. }
  4488. void manual_enable_pool(struct pool * const pool)
  4489. {
  4490. pool->failover_only = false;
  4491. BFGINIT(pool->quota, 1);
  4492. enable_pool(pool);
  4493. }
  4494. void disable_pool(struct pool * const pool, const enum pool_enable enable_status)
  4495. {
  4496. if (pool->enabled == POOL_DISABLED)
  4497. /* had been manually disabled before */
  4498. return;
  4499. if (pool->enabled != POOL_ENABLED)
  4500. {
  4501. /* has been programmatically disabled already, just change to the new status directly */
  4502. pool->enabled = enable_status;
  4503. return;
  4504. }
  4505. /* Fall into the lock area */
  4506. mutex_lock(&lp_lock);
  4507. --enabled_pools;
  4508. pool->enabled = enable_status;
  4509. mutex_unlock(&lp_lock);
  4510. if (pool == current_pool())
  4511. switch_pools(NULL);
  4512. }
  4513. static
  4514. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  4515. struct cgpu_info *cgpu;
  4516. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  4517. const unsigned char *hashpart = &work->hash[0x1c - malgo->ui_skip_hash_bytes];
  4518. char shrdiffdisp[ALLOC_H2B_SHORTV];
  4519. const double tgtdiff = work->work_difficulty;
  4520. char tgtdiffdisp[ALLOC_H2B_SHORTV];
  4521. char where[20];
  4522. cgpu = get_thr_cgpu(work->thr_id);
  4523. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  4524. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  4525. if (total_pools > 1)
  4526. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  4527. else
  4528. where[0] = '\0';
  4529. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  4530. disp,
  4531. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  4532. cgpu->proc_repr,
  4533. where,
  4534. shrdiffdisp, tgtdiffdisp,
  4535. reason,
  4536. resubmit ? "(resubmit)" : "",
  4537. worktime
  4538. );
  4539. }
  4540. static bool test_work_current(struct work *);
  4541. static void _submit_work_async(struct work *);
  4542. static
  4543. void maybe_local_submit(const struct work *work)
  4544. {
  4545. #if BLKMAKER_VERSION > 3
  4546. if (unlikely(work->block && work->tr))
  4547. {
  4548. // This is a block with a full template (GBT)
  4549. // Regardless of the result, submit to local bitcoind(s) as well
  4550. struct work *work_cp;
  4551. for (int i = 0; i < total_pools; ++i)
  4552. {
  4553. if (!uri_get_param_bool(pools[i]->rpc_url, "allblocks", false))
  4554. continue;
  4555. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  4556. work_cp = copy_work(work);
  4557. work_cp->pool = pools[i];
  4558. work_cp->do_foreign_submit = true;
  4559. _submit_work_async(work_cp);
  4560. }
  4561. }
  4562. #endif
  4563. }
  4564. static
  4565. json_t *extract_reject_reason_j(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4566. {
  4567. if (json_is_string(res))
  4568. return res;
  4569. if ( (res = json_object_get(val, "reject-reason")) )
  4570. return res;
  4571. if (work->stratum && err && json_is_array(err) && json_array_size(err) >= 2 && (res = json_array_get(err, 1)) && json_is_string(res))
  4572. return res;
  4573. return NULL;
  4574. }
  4575. static
  4576. const char *extract_reject_reason(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4577. {
  4578. json_t * const j = extract_reject_reason_j(val, res, err, work);
  4579. return j ? json_string_value(j) : NULL;
  4580. }
  4581. static
  4582. int put_in_parens(char * const buf, const size_t bufsz, const char * const s)
  4583. {
  4584. if (!s)
  4585. {
  4586. if (bufsz)
  4587. buf[0] = '\0';
  4588. return 0;
  4589. }
  4590. int p = snprintf(buf, bufsz, " (%s", s);
  4591. if (p >= bufsz - 1)
  4592. p = bufsz - 2;
  4593. strcpy(&buf[p], ")");
  4594. return p + 1;
  4595. }
  4596. /* Theoretically threads could race when modifying accepted and
  4597. * rejected values but the chance of two submits completing at the
  4598. * same time is zero so there is no point adding extra locking */
  4599. static void
  4600. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  4601. /*char *hashshow,*/ bool resubmit, char *worktime)
  4602. {
  4603. struct pool *pool = work->pool;
  4604. struct cgpu_info *cgpu;
  4605. cgpu = get_thr_cgpu(work->thr_id);
  4606. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  4607. struct mining_goal_info * const goal = pool->goal;
  4608. mutex_lock(&stats_lock);
  4609. cgpu->accepted++;
  4610. total_accepted++;
  4611. pool->accepted++;
  4612. cgpu->diff_accepted += work->work_difficulty;
  4613. total_diff_accepted += work->work_difficulty;
  4614. pool->diff_accepted += work->work_difficulty;
  4615. goal->diff_accepted += work->work_difficulty;
  4616. mutex_unlock(&stats_lock);
  4617. pool->seq_rejects = 0;
  4618. cgpu->last_share_pool = pool->pool_no;
  4619. cgpu->last_share_pool_time = time(NULL);
  4620. cgpu->last_share_diff = work->work_difficulty;
  4621. pool->last_share_time = cgpu->last_share_pool_time;
  4622. pool->last_share_diff = work->work_difficulty;
  4623. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  4624. if (!QUIET) {
  4625. share_result_msg(work, "Accepted", "", resubmit, worktime);
  4626. }
  4627. sharelog("accept", work);
  4628. if (opt_shares && total_diff_accepted >= opt_shares) {
  4629. applog(LOG_WARNING, "Successfully mined %g accepted shares as requested and exiting.", opt_shares);
  4630. kill_work();
  4631. return;
  4632. }
  4633. /* Detect if a pool that has been temporarily disabled for
  4634. * continually rejecting shares has started accepting shares.
  4635. * This will only happen with the work returned from a
  4636. * longpoll */
  4637. if (unlikely(pool->enabled == POOL_REJECTING)) {
  4638. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  4639. enable_pool(pool);
  4640. }
  4641. if (unlikely(work->block)) {
  4642. // Force moving on to this new block :)
  4643. struct work fakework;
  4644. memset(&fakework, 0, sizeof(fakework));
  4645. fakework.pool = work->pool;
  4646. // Copy block version, bits, and time from share
  4647. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  4648. memcpy(&fakework.data[68], &work->data[68], 8);
  4649. // Set prevblock to winning hash (swap32'd)
  4650. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  4651. test_work_current(&fakework);
  4652. }
  4653. }
  4654. else
  4655. if (!hash_target_check(work->hash, work->target))
  4656. {
  4657. // This was submitted despite failing the proper target
  4658. // Quietly ignore the reject
  4659. char reason[32];
  4660. put_in_parens(reason, sizeof(reason), extract_reject_reason(val, res, err, work));
  4661. applog(LOG_DEBUG, "Share above target rejected%s by pool %u as expected, ignoring", reason, pool->pool_no);
  4662. // Stratum error 23 is "low difficulty share", which suggests this pool tracks job difficulty correctly.
  4663. // Therefore, we disable retrodiff if it was enabled-by-default.
  4664. if (pool->pool_diff_effective_retroactively == BTS_UNKNOWN) {
  4665. json_t *errnum;
  4666. if (work->stratum && err && json_is_array(err) && json_array_size(err) >= 1 && (errnum = json_array_get(err, 0)) && json_is_number(errnum) && ((int)json_number_value(errnum)) == 23) {
  4667. applog(LOG_DEBUG, "Disabling retroactive difficulty adjustments for pool %u", pool->pool_no);
  4668. pool->pool_diff_effective_retroactively = false;
  4669. }
  4670. }
  4671. } else {
  4672. mutex_lock(&stats_lock);
  4673. cgpu->rejected++;
  4674. total_rejected++;
  4675. pool->rejected++;
  4676. cgpu->diff_rejected += work->work_difficulty;
  4677. total_diff_rejected += work->work_difficulty;
  4678. pool->diff_rejected += work->work_difficulty;
  4679. pool->seq_rejects++;
  4680. mutex_unlock(&stats_lock);
  4681. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  4682. if (!QUIET) {
  4683. char disposition[36] = "reject";
  4684. char reason[32];
  4685. const char *reasontmp = extract_reject_reason(val, res, err, work);
  4686. int n = put_in_parens(reason, sizeof(reason), reasontmp);
  4687. if (reason[0])
  4688. snprintf(&disposition[6], sizeof(disposition) - 6, ":%.*s", n - 3, &reason[2]);
  4689. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  4690. sharelog(disposition, work);
  4691. }
  4692. /* Once we have more than a nominal amount of sequential rejects,
  4693. * at least 10 and more than 3 mins at the current utility,
  4694. * disable the pool because some pool error is likely to have
  4695. * ensued. Do not do this if we know the share just happened to
  4696. * be stale due to networking delays.
  4697. */
  4698. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  4699. double utility = total_accepted / total_secs * 60;
  4700. if (pool->seq_rejects > utility * 3) {
  4701. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  4702. pool->pool_no, pool->seq_rejects);
  4703. disable_pool(pool, POOL_REJECTING);
  4704. pool->seq_rejects = 0;
  4705. }
  4706. }
  4707. }
  4708. maybe_local_submit(work);
  4709. }
  4710. static char *submit_upstream_work_request(struct work *work)
  4711. {
  4712. char *hexstr = NULL;
  4713. char *s, *sd;
  4714. struct pool *pool = work->pool;
  4715. if (work->tr)
  4716. {
  4717. blktemplate_t * const tmpl = work->tr->tmpl;
  4718. json_t *req;
  4719. unsigned char data[80];
  4720. swap32yes(data, work->data, 80 / 4);
  4721. #if BLKMAKER_VERSION > 3
  4722. if (work->do_foreign_submit)
  4723. req = blkmk_submit_foreign_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4724. else
  4725. #endif
  4726. req = blkmk_submit_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4727. s = json_dumps(req, 0);
  4728. json_decref(req);
  4729. sd = malloc(161);
  4730. bin2hex(sd, data, 80);
  4731. } else {
  4732. /* build hex string */
  4733. hexstr = malloc((sizeof(work->data) * 2) + 1);
  4734. bin2hex(hexstr, work->data, sizeof(work->data));
  4735. /* build JSON-RPC request */
  4736. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  4737. s = realloc_strcat(s, hexstr);
  4738. s = realloc_strcat(s, "\" ], \"id\":1}");
  4739. free(hexstr);
  4740. sd = s;
  4741. }
  4742. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  4743. if (work->tr)
  4744. free(sd);
  4745. else
  4746. s = realloc_strcat(s, "\n");
  4747. return s;
  4748. }
  4749. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  4750. json_t *res, *err;
  4751. bool rc = false;
  4752. int thr_id = work->thr_id;
  4753. struct pool *pool = work->pool;
  4754. struct timeval tv_submit_reply;
  4755. time_t ts_submit_reply;
  4756. char worktime[200] = "";
  4757. cgtime(&tv_submit_reply);
  4758. ts_submit_reply = time(NULL);
  4759. if (unlikely(!val)) {
  4760. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  4761. if (!pool_tset(pool, &pool->submit_fail)) {
  4762. total_ro++;
  4763. pool->remotefail_occasions++;
  4764. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  4765. }
  4766. goto out;
  4767. } else if (pool_tclear(pool, &pool->submit_fail))
  4768. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4769. res = json_object_get(val, "result");
  4770. err = json_object_get(val, "error");
  4771. if (!QUIET) {
  4772. if (opt_worktime) {
  4773. char workclone[20];
  4774. struct tm _tm;
  4775. struct tm *tm, tm_getwork, tm_submit_reply;
  4776. tm = &_tm;
  4777. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  4778. (struct timeval *)&(work->tv_getwork));
  4779. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  4780. (struct timeval *)&(work->tv_getwork_reply));
  4781. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  4782. (struct timeval *)&(work->tv_work_start));
  4783. double work_to_submit = tdiff(ptv_submit,
  4784. (struct timeval *)&(work->tv_work_found));
  4785. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  4786. int diffplaces = 3;
  4787. localtime_r(&work->ts_getwork, tm);
  4788. memcpy(&tm_getwork, tm, sizeof(struct tm));
  4789. localtime_r(&ts_submit_reply, tm);
  4790. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  4791. if (work->clone) {
  4792. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  4793. tdiff((struct timeval *)&(work->tv_cloned),
  4794. (struct timeval *)&(work->tv_getwork_reply)));
  4795. }
  4796. else
  4797. strcpy(workclone, "O");
  4798. if (work->work_difficulty < 1)
  4799. diffplaces = 6;
  4800. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  4801. const uint8_t * const prevblkhash = &work->data[4];
  4802. snprintf(worktime, sizeof(worktime),
  4803. " <-%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",
  4804. (unsigned long)be32toh(((uint32_t *)prevblkhash)[7 - malgo->worktime_skip_prevblk_u32]),
  4805. (unsigned long)be32toh(((uint32_t *)prevblkhash)[6 - malgo->worktime_skip_prevblk_u32]),
  4806. work->getwork_mode, diffplaces, work->work_difficulty,
  4807. tm_getwork.tm_hour, tm_getwork.tm_min,
  4808. tm_getwork.tm_sec, getwork_time, workclone,
  4809. getwork_to_work, work_time, work_to_submit, submit_time,
  4810. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  4811. tm_submit_reply.tm_sec);
  4812. }
  4813. }
  4814. share_result(val, res, err, work, resubmit, worktime);
  4815. if (!opt_realquiet)
  4816. print_status(thr_id);
  4817. if (!want_per_device_stats) {
  4818. char logline[256];
  4819. struct cgpu_info *cgpu;
  4820. cgpu = get_thr_cgpu(thr_id);
  4821. get_statline(logline, sizeof(logline), cgpu);
  4822. applog(LOG_INFO, "%s", logline);
  4823. }
  4824. json_decref(val);
  4825. rc = true;
  4826. out:
  4827. return rc;
  4828. }
  4829. /* Specifies whether we can use this pool for work or not. */
  4830. static bool pool_unworkable(const struct pool * const pool)
  4831. {
  4832. if (pool->idle)
  4833. return true;
  4834. if (pool->enabled != POOL_ENABLED)
  4835. return true;
  4836. if (pool->has_stratum && !pool->stratum_active)
  4837. return true;
  4838. return false;
  4839. }
  4840. static struct pool *priority_pool(int);
  4841. static bool pool_unusable(struct pool *);
  4842. static
  4843. bool pool_actively_desired(const struct pool * const pool, const struct pool *cp)
  4844. {
  4845. if (pool->enabled != POOL_ENABLED)
  4846. return false;
  4847. if (pool_strategy == POOL_LOADBALANCE && pool->quota)
  4848. return true;
  4849. if (pool_strategy == POOL_BALANCE && !pool->failover_only)
  4850. return true;
  4851. if (!cp)
  4852. cp = current_pool();
  4853. if (pool == cp)
  4854. return true;
  4855. // If we are the highest priority, workable pool for a given algorithm, we are needed
  4856. struct mining_algorithm * const malgo = pool->goal->malgo;
  4857. for (int i = 0; i < total_pools; ++i)
  4858. {
  4859. struct pool * const other_pool = priority_pool(i);
  4860. if (other_pool == pool)
  4861. return true;
  4862. if (pool_unusable(other_pool))
  4863. continue;
  4864. if (other_pool->goal->malgo == malgo)
  4865. break;
  4866. }
  4867. return false;
  4868. }
  4869. static
  4870. bool pool_actively_in_use(const struct pool * const pool, const struct pool *cp)
  4871. {
  4872. return (!pool_unworkable(pool)) && pool_actively_desired(pool, cp);
  4873. }
  4874. static
  4875. bool pool_supports_block_change_notification(struct pool * const pool)
  4876. {
  4877. return pool->has_stratum || pool->lp_url;
  4878. }
  4879. static
  4880. bool pool_has_active_block_change_notification(struct pool * const pool)
  4881. {
  4882. return pool->stratum_active || pool->lp_active;
  4883. }
  4884. static struct pool *_select_longpoll_pool(struct pool *, bool(*)(struct pool *));
  4885. #define select_longpoll_pool(pool) _select_longpoll_pool(pool, pool_supports_block_change_notification)
  4886. #define pool_active_lp_pool(pool) _select_longpoll_pool(pool, pool_has_active_block_change_notification)
  4887. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  4888. * rolling average per 10 minutes and if pools start getting more, it biases
  4889. * away from them to distribute work evenly. The share count is reset to the
  4890. * rolling average every 10 minutes to not send all work to one pool after it
  4891. * has been disabled/out for an extended period. */
  4892. static
  4893. struct pool *select_balanced(struct pool *cp, struct mining_algorithm * const malgo)
  4894. {
  4895. int i, lowest = cp->shares;
  4896. struct pool *ret = cp, *failover_pool = NULL;
  4897. for (i = 0; i < total_pools; i++) {
  4898. struct pool *pool = pools[i];
  4899. if (malgo && pool->goal->malgo != malgo)
  4900. continue;
  4901. if (pool_unworkable(pool))
  4902. continue;
  4903. if (pool->failover_only)
  4904. {
  4905. BFGINIT(failover_pool, pool);
  4906. continue;
  4907. }
  4908. if (pool->shares < lowest) {
  4909. lowest = pool->shares;
  4910. ret = pool;
  4911. }
  4912. }
  4913. if (malgo && ret->goal->malgo != malgo)
  4914. // Yes, we want failover_pool even if it's NULL
  4915. ret = failover_pool;
  4916. else
  4917. if (pool_unworkable(ret) && failover_pool)
  4918. ret = failover_pool;
  4919. if (ret)
  4920. ++ret->shares;
  4921. return ret;
  4922. }
  4923. static
  4924. struct pool *select_loadbalance(struct mining_algorithm * const malgo)
  4925. {
  4926. static int rotating_pool = 0;
  4927. struct pool *pool;
  4928. bool avail = false;
  4929. int tested, i, rpsave;
  4930. for (i = 0; i < total_pools; i++) {
  4931. struct pool *tp = pools[i];
  4932. if (tp->quota_used < tp->quota_gcd) {
  4933. avail = true;
  4934. break;
  4935. }
  4936. }
  4937. /* There are no pools with quota, so reset them. */
  4938. if (!avail) {
  4939. for (i = 0; i < total_pools; i++)
  4940. {
  4941. struct pool * const tp = pools[i];
  4942. tp->quota_used -= tp->quota_gcd;
  4943. }
  4944. if (++rotating_pool >= total_pools)
  4945. rotating_pool = 0;
  4946. }
  4947. /* Try to find the first pool in the rotation that is usable */
  4948. // Look for the lowest integer quota_used / quota_gcd in case we are imbalanced by algorithm demands
  4949. struct pool *pool_lowest = NULL;
  4950. int lowest = INT_MAX;
  4951. rpsave = rotating_pool;
  4952. for (tested = 0; tested < total_pools; ++tested)
  4953. {
  4954. pool = pools[rotating_pool];
  4955. if (malgo && pool->goal->malgo != malgo)
  4956. goto continue_tested;
  4957. if (pool->quota_used < pool->quota_gcd)
  4958. {
  4959. ++pool->quota_used;
  4960. if (!pool_unworkable(pool))
  4961. goto out;
  4962. /* Failover-only flag for load-balance means distribute
  4963. * unused quota to priority pool 0. */
  4964. if (opt_fail_only)
  4965. priority_pool(0)->quota_used--;
  4966. }
  4967. if (malgo)
  4968. {
  4969. const int count = pool->quota_used / pool->quota_gcd;
  4970. if (count < lowest)
  4971. {
  4972. pool_lowest = pool;
  4973. lowest = count;
  4974. }
  4975. }
  4976. continue_tested: ;
  4977. if (++rotating_pool >= total_pools)
  4978. rotating_pool = 0;
  4979. }
  4980. // Even if pool_lowest is NULL, we want to return that to indicate failure
  4981. // Note it isn't possible to get here if !malgo
  4982. pool = pool_lowest;
  4983. out: ;
  4984. // Restore rotating_pool static, so malgo searches don't affect the usual load balancing
  4985. if (malgo)
  4986. rotating_pool = rpsave;
  4987. return pool;
  4988. }
  4989. static
  4990. struct pool *select_failover(struct mining_algorithm * const malgo)
  4991. {
  4992. int i;
  4993. for (i = 0; i < total_pools; i++) {
  4994. struct pool *tp = priority_pool(i);
  4995. if (malgo && tp->goal->malgo != malgo)
  4996. continue;
  4997. if (!pool_unusable(tp)) {
  4998. return tp;
  4999. }
  5000. }
  5001. return NULL;
  5002. }
  5003. static bool pool_active(struct pool *, bool pinging);
  5004. static void pool_died(struct pool *);
  5005. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  5006. * it has any quota left. */
  5007. static inline struct pool *select_pool(bool lagging, struct mining_algorithm * const malgo)
  5008. {
  5009. struct pool *pool = NULL, *cp;
  5010. retry:
  5011. cp = current_pool();
  5012. if (pool_strategy == POOL_BALANCE) {
  5013. pool = select_balanced(cp, malgo);
  5014. if ((!pool) || pool_unworkable(pool))
  5015. goto simple_failover;
  5016. goto out;
  5017. }
  5018. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  5019. if (malgo && cp->goal->malgo != malgo)
  5020. goto simple_failover;
  5021. pool = cp;
  5022. goto out;
  5023. } else
  5024. pool = select_loadbalance(malgo);
  5025. simple_failover:
  5026. /* If there are no alive pools with quota, choose according to
  5027. * priority. */
  5028. if (!pool) {
  5029. pool = select_failover(malgo);
  5030. }
  5031. /* If still nothing is usable, use the current pool */
  5032. if (!pool)
  5033. {
  5034. if (malgo && cp->goal->malgo != malgo)
  5035. {
  5036. applog(LOG_DEBUG, "Failed to select pool for specific mining algorithm '%s'", malgo->name);
  5037. return NULL;
  5038. }
  5039. pool = cp;
  5040. }
  5041. out:
  5042. if (!pool_actively_in_use(pool, cp))
  5043. {
  5044. if (!pool_active(pool, false))
  5045. {
  5046. pool_died(pool);
  5047. goto retry;
  5048. }
  5049. pool_tclear(pool, &pool->idle);
  5050. }
  5051. applog(LOG_DEBUG, "Selecting pool %d for %s%swork", pool->pool_no, malgo ? malgo->name : "", malgo ? " " : "");
  5052. return pool;
  5053. }
  5054. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  5055. double target_diff(const unsigned char *target)
  5056. {
  5057. double targ = 0;
  5058. signed int i;
  5059. for (i = 31; i >= 0; --i)
  5060. targ = (targ * 0x100) + target[i];
  5061. return DIFFEXACTONE / (targ ?: 1);
  5062. }
  5063. /*
  5064. * Calculate the work share difficulty
  5065. */
  5066. static void calc_diff(struct work *work, int known)
  5067. {
  5068. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  5069. double difficulty;
  5070. if (!known) {
  5071. work->work_difficulty = target_diff(work->target);
  5072. } else
  5073. work->work_difficulty = known;
  5074. difficulty = work->work_difficulty;
  5075. pool_stats->last_diff = difficulty;
  5076. suffix_string(difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  5077. if (difficulty == pool_stats->min_diff)
  5078. pool_stats->min_diff_count++;
  5079. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  5080. pool_stats->min_diff = difficulty;
  5081. pool_stats->min_diff_count = 1;
  5082. }
  5083. if (difficulty == pool_stats->max_diff)
  5084. pool_stats->max_diff_count++;
  5085. else if (difficulty > pool_stats->max_diff) {
  5086. pool_stats->max_diff = difficulty;
  5087. pool_stats->max_diff_count = 1;
  5088. }
  5089. }
  5090. static void gen_stratum_work(struct pool *, struct work *);
  5091. static void pool_update_work_restart_time(struct pool *);
  5092. static void restart_threads(void);
  5093. static uint32_t benchmark_blkhdr[20];
  5094. static const int benchmark_update_interval = 1;
  5095. static
  5096. void *benchmark_intense_work_update_thread(void *userp)
  5097. {
  5098. pthread_detach(pthread_self());
  5099. RenameThread("benchmark-intense");
  5100. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5101. struct pool * const pool = userp;
  5102. struct stratum_work * const swork = &pool->swork;
  5103. uint8_t * const blkhdr = swork->header1;
  5104. while (true)
  5105. {
  5106. sleep(benchmark_update_interval);
  5107. cg_wlock(&pool->data_lock);
  5108. for (int i = 36; --i >= 0; )
  5109. if (++blkhdr[i])
  5110. break;
  5111. cg_wunlock(&pool->data_lock);
  5112. struct work *work = make_work();
  5113. gen_stratum_work(pool, work);
  5114. pool->swork.work_restart_id = ++pool->work_restart_id;
  5115. pool_update_work_restart_time(pool);
  5116. test_work_current(work);
  5117. free_work(work);
  5118. restart_threads();
  5119. }
  5120. return NULL;
  5121. }
  5122. static
  5123. void setup_benchmark_pool()
  5124. {
  5125. struct pool *pool;
  5126. want_longpoll = false;
  5127. // Temporarily disable opt_benchmark to avoid auto-removal
  5128. opt_benchmark = false;
  5129. pool = add_pool();
  5130. opt_benchmark = true;
  5131. pool->rpc_url = malloc(255);
  5132. strcpy(pool->rpc_url, "Benchmark");
  5133. pool_set_uri(pool, pool->rpc_url);
  5134. pool->rpc_user = pool->rpc_url;
  5135. pool->rpc_pass = pool->rpc_url;
  5136. enable_pool(pool);
  5137. pool->idle = false;
  5138. successful_connect = true;
  5139. {
  5140. uint32_t * const blkhdr = benchmark_blkhdr;
  5141. blkhdr[2] = htobe32(1);
  5142. blkhdr[17] = htobe32(0x7fffffff); // timestamp
  5143. blkhdr[18] = htobe32(0x1700ffff); // "bits"
  5144. }
  5145. {
  5146. struct stratum_work * const swork = &pool->swork;
  5147. const int branchcount = 15; // 1 MB block
  5148. const size_t branchdatasz = branchcount * 0x20;
  5149. const size_t coinbase_sz = (opt_benchmark_intense ? 250 : 6) * 1024;
  5150. bytes_resize(&swork->coinbase, coinbase_sz);
  5151. memset(bytes_buf(&swork->coinbase), '\xff', coinbase_sz);
  5152. swork->nonce2_offset = 0;
  5153. bytes_resize(&swork->merkle_bin, branchdatasz);
  5154. memset(bytes_buf(&swork->merkle_bin), '\xff', branchdatasz);
  5155. swork->merkles = branchcount;
  5156. swork->header1[0] = '\xff';
  5157. memset(&swork->header1[1], '\0', 34);
  5158. swork->header1[35] = '\x01';
  5159. swork->ntime = 0x7fffffff;
  5160. timer_unset(&swork->tv_received);
  5161. memcpy(swork->diffbits, "\x17\0\xff\xff", 4);
  5162. const struct mining_goal_info * const goal = get_mining_goal("default");
  5163. const struct mining_algorithm * const malgo = goal->malgo;
  5164. set_target_to_pdiff(swork->target, malgo->reasonable_low_nonce_diff);
  5165. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  5166. pool->nonce2 = 0;
  5167. }
  5168. if (opt_benchmark_intense)
  5169. {
  5170. pthread_t pth;
  5171. if (unlikely(pthread_create(&pth, NULL, benchmark_intense_work_update_thread, pool)))
  5172. applog(LOG_WARNING, "Failed to start benchmark intense work update thread");
  5173. }
  5174. }
  5175. void get_benchmark_work(struct work *work, bool use_swork)
  5176. {
  5177. if (use_swork)
  5178. {
  5179. struct timeval tv_now;
  5180. timer_set_now(&tv_now);
  5181. gen_stratum_work(pools[0], work);
  5182. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  5183. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  5184. return;
  5185. }
  5186. struct pool * const pool = pools[0];
  5187. uint32_t * const blkhdr = benchmark_blkhdr;
  5188. for (int i = 16; i >= 0; --i)
  5189. if (++blkhdr[i])
  5190. break;
  5191. memcpy(&work->data[ 0], blkhdr, 80);
  5192. memcpy(&work->data[80], workpadding_bin, 48);
  5193. char hex[161];
  5194. bin2hex(hex, work->data, 80);
  5195. applog(LOG_DEBUG, "Generated benchmark header %s", hex);
  5196. calc_midstate(work);
  5197. memcpy(work->target, pool->swork.target, sizeof(work->target));
  5198. work->mandatory = true;
  5199. work->pool = pools[0];
  5200. cgtime(&work->tv_getwork);
  5201. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  5202. copy_time(&work->tv_staged, &work->tv_getwork);
  5203. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  5204. calc_diff(work, 0);
  5205. work_set_simple_ntime_roll_limit(work, 60, &work->tv_getwork);
  5206. }
  5207. static void wake_gws(void);
  5208. static void update_last_work(struct work *work)
  5209. {
  5210. if (!work->tr)
  5211. // Only save GBT jobs, since rollntime isn't coordinated well yet
  5212. return;
  5213. struct pool *pool = work->pool;
  5214. mutex_lock(&pool->last_work_lock);
  5215. if (pool->last_work_copy)
  5216. free_work(pool->last_work_copy);
  5217. pool->last_work_copy = copy_work(work);
  5218. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  5219. mutex_unlock(&pool->last_work_lock);
  5220. }
  5221. static
  5222. void gbt_req_target(json_t *req)
  5223. {
  5224. json_t *j;
  5225. json_t *n;
  5226. if (!request_target_str)
  5227. return;
  5228. j = json_object_get(req, "params");
  5229. if (!j)
  5230. {
  5231. n = json_array();
  5232. if (!n)
  5233. return;
  5234. if (json_object_set_new(req, "params", n))
  5235. goto erradd;
  5236. j = n;
  5237. }
  5238. n = json_array_get(j, 0);
  5239. if (!n)
  5240. {
  5241. n = json_object();
  5242. if (!n)
  5243. return;
  5244. if (json_array_append_new(j, n))
  5245. goto erradd;
  5246. }
  5247. j = n;
  5248. n = json_string(request_target_str);
  5249. if (!n)
  5250. return;
  5251. if (json_object_set_new(j, "target", n))
  5252. goto erradd;
  5253. return;
  5254. erradd:
  5255. json_decref(n);
  5256. }
  5257. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe, struct pool * const pool)
  5258. {
  5259. char *rpc_req;
  5260. clean_work(work);
  5261. switch (proto) {
  5262. case PLP_GETWORK:
  5263. work->getwork_mode = GETWORK_MODE_POOL;
  5264. return strdup(getwork_req);
  5265. case PLP_GETBLOCKTEMPLATE:
  5266. work->getwork_mode = GETWORK_MODE_GBT;
  5267. blktemplate_t * const tmpl = blktmpl_create();
  5268. if (!tmpl)
  5269. goto gbtfail2;
  5270. work->tr = tmpl_makeref(tmpl);
  5271. gbt_capabilities_t caps = blktmpl_addcaps(tmpl);
  5272. if (!caps)
  5273. goto gbtfail;
  5274. caps |= GBT_LONGPOLL;
  5275. #if BLKMAKER_VERSION > 1
  5276. const struct mining_goal_info * const goal = pool->goal;
  5277. if (goal->generation_script || goal_has_at_least_one_getcbaddr(goal))
  5278. caps |= GBT_CBVALUE;
  5279. #endif
  5280. json_t *req = blktmpl_request_jansson(caps, lpid);
  5281. if (!req)
  5282. goto gbtfail;
  5283. if (probe)
  5284. gbt_req_target(req);
  5285. rpc_req = json_dumps(req, 0);
  5286. if (!rpc_req)
  5287. goto gbtfail;
  5288. json_decref(req);
  5289. return rpc_req;
  5290. default:
  5291. return NULL;
  5292. }
  5293. return NULL;
  5294. gbtfail:
  5295. tmpl_decref(work->tr);
  5296. work->tr = NULL;
  5297. gbtfail2:
  5298. return NULL;
  5299. }
  5300. #define prepare_rpc_req(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, false, pool)
  5301. #define prepare_rpc_req_probe(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, true, pool)
  5302. static const char *pool_protocol_name(enum pool_protocol proto)
  5303. {
  5304. switch (proto) {
  5305. case PLP_GETBLOCKTEMPLATE:
  5306. return "getblocktemplate";
  5307. case PLP_GETWORK:
  5308. return "getwork";
  5309. default:
  5310. return "UNKNOWN";
  5311. }
  5312. }
  5313. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  5314. {
  5315. switch (proto) {
  5316. case PLP_GETBLOCKTEMPLATE:
  5317. if (want_getwork)
  5318. return PLP_GETWORK;
  5319. default:
  5320. return PLP_NONE;
  5321. }
  5322. }
  5323. static bool get_upstream_work(struct work *work, CURL *curl)
  5324. {
  5325. struct pool *pool = work->pool;
  5326. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  5327. struct timeval tv_elapsed;
  5328. json_t *val = NULL;
  5329. bool rc = false;
  5330. char *url;
  5331. enum pool_protocol proto;
  5332. char *rpc_req;
  5333. if (pool->proto == PLP_NONE)
  5334. pool->proto = PLP_GETBLOCKTEMPLATE;
  5335. tryagain:
  5336. rpc_req = prepare_rpc_req(work, pool->proto, NULL, pool);
  5337. work->pool = pool;
  5338. if (!rpc_req)
  5339. return false;
  5340. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  5341. url = pool->rpc_url;
  5342. cgtime(&work->tv_getwork);
  5343. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  5344. false, &work->rolltime, pool, false);
  5345. pool_stats->getwork_attempts++;
  5346. free(rpc_req);
  5347. if (likely(val)) {
  5348. rc = work_decode(pool, work, val);
  5349. if (unlikely(!rc))
  5350. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  5351. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  5352. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  5353. pool->proto = proto;
  5354. goto tryagain;
  5355. } else
  5356. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  5357. cgtime(&work->tv_getwork_reply);
  5358. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  5359. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  5360. pool_stats->getwork_wait_rolling /= 1.63;
  5361. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  5362. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  5363. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  5364. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  5365. }
  5366. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  5367. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  5368. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  5369. }
  5370. pool_stats->getwork_calls++;
  5371. work->pool = pool;
  5372. work->longpoll = false;
  5373. calc_diff(work, 0);
  5374. total_getworks++;
  5375. pool->getwork_requested++;
  5376. if (rc)
  5377. update_last_work(work);
  5378. if (likely(val))
  5379. json_decref(val);
  5380. return rc;
  5381. }
  5382. #ifdef HAVE_CURSES
  5383. static void disable_curses(void)
  5384. {
  5385. if (curses_active_locked()) {
  5386. use_curses = false;
  5387. curses_active = false;
  5388. leaveok(logwin, false);
  5389. leaveok(statuswin, false);
  5390. leaveok(mainwin, false);
  5391. nocbreak();
  5392. echo();
  5393. delwin(logwin);
  5394. delwin(statuswin);
  5395. delwin(mainwin);
  5396. endwin();
  5397. #ifdef WIN32
  5398. // Move the cursor to after curses output.
  5399. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  5400. CONSOLE_SCREEN_BUFFER_INFO csbi;
  5401. COORD coord;
  5402. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  5403. coord.X = 0;
  5404. coord.Y = csbi.dwSize.Y - 1;
  5405. SetConsoleCursorPosition(hout, coord);
  5406. }
  5407. #endif
  5408. unlock_curses();
  5409. }
  5410. }
  5411. #endif
  5412. static void __kill_work(void)
  5413. {
  5414. struct cgpu_info *cgpu;
  5415. struct thr_info *thr;
  5416. int i;
  5417. if (!successful_connect)
  5418. return;
  5419. applog(LOG_INFO, "Received kill message");
  5420. shutting_down = true;
  5421. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  5422. notifier_wake(submit_waiting_notifier);
  5423. #ifdef USE_LIBMICROHTTPD
  5424. httpsrv_stop();
  5425. #endif
  5426. applog(LOG_DEBUG, "Killing off watchpool thread");
  5427. /* Kill the watchpool thread */
  5428. thr = &control_thr[watchpool_thr_id];
  5429. thr_info_cancel(thr);
  5430. applog(LOG_DEBUG, "Killing off watchdog thread");
  5431. /* Kill the watchdog thread */
  5432. thr = &control_thr[watchdog_thr_id];
  5433. thr_info_cancel(thr);
  5434. applog(LOG_DEBUG, "Shutting down mining threads");
  5435. for (i = 0; i < mining_threads; i++) {
  5436. thr = get_thread(i);
  5437. if (!thr)
  5438. continue;
  5439. cgpu = thr->cgpu;
  5440. if (!cgpu)
  5441. continue;
  5442. if (!cgpu->threads)
  5443. continue;
  5444. cgpu->shutdown = true;
  5445. thr->work_restart = true;
  5446. notifier_wake(thr->notifier);
  5447. notifier_wake(thr->work_restart_notifier);
  5448. }
  5449. sleep(1);
  5450. applog(LOG_DEBUG, "Killing off mining threads");
  5451. /* Kill the mining threads*/
  5452. for (i = 0; i < mining_threads; i++) {
  5453. thr = get_thread(i);
  5454. if (!thr)
  5455. continue;
  5456. cgpu = thr->cgpu;
  5457. if (cgpu->threads)
  5458. {
  5459. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  5460. thr_info_cancel(thr);
  5461. }
  5462. cgpu->status = LIFE_DEAD2;
  5463. }
  5464. /* Stop the others */
  5465. applog(LOG_DEBUG, "Killing off API thread");
  5466. thr = &control_thr[api_thr_id];
  5467. thr_info_cancel(thr);
  5468. }
  5469. /* This should be the common exit path */
  5470. void kill_work(void)
  5471. {
  5472. __kill_work();
  5473. quit(0, "Shutdown signal received.");
  5474. }
  5475. static
  5476. #ifdef WIN32
  5477. #ifndef _WIN64
  5478. const
  5479. #endif
  5480. #endif
  5481. char **initial_args;
  5482. void _bfg_clean_up(bool);
  5483. void app_restart(void)
  5484. {
  5485. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  5486. __kill_work();
  5487. _bfg_clean_up(true);
  5488. #if defined(unix) || defined(__APPLE__)
  5489. if (forkpid > 0) {
  5490. kill(forkpid, SIGTERM);
  5491. forkpid = 0;
  5492. }
  5493. #endif
  5494. execv(initial_args[0], initial_args);
  5495. applog(LOG_WARNING, "Failed to restart application");
  5496. }
  5497. static void sighandler(int __maybe_unused sig)
  5498. {
  5499. /* Restore signal handlers so we can still quit if kill_work fails */
  5500. sigaction(SIGTERM, &termhandler, NULL);
  5501. sigaction(SIGINT, &inthandler, NULL);
  5502. kill_work();
  5503. }
  5504. static void start_longpoll(void);
  5505. static void stop_longpoll(void);
  5506. /* Called with pool_lock held. Recruit an extra curl if none are available for
  5507. * this pool. */
  5508. static void recruit_curl(struct pool *pool)
  5509. {
  5510. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  5511. if (unlikely(!ce))
  5512. quit(1, "Failed to calloc in recruit_curl");
  5513. ce->curl = curl_easy_init();
  5514. if (unlikely(!ce->curl))
  5515. quit(1, "Failed to init in recruit_curl");
  5516. LL_PREPEND(pool->curllist, ce);
  5517. pool->curls++;
  5518. }
  5519. /* Grab an available curl if there is one. If not, then recruit extra curls
  5520. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  5521. * and there are already 5 curls in circulation. Limit total number to the
  5522. * number of mining threads per pool as well to prevent blasting a pool during
  5523. * network delays/outages. */
  5524. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  5525. {
  5526. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  5527. bool recruited = false;
  5528. struct curl_ent *ce;
  5529. mutex_lock(&pool->pool_lock);
  5530. retry:
  5531. if (!pool->curls) {
  5532. recruit_curl(pool);
  5533. recruited = true;
  5534. } else if (!pool->curllist) {
  5535. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  5536. if (!blocking) {
  5537. mutex_unlock(&pool->pool_lock);
  5538. return NULL;
  5539. }
  5540. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  5541. goto retry;
  5542. } else {
  5543. recruit_curl(pool);
  5544. recruited = true;
  5545. }
  5546. }
  5547. ce = pool->curllist;
  5548. LL_DELETE(pool->curllist, ce);
  5549. mutex_unlock(&pool->pool_lock);
  5550. if (recruited)
  5551. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  5552. return ce;
  5553. }
  5554. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  5555. {
  5556. return pop_curl_entry3(pool, blocking ? 1 : 0);
  5557. }
  5558. __maybe_unused
  5559. static struct curl_ent *pop_curl_entry(struct pool *pool)
  5560. {
  5561. return pop_curl_entry3(pool, 1);
  5562. }
  5563. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  5564. {
  5565. mutex_lock(&pool->pool_lock);
  5566. if (!ce || !ce->curl)
  5567. quithere(1, "Attempted to add NULL");
  5568. LL_PREPEND(pool->curllist, ce);
  5569. cgtime(&ce->tv);
  5570. pthread_cond_broadcast(&pool->cr_cond);
  5571. mutex_unlock(&pool->pool_lock);
  5572. }
  5573. bool stale_work(struct work *work, bool share);
  5574. static inline bool should_roll(struct work *work)
  5575. {
  5576. struct timeval now;
  5577. time_t expiry;
  5578. if (!pool_actively_in_use(work->pool, NULL))
  5579. return false;
  5580. if (stale_work(work, false))
  5581. return false;
  5582. if (work->rolltime > opt_scantime)
  5583. expiry = work->rolltime;
  5584. else
  5585. expiry = opt_scantime;
  5586. expiry = expiry * 2 / 3;
  5587. /* We shouldn't roll if we're unlikely to get one shares' duration
  5588. * work out of doing so */
  5589. cgtime(&now);
  5590. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  5591. return false;
  5592. return true;
  5593. }
  5594. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  5595. * reject blocks as invalid. */
  5596. static inline bool can_roll(struct work *work)
  5597. {
  5598. if (work->stratum)
  5599. return false;
  5600. if (!(work->pool && !work->clone))
  5601. return false;
  5602. if (work->tr)
  5603. {
  5604. if (stale_work(work, false))
  5605. return false;
  5606. return blkmk_work_left(work->tr->tmpl);
  5607. }
  5608. return (work->rolltime &&
  5609. work->rolls < 7000 && !stale_work(work, false));
  5610. }
  5611. static void roll_work(struct work *work)
  5612. {
  5613. if (work->tr)
  5614. {
  5615. struct timeval tv_now;
  5616. cgtime(&tv_now);
  5617. if (blkmk_get_data(work->tr->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  5618. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  5619. swap32yes(work->data, work->data, 80 / 4);
  5620. calc_midstate(work);
  5621. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  5622. } else {
  5623. uint32_t *work_ntime;
  5624. uint32_t ntime;
  5625. work_ntime = (uint32_t *)(work->data + 68);
  5626. ntime = be32toh(*work_ntime);
  5627. ntime++;
  5628. *work_ntime = htobe32(ntime);
  5629. work_set_simple_ntime_roll_limit(work, 0, &work->ntime_roll_limits.tv_ref);
  5630. applog(LOG_DEBUG, "Successfully rolled time header in work");
  5631. }
  5632. local_work++;
  5633. work->rolls++;
  5634. work->blk.nonce = 0;
  5635. /* This is now a different work item so it needs a different ID for the
  5636. * hashtable */
  5637. work->id = total_work++;
  5638. }
  5639. /* Duplicates any dynamically allocated arrays within the work struct to
  5640. * prevent a copied work struct from freeing ram belonging to another struct */
  5641. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  5642. {
  5643. int id = work->id;
  5644. clean_work(work);
  5645. memcpy(work, base_work, sizeof(struct work));
  5646. /* Keep the unique new id assigned during make_work to prevent copied
  5647. * work from having the same id. */
  5648. work->id = id;
  5649. if (base_work->job_id)
  5650. work->job_id = strdup(base_work->job_id);
  5651. if (base_work->nonce1)
  5652. work->nonce1 = strdup(base_work->nonce1);
  5653. bytes_cpy(&work->nonce2, &base_work->nonce2);
  5654. if (base_work->tr)
  5655. tmpl_incref(base_work->tr);
  5656. if (noffset)
  5657. {
  5658. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  5659. uint32_t ntime = be32toh(*work_ntime);
  5660. ntime += noffset;
  5661. *work_ntime = htobe32(ntime);
  5662. }
  5663. if (work->device_data_dup_func)
  5664. work->device_data = work->device_data_dup_func(work);
  5665. }
  5666. /* Generates a copy of an existing work struct, creating fresh heap allocations
  5667. * for all dynamically allocated arrays within the struct. noffset is used for
  5668. * when a driver has internally rolled the ntime, noffset is a relative value.
  5669. * The macro copy_work() calls this function with an noffset of 0. */
  5670. struct work *copy_work_noffset(const struct work *base_work, int noffset)
  5671. {
  5672. struct work *work = make_work();
  5673. _copy_work(work, base_work, noffset);
  5674. return work;
  5675. }
  5676. void __copy_work(struct work *work, const struct work *base_work)
  5677. {
  5678. _copy_work(work, base_work, 0);
  5679. }
  5680. static struct work *make_clone(struct work *work)
  5681. {
  5682. struct work *work_clone = copy_work(work);
  5683. work_clone->clone = true;
  5684. cgtime((struct timeval *)&(work_clone->tv_cloned));
  5685. work_clone->longpoll = false;
  5686. work_clone->mandatory = false;
  5687. /* Make cloned work appear slightly older to bias towards keeping the
  5688. * master work item which can be further rolled */
  5689. work_clone->tv_staged.tv_sec -= 1;
  5690. return work_clone;
  5691. }
  5692. static void stage_work(struct work *work);
  5693. static bool clone_available(void)
  5694. {
  5695. struct work *work_clone = NULL, *work, *tmp;
  5696. bool cloned = false;
  5697. mutex_lock(stgd_lock);
  5698. if (!staged_rollable)
  5699. goto out_unlock;
  5700. HASH_ITER(hh, staged_work, work, tmp) {
  5701. if (can_roll(work) && should_roll(work)) {
  5702. roll_work(work);
  5703. work_clone = make_clone(work);
  5704. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  5705. roll_work(work);
  5706. cloned = true;
  5707. break;
  5708. }
  5709. }
  5710. out_unlock:
  5711. mutex_unlock(stgd_lock);
  5712. if (cloned) {
  5713. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  5714. stage_work(work_clone);
  5715. }
  5716. return cloned;
  5717. }
  5718. static void pool_died(struct pool *pool)
  5719. {
  5720. mutex_lock(&lp_lock);
  5721. if (!pool_tset(pool, &pool->idle)) {
  5722. cgtime(&pool->tv_idle);
  5723. pthread_cond_broadcast(&lp_cond);
  5724. mutex_unlock(&lp_lock);
  5725. if (pool == current_pool()) {
  5726. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  5727. switch_pools(NULL);
  5728. } else
  5729. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  5730. }
  5731. else
  5732. mutex_unlock(&lp_lock);
  5733. }
  5734. bool stale_work(struct work *work, bool share)
  5735. {
  5736. unsigned work_expiry;
  5737. struct pool *pool;
  5738. uint32_t block_id;
  5739. unsigned getwork_delay;
  5740. block_id = ((uint32_t*)work->data)[1];
  5741. pool = work->pool;
  5742. struct mining_goal_info * const goal = pool->goal;
  5743. struct blockchain_info * const blkchain = goal->blkchain;
  5744. /* Technically the rolltime should be correct but some pools
  5745. * advertise a broken expire= that is lower than a meaningful
  5746. * scantime */
  5747. if (work->rolltime >= opt_scantime || work->tr)
  5748. work_expiry = work->rolltime;
  5749. else
  5750. work_expiry = opt_expiry;
  5751. unsigned max_expiry = (goal->have_longpoll ? opt_expiry_lp : opt_expiry);
  5752. if (work_expiry > max_expiry)
  5753. work_expiry = max_expiry;
  5754. if (share) {
  5755. /* If the share isn't on this pool's latest block, it's stale */
  5756. if (pool->block_id && pool->block_id != block_id)
  5757. {
  5758. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  5759. return true;
  5760. }
  5761. /* If the pool doesn't want old shares, then any found in work before
  5762. * the most recent longpoll is stale */
  5763. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  5764. {
  5765. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5766. return true;
  5767. }
  5768. } else {
  5769. /* If this work isn't for the latest Bitcoin block, it's stale */
  5770. /* But only care about the current pool if failover-only */
  5771. if (enabled_pools <= 1 || opt_fail_only) {
  5772. if (pool->block_id && block_id != pool->block_id)
  5773. {
  5774. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 1 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)blkchain->currentblk->block_id);
  5775. return true;
  5776. }
  5777. } else {
  5778. if (block_id != blkchain->currentblk->block_id)
  5779. {
  5780. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 0 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)blkchain->currentblk->block_id);
  5781. return true;
  5782. }
  5783. }
  5784. /* If the pool has asked us to restart since this work, it's stale */
  5785. if (work->work_restart_id != pool->work_restart_id)
  5786. {
  5787. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5788. return true;
  5789. }
  5790. if (pool->has_stratum && work->job_id) {
  5791. bool same_job;
  5792. if (!pool->stratum_active || !pool->stratum_notify) {
  5793. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  5794. return true;
  5795. }
  5796. same_job = true;
  5797. cg_rlock(&pool->data_lock);
  5798. if (strcmp(work->job_id, pool->swork.job_id))
  5799. same_job = false;
  5800. cg_runlock(&pool->data_lock);
  5801. if (!same_job) {
  5802. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  5803. return true;
  5804. }
  5805. }
  5806. /* Factor in the average getwork delay of this pool, rounding it up to
  5807. * the nearest second */
  5808. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  5809. if (unlikely(work_expiry <= getwork_delay + 5))
  5810. work_expiry = 5;
  5811. else
  5812. work_expiry -= getwork_delay;
  5813. }
  5814. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  5815. if (elapsed_since_staged > work_expiry) {
  5816. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  5817. return true;
  5818. }
  5819. /* If the user only wants strict failover, any work from a pool other than
  5820. * the current one is always considered stale */
  5821. if (opt_fail_only && !share && !work->mandatory && !pool_actively_in_use(pool, NULL))
  5822. {
  5823. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  5824. return true;
  5825. }
  5826. return false;
  5827. }
  5828. double share_diff(const struct work *work)
  5829. {
  5830. double ret;
  5831. bool new_best = false;
  5832. ret = target_diff(work->hash);
  5833. cg_wlock(&control_lock);
  5834. if (unlikely(ret > best_diff)) {
  5835. new_best = true;
  5836. best_diff = ret;
  5837. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5838. }
  5839. if (unlikely(ret > work->pool->best_diff))
  5840. work->pool->best_diff = ret;
  5841. cg_wunlock(&control_lock);
  5842. if (unlikely(new_best))
  5843. applog(LOG_INFO, "New best share: %s", best_share);
  5844. return ret;
  5845. }
  5846. static
  5847. void work_check_for_block(struct work * const work)
  5848. {
  5849. struct pool * const pool = work->pool;
  5850. struct mining_goal_info * const goal = pool->goal;
  5851. work->share_diff = share_diff(work);
  5852. if (unlikely(work->share_diff >= goal->current_diff)) {
  5853. work->block = true;
  5854. work->pool->solved++;
  5855. found_blocks++;
  5856. work->mandatory = true;
  5857. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  5858. }
  5859. }
  5860. static void submit_discard_share2(const char *reason, struct work *work)
  5861. {
  5862. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  5863. sharelog(reason, work);
  5864. mutex_lock(&stats_lock);
  5865. ++total_stale;
  5866. ++cgpu->stale;
  5867. ++(work->pool->stale_shares);
  5868. total_diff_stale += work->work_difficulty;
  5869. cgpu->diff_stale += work->work_difficulty;
  5870. work->pool->diff_stale += work->work_difficulty;
  5871. mutex_unlock(&stats_lock);
  5872. }
  5873. static void submit_discard_share(struct work *work)
  5874. {
  5875. submit_discard_share2("discard", work);
  5876. }
  5877. struct submit_work_state {
  5878. struct work *work;
  5879. bool resubmit;
  5880. struct curl_ent *ce;
  5881. int failures;
  5882. struct timeval tv_staleexpire;
  5883. char *s;
  5884. struct timeval tv_submit;
  5885. struct submit_work_state *next;
  5886. };
  5887. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  5888. {
  5889. long *p_timeout_us = userp;
  5890. const long max_ms = LONG_MAX / 1000;
  5891. if (max_ms < timeout_ms)
  5892. timeout_ms = max_ms;
  5893. *p_timeout_us = timeout_ms * 1000;
  5894. return 0;
  5895. }
  5896. static void sws_has_ce(struct submit_work_state *sws)
  5897. {
  5898. struct pool *pool = sws->work->pool;
  5899. sws->s = submit_upstream_work_request(sws->work);
  5900. cgtime(&sws->tv_submit);
  5901. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5902. }
  5903. static struct submit_work_state *begin_submission(struct work *work)
  5904. {
  5905. struct pool *pool;
  5906. struct submit_work_state *sws = NULL;
  5907. pool = work->pool;
  5908. sws = malloc(sizeof(*sws));
  5909. *sws = (struct submit_work_state){
  5910. .work = work,
  5911. };
  5912. work_check_for_block(work);
  5913. if (stale_work(work, true)) {
  5914. work->stale = true;
  5915. if (opt_submit_stale)
  5916. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  5917. else if (pool->submit_old)
  5918. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  5919. else {
  5920. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  5921. submit_discard_share(work);
  5922. goto out;
  5923. }
  5924. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5925. }
  5926. if (work->stratum) {
  5927. char *s;
  5928. s = malloc(1024);
  5929. sws->s = s;
  5930. } else {
  5931. /* submit solution to bitcoin via JSON-RPC */
  5932. sws->ce = pop_curl_entry2(pool, false);
  5933. if (sws->ce) {
  5934. sws_has_ce(sws);
  5935. } else {
  5936. sws->next = pool->sws_waiting_on_curl;
  5937. pool->sws_waiting_on_curl = sws;
  5938. if (sws->next)
  5939. applog(LOG_DEBUG, "submit_thread queuing submission");
  5940. else
  5941. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  5942. }
  5943. }
  5944. return sws;
  5945. out:
  5946. free(sws);
  5947. return NULL;
  5948. }
  5949. static bool retry_submission(struct submit_work_state *sws)
  5950. {
  5951. struct work *work = sws->work;
  5952. struct pool *pool = work->pool;
  5953. sws->resubmit = true;
  5954. if ((!work->stale) && stale_work(work, true)) {
  5955. work->stale = true;
  5956. if (opt_submit_stale)
  5957. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  5958. else if (pool->submit_old)
  5959. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  5960. else {
  5961. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  5962. submit_discard_share(work);
  5963. return false;
  5964. }
  5965. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5966. }
  5967. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  5968. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  5969. submit_discard_share(work);
  5970. return false;
  5971. }
  5972. else if (work->stale) {
  5973. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  5974. {
  5975. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  5976. submit_discard_share(work);
  5977. return false;
  5978. }
  5979. }
  5980. /* pause, then restart work-request loop */
  5981. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  5982. cgtime(&sws->tv_submit);
  5983. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5984. return true;
  5985. }
  5986. static void free_sws(struct submit_work_state *sws)
  5987. {
  5988. free(sws->s);
  5989. free_work(sws->work);
  5990. free(sws);
  5991. }
  5992. static void *submit_work_thread(__maybe_unused void *userdata)
  5993. {
  5994. int wip = 0;
  5995. CURLM *curlm;
  5996. long curlm_timeout_us = -1;
  5997. struct timeval curlm_timer;
  5998. struct submit_work_state *sws, **swsp;
  5999. struct submit_work_state *write_sws = NULL;
  6000. unsigned tsreduce = 0;
  6001. pthread_detach(pthread_self());
  6002. RenameThread("submit_work");
  6003. applog(LOG_DEBUG, "Creating extra submit work thread");
  6004. curlm = curl_multi_init();
  6005. curlm_timeout_us = -1;
  6006. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  6007. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  6008. fd_set rfds, wfds, efds;
  6009. int maxfd;
  6010. struct timeval tv_timeout, tv_now;
  6011. int n;
  6012. CURLMsg *cm;
  6013. FD_ZERO(&rfds);
  6014. while (1) {
  6015. mutex_lock(&submitting_lock);
  6016. total_submitting -= tsreduce;
  6017. tsreduce = 0;
  6018. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  6019. notifier_read(submit_waiting_notifier);
  6020. }
  6021. // Receive any new submissions
  6022. while (submit_waiting) {
  6023. struct work *work = submit_waiting;
  6024. DL_DELETE(submit_waiting, work);
  6025. if ( (sws = begin_submission(work)) ) {
  6026. if (sws->ce)
  6027. curl_multi_add_handle(curlm, sws->ce->curl);
  6028. else if (sws->s) {
  6029. sws->next = write_sws;
  6030. write_sws = sws;
  6031. }
  6032. ++wip;
  6033. }
  6034. else {
  6035. --total_submitting;
  6036. free_work(work);
  6037. }
  6038. }
  6039. if (unlikely(shutting_down && !wip))
  6040. break;
  6041. mutex_unlock(&submitting_lock);
  6042. FD_ZERO(&rfds);
  6043. FD_ZERO(&wfds);
  6044. FD_ZERO(&efds);
  6045. tv_timeout.tv_sec = -1;
  6046. // Setup cURL with select
  6047. // Need to call perform to ensure the timeout gets updated
  6048. curl_multi_perform(curlm, &n);
  6049. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  6050. if (curlm_timeout_us >= 0)
  6051. {
  6052. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  6053. reduce_timeout_to(&tv_timeout, &curlm_timer);
  6054. }
  6055. // Setup waiting stratum submissions with select
  6056. for (sws = write_sws; sws; sws = sws->next)
  6057. {
  6058. struct pool *pool = sws->work->pool;
  6059. int fd = pool->sock;
  6060. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  6061. continue;
  6062. FD_SET(fd, &wfds);
  6063. set_maxfd(&maxfd, fd);
  6064. }
  6065. // Setup "submit waiting" notifier with select
  6066. FD_SET(submit_waiting_notifier[0], &rfds);
  6067. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  6068. // Wait for something interesting to happen :)
  6069. cgtime(&tv_now);
  6070. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  6071. FD_ZERO(&rfds);
  6072. continue;
  6073. }
  6074. // Handle any stratum ready-to-write results
  6075. for (swsp = &write_sws; (sws = *swsp); ) {
  6076. struct work *work = sws->work;
  6077. struct pool *pool = work->pool;
  6078. int fd = pool->sock;
  6079. bool sessionid_match;
  6080. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  6081. next_write_sws:
  6082. // TODO: Check if stale, possibly discard etc
  6083. swsp = &sws->next;
  6084. continue;
  6085. }
  6086. cg_rlock(&pool->data_lock);
  6087. // NOTE: cgminer only does this check on retries, but BFGMiner does it for even the first/normal submit; therefore, it needs to be such that it always is true on the same connection regardless of session management
  6088. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  6089. sessionid_match = (!pool->swork.nonce1) || !strcmp(work->nonce1, pool->swork.nonce1);
  6090. cg_runlock(&pool->data_lock);
  6091. if (!sessionid_match)
  6092. {
  6093. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  6094. submit_discard_share2("disconnect", work);
  6095. ++tsreduce;
  6096. next_write_sws_del:
  6097. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  6098. FD_CLR(fd, &wfds);
  6099. // Delete sws for this submission, since we're done with it
  6100. *swsp = sws->next;
  6101. free_sws(sws);
  6102. --wip;
  6103. continue;
  6104. }
  6105. char *s = sws->s;
  6106. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  6107. int sshare_id;
  6108. uint32_t nonce;
  6109. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  6110. char noncehex[9];
  6111. char ntimehex[9];
  6112. sshare->work = copy_work(work);
  6113. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  6114. nonce = *((uint32_t *)(work->data + 76));
  6115. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  6116. bin2hex(ntimehex, (void *)&work->data[68], 4);
  6117. mutex_lock(&sshare_lock);
  6118. /* Give the stratum share a unique id */
  6119. sshare_id =
  6120. sshare->id = swork_id++;
  6121. HASH_ADD_INT(stratum_shares, id, sshare);
  6122. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  6123. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  6124. mutex_unlock(&sshare_lock);
  6125. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  6126. if (likely(stratum_send(pool, s, strlen(s)))) {
  6127. if (pool_tclear(pool, &pool->submit_fail))
  6128. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  6129. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  6130. goto next_write_sws_del;
  6131. } else if (!pool_tset(pool, &pool->submit_fail)) {
  6132. // Undo stuff
  6133. mutex_lock(&sshare_lock);
  6134. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  6135. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  6136. if (sshare)
  6137. HASH_DEL(stratum_shares, sshare);
  6138. mutex_unlock(&sshare_lock);
  6139. if (sshare)
  6140. {
  6141. free_work(sshare->work);
  6142. free(sshare);
  6143. }
  6144. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  6145. total_ro++;
  6146. pool->remotefail_occasions++;
  6147. if (!sshare)
  6148. goto next_write_sws_del;
  6149. goto next_write_sws;
  6150. }
  6151. }
  6152. // Handle any cURL activities
  6153. curl_multi_perform(curlm, &n);
  6154. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  6155. if (cm->msg == CURLMSG_DONE)
  6156. {
  6157. bool finished;
  6158. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  6159. curl_multi_remove_handle(curlm, cm->easy_handle);
  6160. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  6161. if (!finished) {
  6162. if (retry_submission(sws))
  6163. curl_multi_add_handle(curlm, sws->ce->curl);
  6164. else
  6165. finished = true;
  6166. }
  6167. if (finished) {
  6168. --wip;
  6169. ++tsreduce;
  6170. struct pool *pool = sws->work->pool;
  6171. if (pool->sws_waiting_on_curl) {
  6172. pool->sws_waiting_on_curl->ce = sws->ce;
  6173. sws_has_ce(pool->sws_waiting_on_curl);
  6174. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  6175. curl_multi_add_handle(curlm, sws->ce->curl);
  6176. } else {
  6177. push_curl_entry(sws->ce, sws->work->pool);
  6178. }
  6179. free_sws(sws);
  6180. }
  6181. }
  6182. }
  6183. }
  6184. assert(!write_sws);
  6185. mutex_unlock(&submitting_lock);
  6186. curl_multi_cleanup(curlm);
  6187. applog(LOG_DEBUG, "submit_work thread exiting");
  6188. return NULL;
  6189. }
  6190. /* Find the pool that currently has the highest priority */
  6191. static struct pool *priority_pool(int choice)
  6192. {
  6193. struct pool *ret = NULL;
  6194. int i;
  6195. for (i = 0; i < total_pools; i++) {
  6196. struct pool *pool = pools[i];
  6197. if (pool->prio == choice) {
  6198. ret = pool;
  6199. break;
  6200. }
  6201. }
  6202. if (unlikely(!ret)) {
  6203. applog(LOG_ERR, "WTF No pool %d found!", choice);
  6204. return pools[choice];
  6205. }
  6206. return ret;
  6207. }
  6208. int prioritize_pools(char *param, int *pid)
  6209. {
  6210. char *ptr, *next;
  6211. int i, pr, prio = 0;
  6212. if (total_pools == 0) {
  6213. return MSG_NOPOOL;
  6214. }
  6215. if (param == NULL || *param == '\0') {
  6216. return MSG_MISPID;
  6217. }
  6218. bool pools_changed[total_pools];
  6219. int new_prio[total_pools];
  6220. for (i = 0; i < total_pools; ++i)
  6221. pools_changed[i] = false;
  6222. next = param;
  6223. while (next && *next) {
  6224. ptr = next;
  6225. next = strchr(ptr, ',');
  6226. if (next)
  6227. *(next++) = '\0';
  6228. i = atoi(ptr);
  6229. if (i < 0 || i >= total_pools) {
  6230. *pid = i;
  6231. return MSG_INVPID;
  6232. }
  6233. if (pools_changed[i]) {
  6234. *pid = i;
  6235. return MSG_DUPPID;
  6236. }
  6237. pools_changed[i] = true;
  6238. new_prio[i] = prio++;
  6239. }
  6240. // Only change them if no errors
  6241. for (i = 0; i < total_pools; i++) {
  6242. if (pools_changed[i])
  6243. pools[i]->prio = new_prio[i];
  6244. }
  6245. // In priority order, cycle through the unchanged pools and append them
  6246. for (pr = 0; pr < total_pools; pr++)
  6247. for (i = 0; i < total_pools; i++) {
  6248. if (!pools_changed[i] && pools[i]->prio == pr) {
  6249. pools[i]->prio = prio++;
  6250. pools_changed[i] = true;
  6251. break;
  6252. }
  6253. }
  6254. if (current_pool()->prio)
  6255. switch_pools(NULL);
  6256. return MSG_POOLPRIO;
  6257. }
  6258. void validate_pool_priorities(void)
  6259. {
  6260. // TODO: this should probably do some sort of logging
  6261. int i, j;
  6262. bool used[total_pools];
  6263. bool valid[total_pools];
  6264. for (i = 0; i < total_pools; i++)
  6265. used[i] = valid[i] = false;
  6266. for (i = 0; i < total_pools; i++) {
  6267. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  6268. if (!used[pools[i]->prio]) {
  6269. valid[i] = true;
  6270. used[pools[i]->prio] = true;
  6271. }
  6272. }
  6273. }
  6274. for (i = 0; i < total_pools; i++) {
  6275. if (!valid[i]) {
  6276. for (j = 0; j < total_pools; j++) {
  6277. if (!used[j]) {
  6278. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  6279. pools[i]->prio = j;
  6280. used[j] = true;
  6281. break;
  6282. }
  6283. }
  6284. }
  6285. }
  6286. }
  6287. static void clear_pool_work(struct pool *pool);
  6288. /* Specifies whether we can switch to this pool or not. */
  6289. static bool pool_unusable(struct pool *pool)
  6290. {
  6291. if (pool->idle)
  6292. return true;
  6293. if (pool->enabled != POOL_ENABLED)
  6294. return true;
  6295. return false;
  6296. }
  6297. void switch_pools(struct pool *selected)
  6298. {
  6299. struct pool *pool, *last_pool, *failover_pool = NULL;
  6300. int i, pool_no, next_pool;
  6301. if (selected)
  6302. enable_pool(selected);
  6303. cg_wlock(&control_lock);
  6304. last_pool = currentpool;
  6305. pool_no = currentpool->pool_no;
  6306. /* Switch selected to pool number 0 and move the rest down */
  6307. if (selected) {
  6308. if (selected->prio != 0) {
  6309. for (i = 0; i < total_pools; i++) {
  6310. pool = pools[i];
  6311. if (pool->prio < selected->prio)
  6312. pool->prio++;
  6313. }
  6314. selected->prio = 0;
  6315. }
  6316. }
  6317. switch (pool_strategy) {
  6318. /* All of these set to the master pool */
  6319. case POOL_BALANCE:
  6320. case POOL_FAILOVER:
  6321. case POOL_LOADBALANCE:
  6322. for (i = 0; i < total_pools; i++) {
  6323. pool = priority_pool(i);
  6324. if (pool_unusable(pool))
  6325. continue;
  6326. pool_no = pool->pool_no;
  6327. break;
  6328. }
  6329. break;
  6330. /* Both of these simply increment and cycle */
  6331. case POOL_ROUNDROBIN:
  6332. case POOL_ROTATE:
  6333. if (selected && !selected->idle) {
  6334. pool_no = selected->pool_no;
  6335. break;
  6336. }
  6337. next_pool = pool_no;
  6338. /* Select the next alive pool */
  6339. for (i = 1; i < total_pools; i++) {
  6340. next_pool++;
  6341. if (next_pool >= total_pools)
  6342. next_pool = 0;
  6343. pool = pools[next_pool];
  6344. if (pool_unusable(pool))
  6345. continue;
  6346. if (pool->failover_only)
  6347. {
  6348. BFGINIT(failover_pool, pool);
  6349. continue;
  6350. }
  6351. pool_no = next_pool;
  6352. break;
  6353. }
  6354. break;
  6355. default:
  6356. break;
  6357. }
  6358. pool = pools[pool_no];
  6359. if (pool_unusable(pool) && failover_pool)
  6360. pool = failover_pool;
  6361. currentpool = pool;
  6362. cg_wunlock(&control_lock);
  6363. mutex_lock(&lp_lock);
  6364. pthread_cond_broadcast(&lp_cond);
  6365. mutex_unlock(&lp_lock);
  6366. /* Set the lagging flag to avoid pool not providing work fast enough
  6367. * messages in failover only mode since we have to get all fresh work
  6368. * as in restart_threads */
  6369. if (opt_fail_only)
  6370. pool_tset(pool, &pool->lagging);
  6371. if (pool != last_pool)
  6372. {
  6373. pool->block_id = 0;
  6374. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  6375. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  6376. if (pool_localgen(pool) || opt_fail_only)
  6377. clear_pool_work(last_pool);
  6378. }
  6379. }
  6380. mutex_lock(&lp_lock);
  6381. pthread_cond_broadcast(&lp_cond);
  6382. mutex_unlock(&lp_lock);
  6383. #ifdef HAVE_CURSES
  6384. update_block_display(false);
  6385. #endif
  6386. }
  6387. static void discard_work(struct work *work)
  6388. {
  6389. if (!work->clone && !work->rolls && !work->mined) {
  6390. if (work->pool) {
  6391. work->pool->discarded_work++;
  6392. work->pool->quota_used--;
  6393. work->pool->works--;
  6394. }
  6395. total_discarded++;
  6396. applog(LOG_DEBUG, "Discarded work");
  6397. } else
  6398. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  6399. free_work(work);
  6400. }
  6401. static bool work_rollable(struct work *);
  6402. static
  6403. void unstage_work(struct work * const work)
  6404. {
  6405. HASH_DEL(staged_work, work);
  6406. --work_mining_algorithm(work)->staged;
  6407. if (work_rollable(work))
  6408. --staged_rollable;
  6409. if (work->spare)
  6410. --staged_spare;
  6411. staged_full = false;
  6412. }
  6413. static void wake_gws(void)
  6414. {
  6415. mutex_lock(stgd_lock);
  6416. pthread_cond_signal(&gws_cond);
  6417. mutex_unlock(stgd_lock);
  6418. }
  6419. static void discard_stale(void)
  6420. {
  6421. struct work *work, *tmp;
  6422. int stale = 0;
  6423. mutex_lock(stgd_lock);
  6424. HASH_ITER(hh, staged_work, work, tmp) {
  6425. if (stale_work(work, false)) {
  6426. unstage_work(work);
  6427. discard_work(work);
  6428. stale++;
  6429. }
  6430. }
  6431. pthread_cond_signal(&gws_cond);
  6432. mutex_unlock(stgd_lock);
  6433. if (stale)
  6434. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  6435. }
  6436. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  6437. {
  6438. bool rv;
  6439. struct timeval tv, orig;
  6440. ldiv_t d;
  6441. d = ldiv(ustime, 1000000);
  6442. tv = (struct timeval){
  6443. .tv_sec = d.quot,
  6444. .tv_usec = d.rem,
  6445. };
  6446. orig = work->tv_staged;
  6447. timersub(&orig, &tv, &work->tv_staged);
  6448. rv = stale_work(work, share);
  6449. work->tv_staged = orig;
  6450. return rv;
  6451. }
  6452. static
  6453. void pool_update_work_restart_time(struct pool * const pool)
  6454. {
  6455. pool->work_restart_time = time(NULL);
  6456. get_timestamp(pool->work_restart_timestamp, sizeof(pool->work_restart_timestamp), pool->work_restart_time);
  6457. }
  6458. static void restart_threads(void)
  6459. {
  6460. struct pool *cp = current_pool();
  6461. int i;
  6462. struct thr_info *thr;
  6463. /* Artificially set the lagging flag to avoid pool not providing work
  6464. * fast enough messages after every long poll */
  6465. pool_tset(cp, &cp->lagging);
  6466. /* Discard staged work that is now stale */
  6467. discard_stale();
  6468. rd_lock(&mining_thr_lock);
  6469. for (i = 0; i < mining_threads; i++)
  6470. {
  6471. thr = mining_thr[i];
  6472. thr->work_restart = true;
  6473. }
  6474. for (i = 0; i < mining_threads; i++)
  6475. {
  6476. thr = mining_thr[i];
  6477. notifier_wake(thr->work_restart_notifier);
  6478. }
  6479. rd_unlock(&mining_thr_lock);
  6480. }
  6481. void blkhashstr(char *rv, const unsigned char *hash)
  6482. {
  6483. unsigned char hash_swap[32];
  6484. swap256(hash_swap, hash);
  6485. swap32tole(hash_swap, hash_swap, 32 / 4);
  6486. bin2hex(rv, hash_swap, 32);
  6487. }
  6488. static
  6489. void set_curblock(struct mining_goal_info * const goal, struct block_info * const blkinfo)
  6490. {
  6491. struct blockchain_info * const blkchain = goal->blkchain;
  6492. blkchain->currentblk = blkinfo;
  6493. blkchain->currentblk_subsidy = 5000000000LL >> (blkinfo->height / 210000);
  6494. cg_wlock(&ch_lock);
  6495. __update_block_title(goal);
  6496. get_timestamp(blkchain->currentblk_first_seen_time_str, sizeof(blkchain->currentblk_first_seen_time_str), blkinfo->first_seen_time);
  6497. cg_wunlock(&ch_lock);
  6498. applog(LOG_INFO, "New block: %s diff %s (%s)", goal->current_goal_detail, goal->current_diff_str, goal->net_hashrate);
  6499. }
  6500. /* Search to see if this prevblkhash has been seen before */
  6501. static
  6502. struct block_info *block_exists(const struct blockchain_info * const blkchain, const void * const prevblkhash)
  6503. {
  6504. struct block_info *s;
  6505. rd_lock(&blk_lock);
  6506. HASH_FIND(hh, blkchain->blocks, prevblkhash, 0x20, s);
  6507. rd_unlock(&blk_lock);
  6508. return s;
  6509. }
  6510. static int block_sort(struct block_info * const blocka, struct block_info * const blockb)
  6511. {
  6512. return blocka->block_seen_order - blockb->block_seen_order;
  6513. }
  6514. static
  6515. void set_blockdiff(struct mining_goal_info * const goal, const struct work * const work)
  6516. {
  6517. unsigned char target[32];
  6518. double diff;
  6519. uint64_t diff64;
  6520. real_block_target(target, work->data);
  6521. diff = target_diff(target);
  6522. diff64 = diff;
  6523. suffix_string(diff64, goal->current_diff_str, sizeof(goal->current_diff_str), 0);
  6524. format_unit2(goal->net_hashrate, sizeof(goal->net_hashrate),
  6525. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  6526. if (unlikely(goal->current_diff != diff))
  6527. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", goal->current_diff_str, goal->net_hashrate);
  6528. goal->current_diff = diff;
  6529. }
  6530. static bool test_work_current(struct work *work)
  6531. {
  6532. bool ret = true;
  6533. if (work->mandatory)
  6534. return ret;
  6535. uint32_t block_id = ((uint32_t*)(work->data))[1];
  6536. const uint8_t * const prevblkhash = &work->data[4];
  6537. {
  6538. /* Hack to work around dud work sneaking into test */
  6539. bool dudwork = true;
  6540. for (int i = 8; i < 26; ++i)
  6541. if (work->data[i])
  6542. {
  6543. dudwork = false;
  6544. break;
  6545. }
  6546. if (dudwork)
  6547. goto out_free;
  6548. }
  6549. struct pool * const pool = work->pool;
  6550. struct mining_goal_info * const goal = pool->goal;
  6551. struct blockchain_info * const blkchain = goal->blkchain;
  6552. /* Search to see if this block exists yet and if not, consider it a
  6553. * new block and set the current block details to this one */
  6554. if (!block_exists(blkchain, prevblkhash))
  6555. {
  6556. struct block_info * const s = calloc(sizeof(struct block_info), 1);
  6557. int deleted_block = 0;
  6558. ret = false;
  6559. if (unlikely(!s))
  6560. quit (1, "test_work_current OOM");
  6561. memcpy(s->prevblkhash, prevblkhash, sizeof(s->prevblkhash));
  6562. s->block_id = block_id;
  6563. s->block_seen_order = new_blocks++;
  6564. s->first_seen_time = time(NULL);
  6565. wr_lock(&blk_lock);
  6566. /* Only keep the last hour's worth of blocks in memory since
  6567. * work from blocks before this is virtually impossible and we
  6568. * want to prevent memory usage from continually rising */
  6569. if (HASH_COUNT(blkchain->blocks) > 6)
  6570. {
  6571. struct block_info *oldblock;
  6572. HASH_SORT(blkchain->blocks, block_sort);
  6573. oldblock = blkchain->blocks;
  6574. deleted_block = oldblock->block_seen_order;
  6575. HASH_DEL(blkchain->blocks, oldblock);
  6576. free(oldblock);
  6577. }
  6578. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(s->prevblkhash), s);
  6579. set_blockdiff(goal, work);
  6580. wr_unlock(&blk_lock);
  6581. pool->block_id = block_id;
  6582. pool_update_work_restart_time(pool);
  6583. if (deleted_block)
  6584. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  6585. #if BLKMAKER_VERSION > 1
  6586. template_nonce = 0;
  6587. #endif
  6588. set_curblock(goal, s);
  6589. if (unlikely(new_blocks == 1))
  6590. goto out_free;
  6591. if (!work->stratum)
  6592. {
  6593. if (work->longpoll)
  6594. {
  6595. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  6596. pool->pool_no);
  6597. }
  6598. else
  6599. if (goal->have_longpoll)
  6600. applog(LOG_NOTICE, "New block detected on network before longpoll");
  6601. else
  6602. applog(LOG_NOTICE, "New block detected on network");
  6603. }
  6604. restart_threads();
  6605. }
  6606. else
  6607. {
  6608. bool restart = false;
  6609. if (unlikely(pool->block_id != block_id))
  6610. {
  6611. bool was_active = pool->block_id != 0;
  6612. pool->block_id = block_id;
  6613. pool_update_work_restart_time(pool);
  6614. if (!work->longpoll)
  6615. update_last_work(work);
  6616. if (was_active)
  6617. {
  6618. // Pool actively changed block
  6619. if (pool == current_pool())
  6620. restart = true;
  6621. if (block_id == blkchain->currentblk->block_id)
  6622. {
  6623. // Caught up, only announce if this pool is the one in use
  6624. if (restart)
  6625. applog(LOG_NOTICE, "%s %d caught up to new block",
  6626. work->longpoll ? "Longpoll from pool" : "Pool",
  6627. pool->pool_no);
  6628. }
  6629. else
  6630. {
  6631. // Switched to a block we know, but not the latest... why?
  6632. // This might detect pools trying to double-spend or 51%,
  6633. // but let's not make any accusations until it's had time
  6634. // in the real world.
  6635. char hexstr[65];
  6636. blkhashstr(hexstr, prevblkhash);
  6637. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  6638. work->longpoll ? "Longpoll from pool" : "Pool",
  6639. pool->pool_no,
  6640. hexstr);
  6641. }
  6642. }
  6643. }
  6644. if (work->longpoll)
  6645. {
  6646. struct pool * const cp = current_pool();
  6647. ++pool->work_restart_id;
  6648. if (work->tr && work->tr == pool->swork.tr)
  6649. pool->swork.work_restart_id = pool->work_restart_id;
  6650. update_last_work(work);
  6651. pool_update_work_restart_time(pool);
  6652. applog(
  6653. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  6654. "Longpoll from pool %d requested work update",
  6655. pool->pool_no);
  6656. if ((!restart) && pool == cp)
  6657. restart = true;
  6658. }
  6659. if (restart)
  6660. restart_threads();
  6661. }
  6662. work->longpoll = false;
  6663. out_free:
  6664. return ret;
  6665. }
  6666. static int tv_sort(struct work *worka, struct work *workb)
  6667. {
  6668. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  6669. }
  6670. static bool work_rollable(struct work *work)
  6671. {
  6672. return (!work->clone && work->rolltime);
  6673. }
  6674. static bool hash_push(struct work *work)
  6675. {
  6676. bool rc = true;
  6677. mutex_lock(stgd_lock);
  6678. if (work_rollable(work))
  6679. staged_rollable++;
  6680. ++work_mining_algorithm(work)->staged;
  6681. if (work->spare)
  6682. ++staged_spare;
  6683. if (likely(!getq->frozen)) {
  6684. HASH_ADD_INT(staged_work, id, work);
  6685. HASH_SORT(staged_work, tv_sort);
  6686. } else
  6687. rc = false;
  6688. pthread_cond_broadcast(&getq->cond);
  6689. mutex_unlock(stgd_lock);
  6690. return rc;
  6691. }
  6692. static void stage_work(struct work *work)
  6693. {
  6694. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  6695. work->id, work->pool->pool_no);
  6696. work->work_restart_id = work->pool->work_restart_id;
  6697. work->pool->last_work_time = time(NULL);
  6698. cgtime(&work->pool->tv_last_work_time);
  6699. test_work_current(work);
  6700. work->pool->works++;
  6701. hash_push(work);
  6702. }
  6703. #ifdef HAVE_CURSES
  6704. int curses_int(const char *query)
  6705. {
  6706. int ret;
  6707. char *cvar;
  6708. cvar = curses_input(query);
  6709. if (unlikely(!cvar))
  6710. return -1;
  6711. ret = atoi(cvar);
  6712. free(cvar);
  6713. return ret;
  6714. }
  6715. #endif
  6716. #ifdef HAVE_CURSES
  6717. static bool input_pool(bool live);
  6718. #endif
  6719. #ifdef HAVE_CURSES
  6720. static void display_pool_summary(struct pool *pool)
  6721. {
  6722. double efficiency = 0.0;
  6723. char xfer[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+4+1], bw[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+6+1];
  6724. int pool_secs;
  6725. if (curses_active_locked()) {
  6726. wlog("Pool: %s Goal: %s\n", pool->rpc_url, pool->goal->name);
  6727. if (pool->solved)
  6728. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  6729. if (!pool->has_stratum)
  6730. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  6731. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  6732. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  6733. wlog(" Accepted shares: %d\n", pool->accepted);
  6734. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  6735. pool->rejected, pool->stale_shares,
  6736. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  6737. );
  6738. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  6739. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  6740. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  6741. wlog(" Network transfer: %s (%s)\n",
  6742. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  6743. (float)pool->cgminer_pool_stats.net_bytes_received,
  6744. (float)pool->cgminer_pool_stats.net_bytes_sent),
  6745. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  6746. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  6747. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  6748. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  6749. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  6750. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  6751. wlog(" Items worked on: %d\n", pool->works);
  6752. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  6753. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  6754. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  6755. unlock_curses();
  6756. }
  6757. }
  6758. #endif
  6759. /* We can't remove the memory used for this struct pool because there may
  6760. * still be work referencing it. We just remove it from the pools list */
  6761. void remove_pool(struct pool *pool)
  6762. {
  6763. int i, last_pool = total_pools - 1;
  6764. struct pool *other;
  6765. disable_pool(pool, POOL_DISABLED);
  6766. /* Boost priority of any lower prio than this one */
  6767. for (i = 0; i < total_pools; i++) {
  6768. other = pools[i];
  6769. if (other->prio > pool->prio)
  6770. other->prio--;
  6771. }
  6772. if (pool->pool_no < last_pool) {
  6773. /* Swap the last pool for this one */
  6774. (pools[last_pool])->pool_no = pool->pool_no;
  6775. pools[pool->pool_no] = pools[last_pool];
  6776. }
  6777. /* Give it an invalid number */
  6778. pool->pool_no = total_pools;
  6779. pool->removed = true;
  6780. pool->has_stratum = false;
  6781. total_pools--;
  6782. }
  6783. /* add a mutex if this needs to be thread safe in the future */
  6784. static struct JE {
  6785. char *buf;
  6786. struct JE *next;
  6787. } *jedata = NULL;
  6788. static void json_escape_free()
  6789. {
  6790. struct JE *jeptr = jedata;
  6791. struct JE *jenext;
  6792. jedata = NULL;
  6793. while (jeptr) {
  6794. jenext = jeptr->next;
  6795. free(jeptr->buf);
  6796. free(jeptr);
  6797. jeptr = jenext;
  6798. }
  6799. }
  6800. static
  6801. char *json_escape(const char *str)
  6802. {
  6803. struct JE *jeptr;
  6804. char *buf, *ptr;
  6805. /* 2x is the max, may as well just allocate that */
  6806. ptr = buf = malloc(strlen(str) * 2 + 1);
  6807. jeptr = malloc(sizeof(*jeptr));
  6808. jeptr->buf = buf;
  6809. jeptr->next = jedata;
  6810. jedata = jeptr;
  6811. while (*str) {
  6812. if (*str == '\\' || *str == '"')
  6813. *(ptr++) = '\\';
  6814. *(ptr++) = *(str++);
  6815. }
  6816. *ptr = '\0';
  6817. return buf;
  6818. }
  6819. static
  6820. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  6821. {
  6822. if (!elist)
  6823. return;
  6824. static struct string_elist *entry;
  6825. fprintf(fcfg, ",\n\"%s\" : [", configname);
  6826. bool first = true;
  6827. DL_FOREACH(elist, entry)
  6828. {
  6829. const char * const s = entry->string;
  6830. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  6831. first = false;
  6832. }
  6833. fprintf(fcfg, "\n]");
  6834. }
  6835. void write_config(FILE *fcfg)
  6836. {
  6837. int i;
  6838. /* Write pool values */
  6839. fputs("{\n\"pools\" : [", fcfg);
  6840. for(i = 0; i < total_pools; i++) {
  6841. struct pool *pool = pools[i];
  6842. if (pool->failover_only)
  6843. // Don't write failover-only (automatically added) pools to the config file for now
  6844. continue;
  6845. if (pool->quota != 1) {
  6846. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  6847. pool->quota,
  6848. json_escape(pool->rpc_url));
  6849. } else {
  6850. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  6851. json_escape(pool->rpc_url));
  6852. }
  6853. if (pool->rpc_proxy)
  6854. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  6855. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  6856. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  6857. if (strcmp(pool->goal->name, "default"))
  6858. fprintf(fcfg, "\n\t\t\"pool-goal\" : \"%s\",", pool->goal->name);
  6859. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  6860. if (pool->force_rollntime)
  6861. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  6862. fprintf(fcfg, "\n\t}");
  6863. }
  6864. fputs("\n]\n", fcfg);
  6865. #ifdef USE_OPENCL
  6866. write_config_opencl(fcfg);
  6867. #endif
  6868. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  6869. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  6870. #endif
  6871. /* Simple bool and int options */
  6872. struct opt_table *opt;
  6873. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  6874. char *p, *name = strdup(opt->names);
  6875. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  6876. if (p[1] != '-')
  6877. continue;
  6878. if (opt->type & OPT_NOARG &&
  6879. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  6880. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  6881. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  6882. if (opt->type & OPT_HASARG &&
  6883. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  6884. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  6885. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  6886. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  6887. opt->desc != opt_hidden &&
  6888. 0 <= *(int *)opt->u.arg)
  6889. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  6890. }
  6891. free(name);
  6892. }
  6893. /* Special case options */
  6894. if (request_target_str)
  6895. {
  6896. if (request_pdiff == (long)request_pdiff)
  6897. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  6898. else
  6899. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  6900. }
  6901. fprintf(fcfg, ",\n\"shares\" : %g", opt_shares);
  6902. if (pool_strategy == POOL_BALANCE)
  6903. fputs(",\n\"balance\" : true", fcfg);
  6904. if (pool_strategy == POOL_LOADBALANCE)
  6905. fputs(",\n\"load-balance\" : true", fcfg);
  6906. if (pool_strategy == POOL_ROUNDROBIN)
  6907. fputs(",\n\"round-robin\" : true", fcfg);
  6908. if (pool_strategy == POOL_ROTATE)
  6909. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  6910. #if defined(unix) || defined(__APPLE__)
  6911. if (opt_stderr_cmd && *opt_stderr_cmd)
  6912. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  6913. #endif // defined(unix)
  6914. if (opt_kernel_path && *opt_kernel_path) {
  6915. char *kpath = strdup(opt_kernel_path);
  6916. if (kpath[strlen(kpath)-1] == '/')
  6917. kpath[strlen(kpath)-1] = 0;
  6918. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  6919. free(kpath);
  6920. }
  6921. if (schedstart.enable)
  6922. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  6923. if (schedstop.enable)
  6924. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  6925. if (opt_socks_proxy && *opt_socks_proxy)
  6926. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  6927. _write_config_string_elist(fcfg, "scan", scan_devices);
  6928. #ifdef USE_LIBMICROHTTPD
  6929. if (httpsrv_port != -1)
  6930. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  6931. #endif
  6932. #ifdef USE_LIBEVENT
  6933. if (stratumsrv_port != -1)
  6934. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  6935. #endif
  6936. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  6937. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  6938. if (opt_api_allow)
  6939. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  6940. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  6941. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  6942. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  6943. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  6944. if (*opt_api_mcast_des)
  6945. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  6946. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  6947. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  6948. if (opt_api_groups)
  6949. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  6950. fputs("\n}\n", fcfg);
  6951. json_escape_free();
  6952. }
  6953. void zero_bestshare(void)
  6954. {
  6955. int i;
  6956. best_diff = 0;
  6957. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  6958. for (i = 0; i < total_pools; i++) {
  6959. struct pool *pool = pools[i];
  6960. pool->best_diff = 0;
  6961. }
  6962. }
  6963. void zero_stats(void)
  6964. {
  6965. int i;
  6966. applog(LOG_DEBUG, "Zeroing stats");
  6967. cgtime(&total_tv_start);
  6968. miner_started = total_tv_start;
  6969. total_rolling = 0;
  6970. total_mhashes_done = 0;
  6971. total_getworks = 0;
  6972. total_accepted = 0;
  6973. total_rejected = 0;
  6974. hw_errors = 0;
  6975. total_stale = 0;
  6976. total_discarded = 0;
  6977. total_bytes_rcvd = total_bytes_sent = 0;
  6978. new_blocks = 0;
  6979. local_work = 0;
  6980. total_go = 0;
  6981. total_ro = 0;
  6982. total_secs = 1.0;
  6983. total_diff1 = 0;
  6984. total_bad_diff1 = 0;
  6985. found_blocks = 0;
  6986. total_diff_accepted = 0;
  6987. total_diff_rejected = 0;
  6988. total_diff_stale = 0;
  6989. #ifdef HAVE_CURSES
  6990. awidth = rwidth = swidth = hwwidth = 1;
  6991. #endif
  6992. struct mining_goal_info *goal, *tmpgoal;
  6993. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  6994. {
  6995. goal->diff_accepted = 0;
  6996. }
  6997. for (i = 0; i < total_pools; i++) {
  6998. struct pool *pool = pools[i];
  6999. pool->getwork_requested = 0;
  7000. pool->accepted = 0;
  7001. pool->rejected = 0;
  7002. pool->solved = 0;
  7003. pool->getwork_requested = 0;
  7004. pool->stale_shares = 0;
  7005. pool->discarded_work = 0;
  7006. pool->getfail_occasions = 0;
  7007. pool->remotefail_occasions = 0;
  7008. pool->last_share_time = 0;
  7009. pool->works = 0;
  7010. pool->diff1 = 0;
  7011. pool->diff_accepted = 0;
  7012. pool->diff_rejected = 0;
  7013. pool->diff_stale = 0;
  7014. pool->last_share_diff = 0;
  7015. pool->cgminer_stats.start_tv = total_tv_start;
  7016. pool->cgminer_stats.getwork_calls = 0;
  7017. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  7018. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  7019. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  7020. pool->cgminer_pool_stats.getwork_calls = 0;
  7021. pool->cgminer_pool_stats.getwork_attempts = 0;
  7022. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  7023. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  7024. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  7025. pool->cgminer_pool_stats.min_diff = 0;
  7026. pool->cgminer_pool_stats.max_diff = 0;
  7027. pool->cgminer_pool_stats.min_diff_count = 0;
  7028. pool->cgminer_pool_stats.max_diff_count = 0;
  7029. pool->cgminer_pool_stats.times_sent = 0;
  7030. pool->cgminer_pool_stats.bytes_sent = 0;
  7031. pool->cgminer_pool_stats.net_bytes_sent = 0;
  7032. pool->cgminer_pool_stats.times_received = 0;
  7033. pool->cgminer_pool_stats.bytes_received = 0;
  7034. pool->cgminer_pool_stats.net_bytes_received = 0;
  7035. }
  7036. zero_bestshare();
  7037. for (i = 0; i < total_devices; ++i) {
  7038. struct cgpu_info *cgpu = get_devices(i);
  7039. mutex_lock(&hash_lock);
  7040. cgpu->total_mhashes = 0;
  7041. cgpu->accepted = 0;
  7042. cgpu->rejected = 0;
  7043. cgpu->stale = 0;
  7044. cgpu->hw_errors = 0;
  7045. cgpu->utility = 0.0;
  7046. cgpu->utility_diff1 = 0;
  7047. cgpu->last_share_pool_time = 0;
  7048. cgpu->bad_diff1 = 0;
  7049. cgpu->diff1 = 0;
  7050. cgpu->diff_accepted = 0;
  7051. cgpu->diff_rejected = 0;
  7052. cgpu->diff_stale = 0;
  7053. cgpu->last_share_diff = 0;
  7054. cgpu->thread_fail_init_count = 0;
  7055. cgpu->thread_zero_hash_count = 0;
  7056. cgpu->thread_fail_queue_count = 0;
  7057. cgpu->dev_sick_idle_60_count = 0;
  7058. cgpu->dev_dead_idle_600_count = 0;
  7059. cgpu->dev_nostart_count = 0;
  7060. cgpu->dev_over_heat_count = 0;
  7061. cgpu->dev_thermal_cutoff_count = 0;
  7062. cgpu->dev_comms_error_count = 0;
  7063. cgpu->dev_throttle_count = 0;
  7064. cgpu->cgminer_stats.start_tv = total_tv_start;
  7065. cgpu->cgminer_stats.getwork_calls = 0;
  7066. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  7067. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  7068. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  7069. mutex_unlock(&hash_lock);
  7070. if (cgpu->drv->zero_stats)
  7071. cgpu->drv->zero_stats(cgpu);
  7072. }
  7073. }
  7074. int bfg_strategy_parse(const char * const s)
  7075. {
  7076. char *endptr;
  7077. if (!(s && s[0]))
  7078. return -1;
  7079. long int selected = strtol(s, &endptr, 0);
  7080. if (endptr == s || *endptr) {
  7081. // Look-up by name
  7082. selected = -1;
  7083. for (unsigned i = 0; i <= TOP_STRATEGY; ++i) {
  7084. if (!strcasecmp(strategies[i].s, s)) {
  7085. selected = i;
  7086. }
  7087. }
  7088. }
  7089. if (selected < 0 || selected > TOP_STRATEGY) {
  7090. return -1;
  7091. }
  7092. return selected;
  7093. }
  7094. bool bfg_strategy_change(const int selected, const char * const param)
  7095. {
  7096. if (param && param[0]) {
  7097. switch (selected) {
  7098. case POOL_ROTATE:
  7099. {
  7100. char *endptr;
  7101. long int n = strtol(param, &endptr, 0);
  7102. if (n < 0 || n > 9999 || *endptr) {
  7103. return false;
  7104. }
  7105. opt_rotate_period = n;
  7106. break;
  7107. }
  7108. default:
  7109. return false;
  7110. }
  7111. }
  7112. mutex_lock(&lp_lock);
  7113. pool_strategy = selected;
  7114. pthread_cond_broadcast(&lp_cond);
  7115. mutex_unlock(&lp_lock);
  7116. switch_pools(NULL);
  7117. return true;
  7118. }
  7119. #ifdef HAVE_CURSES
  7120. static
  7121. void loginput_mode(const int size)
  7122. {
  7123. clear_logwin();
  7124. loginput_size = size;
  7125. check_winsizes();
  7126. }
  7127. static void display_pools(void)
  7128. {
  7129. struct pool *pool;
  7130. int selected, i, j;
  7131. char input;
  7132. loginput_mode(7 + total_pools);
  7133. immedok(logwin, true);
  7134. updated:
  7135. for (j = 0; j < total_pools; j++) {
  7136. for (i = 0; i < total_pools; i++) {
  7137. pool = pools[i];
  7138. if (pool->prio != j)
  7139. continue;
  7140. if (pool_actively_in_use(pool, NULL))
  7141. wattron(logwin, A_BOLD);
  7142. if (pool->enabled != POOL_ENABLED || pool->failover_only)
  7143. wattron(logwin, A_DIM);
  7144. wlogprint("%d: ", pool->prio);
  7145. switch (pool->enabled) {
  7146. case POOL_ENABLED:
  7147. if ((pool_strategy == POOL_LOADBALANCE) ? (!pool->quota)
  7148. : ((pool_strategy != POOL_FAILOVER) ? pool->failover_only : 0))
  7149. wlogprint("Failover ");
  7150. else
  7151. wlogprint("Enabled ");
  7152. break;
  7153. case POOL_DISABLED:
  7154. wlogprint("Disabled ");
  7155. break;
  7156. case POOL_REJECTING:
  7157. wlogprint("Rejectin ");
  7158. break;
  7159. case POOL_MISBEHAVING:
  7160. wlogprint("Misbehav ");
  7161. break;
  7162. }
  7163. _wlogprint(pool_proto_str(pool));
  7164. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  7165. pool->quota,
  7166. pool->pool_no,
  7167. pool->rpc_url, pool->rpc_user);
  7168. wattroff(logwin, A_BOLD | A_DIM);
  7169. break; //for (i = 0; i < total_pools; i++)
  7170. }
  7171. }
  7172. retry:
  7173. wlogprint("\nCurrent pool management strategy: %s\n",
  7174. strategies[pool_strategy].s);
  7175. if (pool_strategy == POOL_ROTATE)
  7176. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  7177. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  7178. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  7179. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  7180. wlogprint("Or press any other key to continue\n");
  7181. logwin_update();
  7182. input = getch();
  7183. if (!strncasecmp(&input, "a", 1)) {
  7184. if (opt_benchmark)
  7185. {
  7186. wlogprint("Cannot add pools in benchmark mode");
  7187. goto retry;
  7188. }
  7189. input_pool(true);
  7190. goto updated;
  7191. } else if (!strncasecmp(&input, "r", 1)) {
  7192. if (total_pools <= 1) {
  7193. wlogprint("Cannot remove last pool");
  7194. goto retry;
  7195. }
  7196. selected = curses_int("Select pool number");
  7197. if (selected < 0 || selected >= total_pools) {
  7198. wlogprint("Invalid selection\n");
  7199. goto retry;
  7200. }
  7201. pool = pools[selected];
  7202. if (pool == current_pool())
  7203. switch_pools(NULL);
  7204. if (pool == current_pool()) {
  7205. wlogprint("Unable to remove pool due to activity\n");
  7206. goto retry;
  7207. }
  7208. remove_pool(pool);
  7209. goto updated;
  7210. } else if (!strncasecmp(&input, "s", 1)) {
  7211. selected = curses_int("Select pool number");
  7212. if (selected < 0 || selected >= total_pools) {
  7213. wlogprint("Invalid selection\n");
  7214. goto retry;
  7215. }
  7216. pool = pools[selected];
  7217. manual_enable_pool(pool);
  7218. switch_pools(pool);
  7219. goto updated;
  7220. } else if (!strncasecmp(&input, "d", 1)) {
  7221. if (enabled_pools <= 1) {
  7222. wlogprint("Cannot disable last pool");
  7223. goto retry;
  7224. }
  7225. selected = curses_int("Select pool number");
  7226. if (selected < 0 || selected >= total_pools) {
  7227. wlogprint("Invalid selection\n");
  7228. goto retry;
  7229. }
  7230. pool = pools[selected];
  7231. disable_pool(pool, POOL_DISABLED);
  7232. goto updated;
  7233. } else if (!strncasecmp(&input, "e", 1)) {
  7234. selected = curses_int("Select pool number");
  7235. if (selected < 0 || selected >= total_pools) {
  7236. wlogprint("Invalid selection\n");
  7237. goto retry;
  7238. }
  7239. pool = pools[selected];
  7240. manual_enable_pool(pool);
  7241. goto updated;
  7242. } else if (!strncasecmp(&input, "c", 1)) {
  7243. for (i = 0; i <= TOP_STRATEGY; i++)
  7244. wlogprint("%d: %s\n", i, strategies[i].s);
  7245. {
  7246. char * const selected_str = curses_input("Select strategy type");
  7247. selected = bfg_strategy_parse(selected_str);
  7248. free(selected_str);
  7249. }
  7250. if (selected < 0 || selected > TOP_STRATEGY) {
  7251. wlogprint("Invalid selection\n");
  7252. goto retry;
  7253. }
  7254. char *param = NULL;
  7255. if (selected == POOL_ROTATE) {
  7256. param = curses_input("Select interval in minutes");
  7257. }
  7258. bool result = bfg_strategy_change(selected, param);
  7259. free(param);
  7260. if (!result) {
  7261. wlogprint("Invalid selection\n");
  7262. goto retry;
  7263. }
  7264. goto updated;
  7265. } else if (!strncasecmp(&input, "i", 1)) {
  7266. selected = curses_int("Select pool number");
  7267. if (selected < 0 || selected >= total_pools) {
  7268. wlogprint("Invalid selection\n");
  7269. goto retry;
  7270. }
  7271. pool = pools[selected];
  7272. display_pool_summary(pool);
  7273. goto retry;
  7274. } else if (!strncasecmp(&input, "q", 1)) {
  7275. selected = curses_int("Select pool number");
  7276. if (selected < 0 || selected >= total_pools) {
  7277. wlogprint("Invalid selection\n");
  7278. goto retry;
  7279. }
  7280. pool = pools[selected];
  7281. selected = curses_int("Set quota");
  7282. if (selected < 0) {
  7283. wlogprint("Invalid negative quota\n");
  7284. goto retry;
  7285. }
  7286. if (selected > 0)
  7287. pool->failover_only = false;
  7288. pool->quota = selected;
  7289. adjust_quota_gcd();
  7290. goto updated;
  7291. } else if (!strncasecmp(&input, "f", 1)) {
  7292. opt_fail_only ^= true;
  7293. goto updated;
  7294. } else if (!strncasecmp(&input, "p", 1)) {
  7295. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  7296. if (!prilist)
  7297. {
  7298. wlogprint("Not changing priorities\n");
  7299. goto retry;
  7300. }
  7301. int res = prioritize_pools(prilist, &i);
  7302. free(prilist);
  7303. switch (res) {
  7304. case MSG_NOPOOL:
  7305. wlogprint("No pools\n");
  7306. goto retry;
  7307. case MSG_MISPID:
  7308. wlogprint("Missing pool id parameter\n");
  7309. goto retry;
  7310. case MSG_INVPID:
  7311. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  7312. goto retry;
  7313. case MSG_DUPPID:
  7314. wlogprint("Duplicate pool specified %d\n", i);
  7315. goto retry;
  7316. case MSG_POOLPRIO:
  7317. default:
  7318. goto updated;
  7319. }
  7320. }
  7321. immedok(logwin, false);
  7322. loginput_mode(0);
  7323. }
  7324. static const char *summary_detail_level_str(void)
  7325. {
  7326. if (opt_compact)
  7327. return "compact";
  7328. if (opt_show_procs)
  7329. return "processors";
  7330. return "devices";
  7331. }
  7332. static void display_options(void)
  7333. {
  7334. int selected;
  7335. char input;
  7336. immedok(logwin, true);
  7337. loginput_mode(12);
  7338. retry:
  7339. clear_logwin();
  7340. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  7341. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  7342. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  7343. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  7344. opt_debug_console ? "on" : "off",
  7345. want_per_device_stats? "on" : "off",
  7346. opt_quiet ? "on" : "off",
  7347. opt_log_output ? "on" : "off",
  7348. opt_protocol ? "on" : "off",
  7349. opt_worktime ? "on" : "off",
  7350. summary_detail_level_str(),
  7351. opt_log_interval,
  7352. opt_weighed_stats ? "weighed" : "absolute");
  7353. wlogprint("Select an option or any other key to return\n");
  7354. logwin_update();
  7355. input = getch();
  7356. if (!strncasecmp(&input, "q", 1)) {
  7357. opt_quiet ^= true;
  7358. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  7359. goto retry;
  7360. } else if (!strncasecmp(&input, "v", 1)) {
  7361. opt_log_output ^= true;
  7362. if (opt_log_output)
  7363. opt_quiet = false;
  7364. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  7365. goto retry;
  7366. } else if (!strncasecmp(&input, "n", 1)) {
  7367. opt_log_output = false;
  7368. opt_debug_console = false;
  7369. opt_quiet = false;
  7370. opt_protocol = false;
  7371. opt_compact = false;
  7372. opt_show_procs = false;
  7373. devsummaryYOffset = 0;
  7374. want_per_device_stats = false;
  7375. wlogprint("Output mode reset to normal\n");
  7376. switch_logsize();
  7377. goto retry;
  7378. } else if (!strncasecmp(&input, "d", 1)) {
  7379. opt_debug = true;
  7380. opt_debug_console ^= true;
  7381. opt_log_output = opt_debug_console;
  7382. if (opt_debug_console)
  7383. opt_quiet = false;
  7384. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  7385. goto retry;
  7386. } else if (!strncasecmp(&input, "m", 1)) {
  7387. if (opt_compact)
  7388. opt_compact = false;
  7389. else
  7390. if (!opt_show_procs)
  7391. opt_show_procs = true;
  7392. else
  7393. {
  7394. opt_compact = true;
  7395. opt_show_procs = false;
  7396. devsummaryYOffset = 0;
  7397. }
  7398. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  7399. switch_logsize();
  7400. goto retry;
  7401. } else if (!strncasecmp(&input, "p", 1)) {
  7402. want_per_device_stats ^= true;
  7403. opt_log_output = want_per_device_stats;
  7404. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  7405. goto retry;
  7406. } else if (!strncasecmp(&input, "r", 1)) {
  7407. opt_protocol ^= true;
  7408. if (opt_protocol)
  7409. opt_quiet = false;
  7410. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  7411. goto retry;
  7412. } else if (!strncasecmp(&input, "c", 1))
  7413. clear_logwin();
  7414. else if (!strncasecmp(&input, "l", 1)) {
  7415. selected = curses_int("Interval in seconds");
  7416. if (selected < 0 || selected > 9999) {
  7417. wlogprint("Invalid selection\n");
  7418. goto retry;
  7419. }
  7420. opt_log_interval = selected;
  7421. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  7422. goto retry;
  7423. } else if (!strncasecmp(&input, "s", 1)) {
  7424. opt_realquiet = true;
  7425. } else if (!strncasecmp(&input, "w", 1)) {
  7426. opt_worktime ^= true;
  7427. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  7428. goto retry;
  7429. } else if (!strncasecmp(&input, "t", 1)) {
  7430. opt_weighed_stats ^= true;
  7431. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  7432. goto retry;
  7433. } else if (!strncasecmp(&input, "z", 1)) {
  7434. zero_stats();
  7435. goto retry;
  7436. }
  7437. immedok(logwin, false);
  7438. loginput_mode(0);
  7439. }
  7440. #endif
  7441. void default_save_file(char *filename)
  7442. {
  7443. #if defined(unix) || defined(__APPLE__)
  7444. if (getenv("HOME") && *getenv("HOME")) {
  7445. strcpy(filename, getenv("HOME"));
  7446. strcat(filename, "/");
  7447. }
  7448. else
  7449. strcpy(filename, "");
  7450. strcat(filename, ".bfgminer/");
  7451. mkdir(filename, 0777);
  7452. #else
  7453. strcpy(filename, "");
  7454. #endif
  7455. strcat(filename, def_conf);
  7456. }
  7457. #ifdef HAVE_CURSES
  7458. static void set_options(void)
  7459. {
  7460. int selected;
  7461. char input;
  7462. immedok(logwin, true);
  7463. loginput_mode(8);
  7464. retry:
  7465. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  7466. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  7467. "[W]rite config file\n[B]FGMiner restart\n",
  7468. opt_queue, opt_scantime, opt_expiry, opt_retries);
  7469. wlogprint("Select an option or any other key to return\n");
  7470. logwin_update();
  7471. input = getch();
  7472. if (!strncasecmp(&input, "q", 1)) {
  7473. selected = curses_int("Extra work items to queue");
  7474. if (selected < 0 || selected > 9999) {
  7475. wlogprint("Invalid selection\n");
  7476. goto retry;
  7477. }
  7478. opt_queue = selected;
  7479. goto retry;
  7480. } else if (!strncasecmp(&input, "l", 1)) {
  7481. if (want_longpoll)
  7482. stop_longpoll();
  7483. else
  7484. start_longpoll();
  7485. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  7486. goto retry;
  7487. } else if (!strncasecmp(&input, "s", 1)) {
  7488. selected = curses_int("Set scantime in seconds");
  7489. if (selected < 0 || selected > 9999) {
  7490. wlogprint("Invalid selection\n");
  7491. goto retry;
  7492. }
  7493. opt_scantime = selected;
  7494. goto retry;
  7495. } else if (!strncasecmp(&input, "e", 1)) {
  7496. selected = curses_int("Set expiry time in seconds");
  7497. if (selected < 0 || selected > 9999) {
  7498. wlogprint("Invalid selection\n");
  7499. goto retry;
  7500. }
  7501. opt_expiry = selected;
  7502. goto retry;
  7503. } else if (!strncasecmp(&input, "r", 1)) {
  7504. selected = curses_int("Retries before failing (-1 infinite)");
  7505. if (selected < -1 || selected > 9999) {
  7506. wlogprint("Invalid selection\n");
  7507. goto retry;
  7508. }
  7509. opt_retries = selected;
  7510. goto retry;
  7511. } else if (!strncasecmp(&input, "w", 1)) {
  7512. FILE *fcfg;
  7513. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  7514. default_save_file(filename);
  7515. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  7516. str = curses_input(prompt);
  7517. if (str) {
  7518. struct stat statbuf;
  7519. strcpy(filename, str);
  7520. free(str);
  7521. if (!stat(filename, &statbuf)) {
  7522. wlogprint("File exists, overwrite?\n");
  7523. input = getch();
  7524. if (strncasecmp(&input, "y", 1))
  7525. goto retry;
  7526. }
  7527. }
  7528. fcfg = fopen(filename, "w");
  7529. if (!fcfg) {
  7530. wlogprint("Cannot open or create file\n");
  7531. goto retry;
  7532. }
  7533. write_config(fcfg);
  7534. fclose(fcfg);
  7535. goto retry;
  7536. } else if (!strncasecmp(&input, "b", 1)) {
  7537. wlogprint("Are you sure?\n");
  7538. input = getch();
  7539. if (!strncasecmp(&input, "y", 1))
  7540. app_restart();
  7541. else
  7542. clear_logwin();
  7543. } else
  7544. clear_logwin();
  7545. loginput_mode(0);
  7546. immedok(logwin, false);
  7547. }
  7548. int scan_serial(const char *);
  7549. static
  7550. void _managetui_msg(const char *repr, const char **msg)
  7551. {
  7552. if (*msg)
  7553. {
  7554. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  7555. wattron(logwin, A_BOLD);
  7556. wlogprint("%s", *msg);
  7557. wattroff(logwin, A_BOLD);
  7558. *msg = NULL;
  7559. }
  7560. logwin_update();
  7561. }
  7562. void manage_device(void)
  7563. {
  7564. char logline[256];
  7565. const char *msg = NULL;
  7566. struct cgpu_info *cgpu;
  7567. const struct device_drv *drv;
  7568. selecting_device = true;
  7569. immedok(logwin, true);
  7570. loginput_mode(12);
  7571. devchange:
  7572. if (unlikely(!total_devices))
  7573. {
  7574. clear_logwin();
  7575. wlogprint("(no devices)\n");
  7576. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  7577. _managetui_msg("(none)", &msg);
  7578. int input = getch();
  7579. switch (input)
  7580. {
  7581. case '+': case '=': // add new device
  7582. goto addnew;
  7583. default:
  7584. goto out;
  7585. }
  7586. }
  7587. cgpu = devices[selected_device];
  7588. drv = cgpu->drv;
  7589. refresh_devstatus();
  7590. refresh:
  7591. clear_logwin();
  7592. wlogprint("Select processor to manage using up/down arrow keys\n");
  7593. get_statline3(logline, sizeof(logline), cgpu, true, true);
  7594. wattron(logwin, A_BOLD);
  7595. wlogprint("%s", logline);
  7596. wattroff(logwin, A_BOLD);
  7597. wlogprint("\n");
  7598. if (cgpu->dev_manufacturer)
  7599. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  7600. else
  7601. if (cgpu->dev_product)
  7602. wlogprint(" %s\n", cgpu->dev_product);
  7603. if (cgpu->dev_serial)
  7604. wlogprint("Serial: %s\n", cgpu->dev_serial);
  7605. if (cgpu->kname)
  7606. wlogprint("Kernel: %s\n", cgpu->kname);
  7607. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  7608. drv->proc_wlogprint_status(cgpu);
  7609. wlogprint("\n");
  7610. // TODO: Last share at TIMESTAMP on pool N
  7611. // TODO: Custom device info/commands
  7612. if (cgpu->deven != DEV_ENABLED)
  7613. wlogprint("[E]nable ");
  7614. if (cgpu->deven != DEV_DISABLED)
  7615. wlogprint("[D]isable ");
  7616. if (drv->identify_device)
  7617. wlogprint("[I]dentify ");
  7618. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  7619. drv->proc_tui_wlogprint_choices(cgpu);
  7620. wlogprint("\n");
  7621. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  7622. _managetui_msg(cgpu->proc_repr, &msg);
  7623. while (true)
  7624. {
  7625. int input = getch();
  7626. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  7627. switch (input) {
  7628. case 'd': case 'D':
  7629. if (cgpu->deven == DEV_DISABLED)
  7630. msg = "Processor already disabled\n";
  7631. else
  7632. {
  7633. cgpu->deven = DEV_DISABLED;
  7634. msg = "Processor being disabled\n";
  7635. }
  7636. goto refresh;
  7637. case 'e': case 'E':
  7638. if (cgpu->deven == DEV_ENABLED)
  7639. msg = "Processor already enabled\n";
  7640. else
  7641. {
  7642. proc_enable(cgpu);
  7643. msg = "Processor being enabled\n";
  7644. }
  7645. goto refresh;
  7646. case 'i': case 'I':
  7647. if (drv->identify_device && drv->identify_device(cgpu))
  7648. msg = "Identify command sent\n";
  7649. else
  7650. goto key_default;
  7651. goto refresh;
  7652. case KEY_DOWN:
  7653. if (selected_device >= total_devices - 1)
  7654. break;
  7655. ++selected_device;
  7656. goto devchange;
  7657. case KEY_UP:
  7658. if (selected_device <= 0)
  7659. break;
  7660. --selected_device;
  7661. goto devchange;
  7662. case KEY_NPAGE:
  7663. {
  7664. if (selected_device >= total_devices - 1)
  7665. break;
  7666. struct cgpu_info *mdev = devices[selected_device]->device;
  7667. do {
  7668. ++selected_device;
  7669. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  7670. goto devchange;
  7671. }
  7672. case KEY_PPAGE:
  7673. {
  7674. if (selected_device <= 0)
  7675. break;
  7676. struct cgpu_info *mdev = devices[selected_device]->device;
  7677. do {
  7678. --selected_device;
  7679. } while (devices[selected_device]->device == mdev && selected_device > 0);
  7680. goto devchange;
  7681. }
  7682. case '/': case '?': // find device
  7683. {
  7684. static char *pattern = NULL;
  7685. char *newpattern = curses_input("Enter pattern");
  7686. if (newpattern)
  7687. {
  7688. free(pattern);
  7689. pattern = newpattern;
  7690. }
  7691. else
  7692. if (!pattern)
  7693. pattern = calloc(1, 1);
  7694. int match = cgpu_search(pattern, selected_device + 1);
  7695. if (match == -1)
  7696. {
  7697. msg = "Couldn't find device\n";
  7698. goto refresh;
  7699. }
  7700. selected_device = match;
  7701. goto devchange;
  7702. }
  7703. case '+': case '=': // add new device
  7704. {
  7705. addnew:
  7706. clear_logwin();
  7707. _wlogprint(
  7708. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  7709. "Prefix by a driver name and colon to only probe a specific driver.\n"
  7710. "For example: erupter:"
  7711. #ifdef WIN32
  7712. "\\\\.\\COM40"
  7713. #elif defined(__APPLE__)
  7714. "/dev/cu.SLAB_USBtoUART"
  7715. #else
  7716. "/dev/ttyUSB39"
  7717. #endif
  7718. "\n"
  7719. );
  7720. char *scanser = curses_input("Enter target");
  7721. if (scan_serial(scanser))
  7722. {
  7723. selected_device = total_devices - 1;
  7724. msg = "Device scan succeeded\n";
  7725. }
  7726. else
  7727. msg = "No new devices found\n";
  7728. goto devchange;
  7729. }
  7730. case 'Q': case 'q':
  7731. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  7732. case '\x1b': // ESC
  7733. case KEY_ENTER:
  7734. case '\r': // Ctrl-M on Windows, with nonl
  7735. #ifdef PADENTER
  7736. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  7737. #endif
  7738. case '\n':
  7739. goto out;
  7740. default:
  7741. ;
  7742. key_default:
  7743. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  7744. {
  7745. msg = drv->proc_tui_handle_choice(cgpu, input);
  7746. if (msg)
  7747. goto refresh;
  7748. }
  7749. }
  7750. }
  7751. out:
  7752. selecting_device = false;
  7753. loginput_mode(0);
  7754. immedok(logwin, false);
  7755. }
  7756. void show_help(void)
  7757. {
  7758. loginput_mode(11);
  7759. // NOTE: wlogprint is a macro with a buffer limit
  7760. _wlogprint(
  7761. "LU: oldest explicit work update currently being used for new work\n"
  7762. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  7763. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  7764. "E: # shares * diff per 2kB bw | I: expected income | BS: best share ever found\n"
  7765. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7766. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7767. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7768. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  7769. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7770. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7771. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE
  7772. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7773. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7774. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7775. "\n"
  7776. "devices/processors hashing (only for totals line), hottest temperature\n"
  7777. );
  7778. wlogprint(
  7779. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  7780. , opt_log_interval);
  7781. _wlogprint(
  7782. "A: accepted shares | R: rejected+discarded(% of total)\n"
  7783. "HW: hardware errors / % nonces invalid\n"
  7784. "\n"
  7785. "Press any key to clear"
  7786. );
  7787. logwin_update();
  7788. getch();
  7789. loginput_mode(0);
  7790. }
  7791. static void *input_thread(void __maybe_unused *userdata)
  7792. {
  7793. RenameThread("input");
  7794. if (!curses_active)
  7795. return NULL;
  7796. while (1) {
  7797. int input;
  7798. input = getch();
  7799. switch (input) {
  7800. case 'h': case 'H': case '?':
  7801. case KEY_F(1):
  7802. show_help();
  7803. break;
  7804. case 'q': case 'Q':
  7805. kill_work();
  7806. return NULL;
  7807. case 'd': case 'D':
  7808. display_options();
  7809. break;
  7810. case 'm': case 'M':
  7811. manage_device();
  7812. break;
  7813. case 'p': case 'P':
  7814. display_pools();
  7815. break;
  7816. case 's': case 'S':
  7817. set_options();
  7818. break;
  7819. #ifdef HAVE_CURSES
  7820. case KEY_DOWN:
  7821. {
  7822. const int visible_lines = logcursor - devcursor;
  7823. const int invisible_lines = total_lines - visible_lines;
  7824. if (devsummaryYOffset <= -invisible_lines)
  7825. break;
  7826. devsummaryYOffset -= 2;
  7827. }
  7828. case KEY_UP:
  7829. if (devsummaryYOffset == 0)
  7830. break;
  7831. ++devsummaryYOffset;
  7832. refresh_devstatus();
  7833. break;
  7834. case KEY_NPAGE:
  7835. {
  7836. const int visible_lines = logcursor - devcursor;
  7837. const int invisible_lines = total_lines - visible_lines;
  7838. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  7839. devsummaryYOffset = -invisible_lines;
  7840. else
  7841. devsummaryYOffset -= visible_lines;
  7842. refresh_devstatus();
  7843. break;
  7844. }
  7845. case KEY_PPAGE:
  7846. {
  7847. const int visible_lines = logcursor - devcursor;
  7848. if (devsummaryYOffset + visible_lines >= 0)
  7849. devsummaryYOffset = 0;
  7850. else
  7851. devsummaryYOffset += visible_lines;
  7852. refresh_devstatus();
  7853. break;
  7854. }
  7855. #endif
  7856. }
  7857. if (opt_realquiet) {
  7858. disable_curses();
  7859. break;
  7860. }
  7861. }
  7862. return NULL;
  7863. }
  7864. #endif
  7865. static void *api_thread(void *userdata)
  7866. {
  7867. struct thr_info *mythr = userdata;
  7868. pthread_detach(pthread_self());
  7869. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7870. RenameThread("rpc");
  7871. api(api_thr_id);
  7872. mythr->has_pth = false;
  7873. return NULL;
  7874. }
  7875. void thread_reportin(struct thr_info *thr)
  7876. {
  7877. cgtime(&thr->last);
  7878. thr->cgpu->status = LIFE_WELL;
  7879. thr->getwork = 0;
  7880. thr->cgpu->device_last_well = time(NULL);
  7881. }
  7882. void thread_reportout(struct thr_info *thr)
  7883. {
  7884. thr->getwork = time(NULL);
  7885. }
  7886. static void hashmeter(int thr_id, struct timeval *diff,
  7887. uint64_t hashes_done)
  7888. {
  7889. char logstatusline[256];
  7890. struct timeval temp_tv_end, total_diff;
  7891. double secs;
  7892. double local_secs;
  7893. static double local_mhashes_done = 0;
  7894. double local_mhashes = (double)hashes_done / 1000000.0;
  7895. bool showlog = false;
  7896. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[ALLOC_H2B_SPACED+3+1];
  7897. char rejpcbuf[6];
  7898. char bnbuf[6];
  7899. struct thr_info *thr;
  7900. /* Update the last time this thread reported in */
  7901. if (thr_id >= 0) {
  7902. thr = get_thread(thr_id);
  7903. cgtime(&(thr->last));
  7904. thr->cgpu->device_last_well = time(NULL);
  7905. }
  7906. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  7907. /* So we can call hashmeter from a non worker thread */
  7908. if (thr_id >= 0) {
  7909. struct cgpu_info *cgpu = thr->cgpu;
  7910. int threadobj = cgpu->threads ?: 1;
  7911. double thread_rolling = 0.0;
  7912. int i;
  7913. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  7914. thr_id, hashes_done, hashes_done / 1000 / secs);
  7915. /* Rolling average for each thread and each device */
  7916. decay_time(&thr->rolling, local_mhashes / secs, secs);
  7917. for (i = 0; i < threadobj; i++)
  7918. thread_rolling += cgpu->thr[i]->rolling;
  7919. mutex_lock(&hash_lock);
  7920. decay_time(&cgpu->rolling, thread_rolling, secs);
  7921. cgpu->total_mhashes += local_mhashes;
  7922. mutex_unlock(&hash_lock);
  7923. // If needed, output detailed, per-device stats
  7924. if (want_per_device_stats) {
  7925. struct timeval now;
  7926. struct timeval elapsed;
  7927. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  7928. cgtime(&now);
  7929. timersub(&now, last_msg_tv, &elapsed);
  7930. if (opt_log_interval <= elapsed.tv_sec) {
  7931. struct cgpu_info *cgpu = thr->cgpu;
  7932. char logline[255];
  7933. *last_msg_tv = now;
  7934. get_statline(logline, sizeof(logline), cgpu);
  7935. if (!curses_active) {
  7936. printf("\n%s\r", logline);
  7937. fflush(stdout);
  7938. } else
  7939. applog(LOG_INFO, "%s", logline);
  7940. }
  7941. }
  7942. }
  7943. /* Totals are updated by all threads so can race without locking */
  7944. mutex_lock(&hash_lock);
  7945. cgtime(&temp_tv_end);
  7946. timersub(&temp_tv_end, &total_tv_start, &total_diff);
  7947. total_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7948. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  7949. total_mhashes_done += local_mhashes;
  7950. local_mhashes_done += local_mhashes;
  7951. /* Only update with opt_log_interval */
  7952. if (total_diff.tv_sec < opt_log_interval)
  7953. goto out_unlock;
  7954. showlog = true;
  7955. cgtime(&total_tv_end);
  7956. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7957. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  7958. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  7959. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  7960. multi_format_unit_array2(
  7961. ((char*[]){cHr, aHr, uHr}),
  7962. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  7963. true, "h/s", H2B_SHORT,
  7964. 3,
  7965. 1e6*total_rolling,
  7966. 1e6*total_mhashes_done / total_secs,
  7967. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  7968. int ui_accepted, ui_rejected, ui_stale;
  7969. if (opt_weighed_stats)
  7970. {
  7971. ui_accepted = total_diff_accepted;
  7972. ui_rejected = total_diff_rejected;
  7973. ui_stale = total_diff_stale;
  7974. }
  7975. else
  7976. {
  7977. ui_accepted = total_accepted;
  7978. ui_rejected = total_rejected;
  7979. ui_stale = total_stale;
  7980. }
  7981. #ifdef HAVE_CURSES
  7982. if (curses_active_locked()) {
  7983. float temp = 0;
  7984. struct cgpu_info *proc, *last_working_dev = NULL;
  7985. int i, working_devs = 0, working_procs = 0;
  7986. int divx;
  7987. bool bad = false;
  7988. // Find the highest temperature of all processors
  7989. for (i = 0; i < total_devices; ++i)
  7990. {
  7991. proc = get_devices(i);
  7992. if (proc->temp > temp)
  7993. temp = proc->temp;
  7994. if (unlikely(proc->deven == DEV_DISABLED))
  7995. ; // Just need to block it off from both conditions
  7996. else
  7997. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  7998. {
  7999. if (proc->rolling > .1)
  8000. {
  8001. ++working_procs;
  8002. if (proc->device != last_working_dev)
  8003. {
  8004. ++working_devs;
  8005. last_working_dev = proc->device;
  8006. }
  8007. }
  8008. }
  8009. else
  8010. bad = true;
  8011. }
  8012. if (working_devs == working_procs)
  8013. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  8014. else
  8015. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  8016. divx = 7;
  8017. if (opt_show_procs && !opt_compact)
  8018. divx += max_lpdigits;
  8019. if (bad)
  8020. {
  8021. divx += sizeof(U8_BAD_START)-1;
  8022. strcpy(&statusline[divx], U8_BAD_END);
  8023. divx += sizeof(U8_BAD_END)-1;
  8024. }
  8025. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  8026. format_statline(statusline, sizeof(statusline),
  8027. cHr, aHr,
  8028. uHr,
  8029. ui_accepted,
  8030. ui_rejected,
  8031. ui_stale,
  8032. total_diff_rejected + total_diff_stale, total_diff_accepted,
  8033. hw_errors,
  8034. total_bad_diff1, total_bad_diff1 + total_diff1);
  8035. unlock_curses();
  8036. }
  8037. #endif
  8038. // Add a space
  8039. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  8040. uHr[5] = ' ';
  8041. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  8042. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  8043. snprintf(logstatusline, sizeof(logstatusline),
  8044. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  8045. want_per_device_stats ? "ALL " : "",
  8046. opt_log_interval,
  8047. cHr, aHr,
  8048. uHr,
  8049. ui_accepted,
  8050. ui_rejected,
  8051. ui_stale,
  8052. rejpcbuf,
  8053. hw_errors,
  8054. bnbuf
  8055. );
  8056. local_mhashes_done = 0;
  8057. out_unlock:
  8058. mutex_unlock(&hash_lock);
  8059. if (showlog) {
  8060. if (!curses_active) {
  8061. if (want_per_device_stats)
  8062. printf("\n%s\r", logstatusline);
  8063. else
  8064. {
  8065. const int logstatusline_len = strlen(logstatusline);
  8066. int padding;
  8067. if (last_logstatusline_len > logstatusline_len)
  8068. padding = (last_logstatusline_len - logstatusline_len);
  8069. else
  8070. {
  8071. padding = 0;
  8072. if (last_logstatusline_len == -1)
  8073. puts("");
  8074. }
  8075. printf("%s%*s\r", logstatusline, padding, "");
  8076. last_logstatusline_len = logstatusline_len;
  8077. }
  8078. fflush(stdout);
  8079. } else
  8080. applog(LOG_INFO, "%s", logstatusline);
  8081. }
  8082. }
  8083. void hashmeter2(struct thr_info *thr)
  8084. {
  8085. struct timeval tv_now, tv_elapsed;
  8086. timerclear(&thr->tv_hashes_done);
  8087. cgtime(&tv_now);
  8088. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  8089. /* Update the hashmeter at most 5 times per second */
  8090. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  8091. tv_elapsed.tv_sec >= opt_log_interval) {
  8092. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  8093. thr->hashes_done = 0;
  8094. thr->tv_lastupdate = tv_now;
  8095. }
  8096. }
  8097. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  8098. struct stratum_share *sshare)
  8099. {
  8100. struct work *work = sshare->work;
  8101. share_result(val, res_val, err_val, work, false, "");
  8102. }
  8103. /* Parses stratum json responses and tries to find the id that the request
  8104. * matched to and treat it accordingly. */
  8105. bool parse_stratum_response(struct pool *pool, char *s)
  8106. {
  8107. json_t *val = NULL, *err_val, *res_val, *id_val;
  8108. struct stratum_share *sshare;
  8109. json_error_t err;
  8110. bool ret = false;
  8111. int id;
  8112. val = JSON_LOADS(s, &err);
  8113. if (!val) {
  8114. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  8115. goto out;
  8116. }
  8117. res_val = json_object_get(val, "result");
  8118. err_val = json_object_get(val, "error");
  8119. id_val = json_object_get(val, "id");
  8120. if (json_is_null(id_val) || !id_val) {
  8121. char *ss;
  8122. if (err_val)
  8123. ss = json_dumps(err_val, JSON_INDENT(3));
  8124. else
  8125. ss = strdup("(unknown reason)");
  8126. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  8127. free(ss);
  8128. goto out;
  8129. }
  8130. if (!json_is_integer(id_val)) {
  8131. if (json_is_string(id_val)
  8132. && !strncmp(json_string_value(id_val), "txlist", 6))
  8133. {
  8134. const bool is_array = json_is_array(res_val);
  8135. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  8136. is_array ? "transaction list" : "no-transaction-list response",
  8137. pool->pool_no, &json_string_value(id_val)[6]);
  8138. if (!is_array)
  8139. {
  8140. // No need to wait for a timeout
  8141. timer_unset(&pool->swork.tv_transparency);
  8142. pool_set_opaque(pool, true);
  8143. goto fishy;
  8144. }
  8145. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id))
  8146. // We only care about a transaction list for the current job id
  8147. goto fishy;
  8148. // Check that the transactions actually hash to the merkle links
  8149. {
  8150. unsigned maxtx = 1 << pool->swork.merkles;
  8151. unsigned mintx = maxtx >> 1;
  8152. --maxtx;
  8153. unsigned acttx = (unsigned)json_array_size(res_val);
  8154. if (acttx < mintx || acttx > maxtx) {
  8155. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  8156. pool->pool_no, acttx, mintx, maxtx);
  8157. goto fishy;
  8158. }
  8159. // TODO: Check hashes match actual merkle links
  8160. }
  8161. pool_set_opaque(pool, false);
  8162. timer_unset(&pool->swork.tv_transparency);
  8163. fishy:
  8164. ret = true;
  8165. }
  8166. goto out;
  8167. }
  8168. id = json_integer_value(id_val);
  8169. mutex_lock(&sshare_lock);
  8170. HASH_FIND_INT(stratum_shares, &id, sshare);
  8171. if (sshare)
  8172. HASH_DEL(stratum_shares, sshare);
  8173. mutex_unlock(&sshare_lock);
  8174. if (!sshare) {
  8175. double pool_diff;
  8176. /* Since the share is untracked, we can only guess at what the
  8177. * work difficulty is based on the current pool diff. */
  8178. cg_rlock(&pool->data_lock);
  8179. pool_diff = target_diff(pool->swork.target);
  8180. cg_runlock(&pool->data_lock);
  8181. if (json_is_true(res_val)) {
  8182. struct mining_goal_info * const goal = pool->goal;
  8183. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  8184. /* We don't know what device this came from so we can't
  8185. * attribute the work to the relevant cgpu */
  8186. mutex_lock(&stats_lock);
  8187. total_accepted++;
  8188. pool->accepted++;
  8189. total_diff_accepted += pool_diff;
  8190. pool->diff_accepted += pool_diff;
  8191. goal->diff_accepted += pool_diff;
  8192. mutex_unlock(&stats_lock);
  8193. } else {
  8194. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  8195. mutex_lock(&stats_lock);
  8196. total_rejected++;
  8197. pool->rejected++;
  8198. total_diff_rejected += pool_diff;
  8199. pool->diff_rejected += pool_diff;
  8200. mutex_unlock(&stats_lock);
  8201. }
  8202. goto out;
  8203. }
  8204. else {
  8205. mutex_lock(&submitting_lock);
  8206. --total_submitting;
  8207. mutex_unlock(&submitting_lock);
  8208. }
  8209. stratum_share_result(val, res_val, err_val, sshare);
  8210. free_work(sshare->work);
  8211. free(sshare);
  8212. ret = true;
  8213. out:
  8214. if (val)
  8215. json_decref(val);
  8216. return ret;
  8217. }
  8218. static void shutdown_stratum(struct pool *pool)
  8219. {
  8220. // Shut down Stratum as if we never had it
  8221. pool->stratum_active = false;
  8222. pool->stratum_init = false;
  8223. pool->has_stratum = false;
  8224. shutdown(pool->sock, SHUT_RDWR);
  8225. free(pool->stratum_url);
  8226. if (pool->sockaddr_url == pool->stratum_url)
  8227. pool->sockaddr_url = NULL;
  8228. pool->stratum_url = NULL;
  8229. }
  8230. void clear_stratum_shares(struct pool *pool)
  8231. {
  8232. int my_mining_threads = mining_threads; // Cached outside of locking
  8233. struct stratum_share *sshare, *tmpshare;
  8234. struct work *work;
  8235. struct cgpu_info *cgpu;
  8236. double diff_cleared = 0;
  8237. double thr_diff_cleared[my_mining_threads];
  8238. int cleared = 0;
  8239. int thr_cleared[my_mining_threads];
  8240. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  8241. for (int i = 0; i < my_mining_threads; ++i)
  8242. {
  8243. thr_diff_cleared[i] = 0;
  8244. thr_cleared[i] = 0;
  8245. }
  8246. mutex_lock(&sshare_lock);
  8247. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  8248. work = sshare->work;
  8249. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  8250. HASH_DEL(stratum_shares, sshare);
  8251. sharelog("disconnect", work);
  8252. diff_cleared += sshare->work->work_difficulty;
  8253. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  8254. ++thr_cleared[work->thr_id];
  8255. free_work(sshare->work);
  8256. free(sshare);
  8257. cleared++;
  8258. }
  8259. }
  8260. mutex_unlock(&sshare_lock);
  8261. if (cleared) {
  8262. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  8263. mutex_lock(&stats_lock);
  8264. pool->stale_shares += cleared;
  8265. total_stale += cleared;
  8266. pool->diff_stale += diff_cleared;
  8267. total_diff_stale += diff_cleared;
  8268. for (int i = 0; i < my_mining_threads; ++i)
  8269. if (thr_cleared[i])
  8270. {
  8271. cgpu = get_thr_cgpu(i);
  8272. cgpu->diff_stale += thr_diff_cleared[i];
  8273. cgpu->stale += thr_cleared[i];
  8274. }
  8275. mutex_unlock(&stats_lock);
  8276. mutex_lock(&submitting_lock);
  8277. total_submitting -= cleared;
  8278. mutex_unlock(&submitting_lock);
  8279. }
  8280. }
  8281. static void resubmit_stratum_shares(struct pool *pool)
  8282. {
  8283. struct stratum_share *sshare, *tmpshare;
  8284. struct work *work;
  8285. unsigned resubmitted = 0;
  8286. mutex_lock(&sshare_lock);
  8287. mutex_lock(&submitting_lock);
  8288. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  8289. if (sshare->work->pool != pool)
  8290. continue;
  8291. HASH_DEL(stratum_shares, sshare);
  8292. work = sshare->work;
  8293. DL_APPEND(submit_waiting, work);
  8294. free(sshare);
  8295. ++resubmitted;
  8296. }
  8297. mutex_unlock(&submitting_lock);
  8298. mutex_unlock(&sshare_lock);
  8299. if (resubmitted) {
  8300. notifier_wake(submit_waiting_notifier);
  8301. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  8302. }
  8303. }
  8304. static void clear_pool_work(struct pool *pool)
  8305. {
  8306. struct work *work, *tmp;
  8307. int cleared = 0;
  8308. mutex_lock(stgd_lock);
  8309. HASH_ITER(hh, staged_work, work, tmp) {
  8310. if (work->pool == pool) {
  8311. unstage_work(work);
  8312. free_work(work);
  8313. cleared++;
  8314. }
  8315. }
  8316. mutex_unlock(stgd_lock);
  8317. }
  8318. static int cp_prio(void)
  8319. {
  8320. int prio;
  8321. cg_rlock(&control_lock);
  8322. prio = currentpool->prio;
  8323. cg_runlock(&control_lock);
  8324. return prio;
  8325. }
  8326. /* We only need to maintain a secondary pool connection when we need the
  8327. * capacity to get work from the backup pools while still on the primary */
  8328. static bool cnx_needed(struct pool *pool)
  8329. {
  8330. struct pool *cp;
  8331. // We want to keep a connection open for rejecting or misbehaving pools, to detect when/if they change their tune
  8332. if (pool->enabled == POOL_DISABLED)
  8333. return false;
  8334. /* Idle stratum pool needs something to kick it alive again */
  8335. if (pool->has_stratum && pool->idle)
  8336. return true;
  8337. /* Getwork pools without opt_fail_only need backup pools up to be able
  8338. * to leak shares */
  8339. cp = current_pool();
  8340. if (pool_actively_desired(pool, cp))
  8341. return true;
  8342. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  8343. return true;
  8344. /* Keep the connection open to allow any stray shares to be submitted
  8345. * on switching pools for 2 minutes. */
  8346. if (timer_elapsed(&pool->tv_last_work_time, NULL) < 120)
  8347. return true;
  8348. /* If the pool has only just come to life and is higher priority than
  8349. * the current pool keep the connection open so we can fail back to
  8350. * it. */
  8351. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8352. return true;
  8353. if (pool_unworkable(cp))
  8354. return true;
  8355. /* We've run out of work, bring anything back to life. */
  8356. if (no_work)
  8357. return true;
  8358. // If the current pool lacks its own block change detection, see if we are needed for that
  8359. if (pool_active_lp_pool(cp) == pool)
  8360. return true;
  8361. return false;
  8362. }
  8363. static void wait_lpcurrent(struct pool *pool);
  8364. static void pool_resus(struct pool *pool);
  8365. static void stratum_resumed(struct pool *pool)
  8366. {
  8367. if (!pool->stratum_notify)
  8368. return;
  8369. if (pool_tclear(pool, &pool->idle)) {
  8370. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  8371. pool_resus(pool);
  8372. }
  8373. }
  8374. static bool supports_resume(struct pool *pool)
  8375. {
  8376. bool ret;
  8377. cg_rlock(&pool->data_lock);
  8378. ret = (pool->sessionid != NULL);
  8379. cg_runlock(&pool->data_lock);
  8380. return ret;
  8381. }
  8382. static bool pools_active;
  8383. /* One stratum thread per pool that has stratum waits on the socket checking
  8384. * for new messages and for the integrity of the socket connection. We reset
  8385. * the connection based on the integrity of the receive side only as the send
  8386. * side will eventually expire data it fails to send. */
  8387. static void *stratum_thread(void *userdata)
  8388. {
  8389. struct pool *pool = (struct pool *)userdata;
  8390. pthread_detach(pthread_self());
  8391. char threadname[20];
  8392. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  8393. RenameThread(threadname);
  8394. srand(time(NULL) + (intptr_t)userdata);
  8395. while (42) {
  8396. struct timeval timeout;
  8397. int sel_ret;
  8398. fd_set rd;
  8399. char *s;
  8400. int sock;
  8401. if (unlikely(!pool->has_stratum))
  8402. break;
  8403. /* Check to see whether we need to maintain this connection
  8404. * indefinitely or just bring it up when we switch to this
  8405. * pool */
  8406. while (true)
  8407. {
  8408. sock = pool->sock;
  8409. if (sock == INVSOCK)
  8410. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  8411. pool->pool_no);
  8412. else
  8413. if (!sock_full(pool) && !cnx_needed(pool) && pools_active)
  8414. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  8415. pool->pool_no);
  8416. else
  8417. break;
  8418. suspend_stratum(pool);
  8419. clear_stratum_shares(pool);
  8420. clear_pool_work(pool);
  8421. wait_lpcurrent(pool);
  8422. if (!restart_stratum(pool)) {
  8423. pool_died(pool);
  8424. while (!restart_stratum(pool)) {
  8425. if (pool->removed)
  8426. goto out;
  8427. cgsleep_ms(30000);
  8428. }
  8429. }
  8430. }
  8431. FD_ZERO(&rd);
  8432. FD_SET(sock, &rd);
  8433. timeout.tv_sec = 120;
  8434. timeout.tv_usec = 0;
  8435. /* If we fail to receive any notify messages for 2 minutes we
  8436. * assume the connection has been dropped and treat this pool
  8437. * as dead */
  8438. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  8439. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  8440. s = NULL;
  8441. } else
  8442. s = recv_line(pool);
  8443. if (!s) {
  8444. if (!pool->has_stratum)
  8445. break;
  8446. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  8447. pool->getfail_occasions++;
  8448. total_go++;
  8449. mutex_lock(&pool->stratum_lock);
  8450. pool->stratum_active = pool->stratum_notify = false;
  8451. pool->sock = INVSOCK;
  8452. mutex_unlock(&pool->stratum_lock);
  8453. /* If the socket to our stratum pool disconnects, all
  8454. * submissions need to be discarded or resent. */
  8455. if (!supports_resume(pool))
  8456. clear_stratum_shares(pool);
  8457. else
  8458. resubmit_stratum_shares(pool);
  8459. clear_pool_work(pool);
  8460. if (pool == current_pool())
  8461. restart_threads();
  8462. if (restart_stratum(pool))
  8463. continue;
  8464. shutdown_stratum(pool);
  8465. pool_died(pool);
  8466. break;
  8467. }
  8468. /* Check this pool hasn't died while being a backup pool and
  8469. * has not had its idle flag cleared */
  8470. stratum_resumed(pool);
  8471. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  8472. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  8473. free(s);
  8474. if (pool->swork.clean) {
  8475. struct work *work = make_work();
  8476. /* Generate a single work item to update the current
  8477. * block database */
  8478. pool->swork.clean = false;
  8479. gen_stratum_work(pool, work);
  8480. /* Try to extract block height from coinbase scriptSig */
  8481. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  8482. unsigned char cb_height_sz;
  8483. cb_height_sz = bin_height[-1];
  8484. if (cb_height_sz == 3) {
  8485. // FIXME: The block number will overflow this by AD 2173
  8486. struct mining_goal_info * const goal = pool->goal;
  8487. const void * const prevblkhash = &work->data[4];
  8488. uint32_t height = 0;
  8489. memcpy(&height, bin_height, 3);
  8490. height = le32toh(height);
  8491. have_block_height(goal, prevblkhash, height);
  8492. }
  8493. pool->swork.work_restart_id =
  8494. ++pool->work_restart_id;
  8495. pool_update_work_restart_time(pool);
  8496. if (test_work_current(work)) {
  8497. /* Only accept a work update if this stratum
  8498. * connection is from the current pool */
  8499. struct pool * const cp = current_pool();
  8500. if (pool == cp)
  8501. restart_threads();
  8502. applog(
  8503. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  8504. "Stratum from pool %d requested work update", pool->pool_no);
  8505. } else
  8506. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  8507. free_work(work);
  8508. }
  8509. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  8510. // More than 4 timmills past since requested transactions
  8511. timer_unset(&pool->swork.tv_transparency);
  8512. pool_set_opaque(pool, true);
  8513. }
  8514. }
  8515. out:
  8516. return NULL;
  8517. }
  8518. static void init_stratum_thread(struct pool *pool)
  8519. {
  8520. struct mining_goal_info * const goal = pool->goal;
  8521. goal->have_longpoll = true;
  8522. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  8523. quit(1, "Failed to create stratum thread");
  8524. }
  8525. static void *longpoll_thread(void *userdata);
  8526. static bool stratum_works(struct pool *pool)
  8527. {
  8528. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  8529. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  8530. return false;
  8531. if (pool->stratum_active)
  8532. return true;
  8533. if (!initiate_stratum(pool))
  8534. return false;
  8535. return true;
  8536. }
  8537. static
  8538. bool pool_recently_got_work(struct pool * const pool, const struct timeval * const tvp_now)
  8539. {
  8540. return (timer_isset(&pool->tv_last_work_time) && timer_elapsed(&pool->tv_last_work_time, tvp_now) < 60);
  8541. }
  8542. static bool pool_active(struct pool *pool, bool pinging)
  8543. {
  8544. struct timeval tv_now, tv_getwork, tv_getwork_reply;
  8545. bool ret = false;
  8546. json_t *val;
  8547. CURL *curl = NULL;
  8548. int rolltime;
  8549. char *rpc_req;
  8550. struct work *work;
  8551. enum pool_protocol proto;
  8552. if (pool->stratum_init)
  8553. {
  8554. if (pool->stratum_active)
  8555. return true;
  8556. }
  8557. else
  8558. if (!pool->idle)
  8559. {
  8560. timer_set_now(&tv_now);
  8561. if (pool_recently_got_work(pool, &tv_now))
  8562. return true;
  8563. }
  8564. mutex_lock(&pool->pool_test_lock);
  8565. if (pool->stratum_init)
  8566. {
  8567. ret = pool->stratum_active;
  8568. goto out;
  8569. }
  8570. timer_set_now(&tv_now);
  8571. if (pool->idle)
  8572. {
  8573. if (timer_elapsed(&pool->tv_idle, &tv_now) < 30)
  8574. goto out;
  8575. }
  8576. else
  8577. if (pool_recently_got_work(pool, &tv_now))
  8578. {
  8579. ret = true;
  8580. goto out;
  8581. }
  8582. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  8583. /* This is the central point we activate stratum when we can */
  8584. curl = curl_easy_init();
  8585. if (unlikely(!curl)) {
  8586. applog(LOG_ERR, "CURL initialisation failed");
  8587. goto out;
  8588. }
  8589. if (!(want_gbt || want_getwork))
  8590. goto nohttp;
  8591. work = make_work();
  8592. /* Probe for GBT support on first pass */
  8593. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  8594. tryagain:
  8595. rpc_req = prepare_rpc_req_probe(work, proto, NULL, pool);
  8596. work->pool = pool;
  8597. if (!rpc_req)
  8598. goto out;
  8599. pool->probed = false;
  8600. cgtime(&tv_getwork);
  8601. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  8602. true, false, &rolltime, pool, false);
  8603. cgtime(&tv_getwork_reply);
  8604. free(rpc_req);
  8605. /* Detect if a http getwork pool has an X-Stratum header at startup,
  8606. * and if so, switch to that in preference to getwork if it works */
  8607. if (pool->stratum_url && want_stratum && pool_may_redirect_to(pool, pool->stratum_url) && (pool->has_stratum || stratum_works(pool))) {
  8608. if (!pool->has_stratum) {
  8609. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  8610. if (!pool->rpc_url)
  8611. pool_set_uri(pool, strdup(pool->stratum_url));
  8612. pool->has_stratum = true;
  8613. }
  8614. free_work(work);
  8615. if (val)
  8616. json_decref(val);
  8617. retry_stratum:
  8618. ;
  8619. /* We create the stratum thread for each pool just after
  8620. * successful authorisation. Once the init flag has been set
  8621. * we never unset it and the stratum thread is responsible for
  8622. * setting/unsetting the active flag */
  8623. bool init = pool_tset(pool, &pool->stratum_init);
  8624. if (!init) {
  8625. ret = initiate_stratum(pool) && auth_stratum(pool);
  8626. if (ret)
  8627. {
  8628. detect_algo = 2;
  8629. init_stratum_thread(pool);
  8630. }
  8631. else
  8632. {
  8633. pool_tclear(pool, &pool->stratum_init);
  8634. pool->tv_idle = tv_getwork_reply;
  8635. }
  8636. goto out;
  8637. }
  8638. ret = pool->stratum_active;
  8639. goto out;
  8640. }
  8641. else if (pool->has_stratum)
  8642. shutdown_stratum(pool);
  8643. if (val) {
  8644. bool rc;
  8645. json_t *res;
  8646. res = json_object_get(val, "result");
  8647. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  8648. goto badwork;
  8649. work->rolltime = rolltime;
  8650. rc = work_decode(pool, work, val);
  8651. if (rc) {
  8652. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  8653. pool->pool_no, pool->rpc_url);
  8654. work->pool = pool;
  8655. copy_time(&work->tv_getwork, &tv_getwork);
  8656. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  8657. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  8658. calc_diff(work, 0);
  8659. update_last_work(work);
  8660. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  8661. stage_work(work);
  8662. total_getworks++;
  8663. pool->getwork_requested++;
  8664. ret = true;
  8665. pool->tv_idle = tv_getwork_reply;
  8666. } else {
  8667. badwork:
  8668. json_decref(val);
  8669. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  8670. pool->pool_no, pool->rpc_url);
  8671. pool->proto = proto = pool_protocol_fallback(proto);
  8672. if (PLP_NONE != proto)
  8673. goto tryagain;
  8674. pool->tv_idle = tv_getwork_reply;
  8675. free_work(work);
  8676. goto out;
  8677. }
  8678. json_decref(val);
  8679. if (proto != pool->proto) {
  8680. pool->proto = proto;
  8681. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  8682. }
  8683. if (pool->lp_url)
  8684. goto out;
  8685. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  8686. const struct blktmpl_longpoll_req *lp;
  8687. if (work->tr && (lp = blktmpl_get_longpoll(work->tr->tmpl))) {
  8688. // NOTE: work_decode takes care of lp id
  8689. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  8690. if (!pool->lp_url)
  8691. {
  8692. ret = false;
  8693. goto out;
  8694. }
  8695. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  8696. }
  8697. else
  8698. if (pool->hdr_path && want_getwork) {
  8699. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  8700. if (!pool->lp_url)
  8701. {
  8702. ret = false;
  8703. goto out;
  8704. }
  8705. pool->lp_proto = PLP_GETWORK;
  8706. } else
  8707. pool->lp_url = NULL;
  8708. if (want_longpoll && !pool->lp_started) {
  8709. pool->lp_started = true;
  8710. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8711. quit(1, "Failed to create pool longpoll thread");
  8712. }
  8713. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  8714. pool->proto = proto;
  8715. goto tryagain;
  8716. } else {
  8717. pool->tv_idle = tv_getwork_reply;
  8718. free_work(work);
  8719. nohttp:
  8720. /* If we failed to parse a getwork, this could be a stratum
  8721. * url without the prefix stratum+tcp:// so let's check it */
  8722. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  8723. pool->has_stratum = true;
  8724. goto retry_stratum;
  8725. }
  8726. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  8727. pool->pool_no, pool->rpc_url);
  8728. if (!pinging)
  8729. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  8730. }
  8731. out:
  8732. if (curl)
  8733. curl_easy_cleanup(curl);
  8734. mutex_unlock(&pool->pool_test_lock);
  8735. return ret;
  8736. }
  8737. static void pool_resus(struct pool *pool)
  8738. {
  8739. if (pool->enabled == POOL_ENABLED && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8740. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  8741. else
  8742. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  8743. }
  8744. static
  8745. void *cmd_idle_thread(void * const __maybe_unused userp)
  8746. {
  8747. pthread_detach(pthread_self());
  8748. RenameThread("cmd-idle");
  8749. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8750. sleep(opt_log_interval);
  8751. pthread_testcancel();
  8752. run_cmd(cmd_idle);
  8753. return NULL;
  8754. }
  8755. static struct work *hash_pop(struct cgpu_info * const proc)
  8756. {
  8757. int hc;
  8758. struct work *work, *work_found, *tmp;
  8759. enum {
  8760. HPWS_NONE,
  8761. HPWS_LOWDIFF,
  8762. HPWS_SPARE,
  8763. HPWS_ROLLABLE,
  8764. HPWS_PERFECT,
  8765. } work_score = HPWS_NONE;
  8766. bool did_cmd_idle = false;
  8767. pthread_t cmd_idle_thr;
  8768. retry:
  8769. mutex_lock(stgd_lock);
  8770. while (true)
  8771. {
  8772. work_found = NULL;
  8773. work_score = 0;
  8774. hc = HASH_COUNT(staged_work);
  8775. HASH_ITER(hh, staged_work, work, tmp)
  8776. {
  8777. const struct mining_algorithm * const work_malgo = work_mining_algorithm(work);
  8778. const float min_nonce_diff = drv_min_nonce_diff(proc->drv, proc, work_malgo);
  8779. #define FOUND_WORK(score) do{ \
  8780. if (work_score < score) \
  8781. { \
  8782. work_found = work; \
  8783. work_score = score; \
  8784. } \
  8785. continue; \
  8786. }while(0)
  8787. if (min_nonce_diff < work->work_difficulty)
  8788. {
  8789. if (min_nonce_diff < 0)
  8790. continue;
  8791. FOUND_WORK(HPWS_LOWDIFF);
  8792. }
  8793. if (work->spare)
  8794. FOUND_WORK(HPWS_SPARE);
  8795. if (work->rolltime && hc > staged_rollable)
  8796. FOUND_WORK(HPWS_ROLLABLE);
  8797. #undef FOUND_WORK
  8798. // Good match
  8799. work_found = work;
  8800. work_score = HPWS_PERFECT;
  8801. break;
  8802. }
  8803. if (work_found)
  8804. {
  8805. work = work_found;
  8806. break;
  8807. }
  8808. // Failed to get a usable work
  8809. if (unlikely(staged_full))
  8810. {
  8811. if (likely(opt_queue < 10 + mining_threads))
  8812. {
  8813. ++opt_queue;
  8814. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  8815. }
  8816. else
  8817. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  8818. staged_full = false; // Let it fill up before triggering an underrun again
  8819. no_work = true;
  8820. }
  8821. pthread_cond_signal(&gws_cond);
  8822. if (cmd_idle && !did_cmd_idle)
  8823. {
  8824. if (likely(!pthread_create(&cmd_idle_thr, NULL, cmd_idle_thread, NULL)))
  8825. did_cmd_idle = true;
  8826. }
  8827. pthread_cond_wait(&getq->cond, stgd_lock);
  8828. }
  8829. if (did_cmd_idle)
  8830. pthread_cancel(cmd_idle_thr);
  8831. no_work = false;
  8832. if (can_roll(work) && should_roll(work))
  8833. {
  8834. // Instead of consuming it, force it to be cloned and grab the clone
  8835. mutex_unlock(stgd_lock);
  8836. clone_available();
  8837. goto retry;
  8838. }
  8839. unstage_work(work);
  8840. /* Signal the getwork scheduler to look for more work */
  8841. pthread_cond_signal(&gws_cond);
  8842. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  8843. pthread_cond_signal(&getq->cond);
  8844. mutex_unlock(stgd_lock);
  8845. work->pool->last_work_time = time(NULL);
  8846. cgtime(&work->pool->tv_last_work_time);
  8847. return work;
  8848. }
  8849. /* Clones work by rolling it if possible, and returning a clone instead of the
  8850. * original work item which gets staged again to possibly be rolled again in
  8851. * the future */
  8852. static struct work *clone_work(struct work *work)
  8853. {
  8854. int mrs = mining_threads + opt_queue - total_staged(false);
  8855. struct work *work_clone;
  8856. bool cloned;
  8857. if (mrs < 1)
  8858. return work;
  8859. cloned = false;
  8860. work_clone = make_clone(work);
  8861. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  8862. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  8863. stage_work(work_clone);
  8864. roll_work(work);
  8865. work_clone = make_clone(work);
  8866. /* Roll it again to prevent duplicates should this be used
  8867. * directly later on */
  8868. roll_work(work);
  8869. cloned = true;
  8870. }
  8871. if (cloned) {
  8872. stage_work(work);
  8873. return work_clone;
  8874. }
  8875. free_work(work_clone);
  8876. return work;
  8877. }
  8878. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  8879. {
  8880. unsigned char hash1[32];
  8881. sha256(data, len, hash1);
  8882. sha256(hash1, 32, hash);
  8883. }
  8884. /* PDiff 1 is a 256 bit unsigned integer of
  8885. * 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  8886. * so we use a big endian 32 bit unsigned integer positioned at the Nth byte to
  8887. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  8888. static void pdiff_target_leadzero(void * const target_p, double diff)
  8889. {
  8890. uint8_t *target = target_p;
  8891. diff *= 0x100000000;
  8892. int skip = log2(diff) / 8;
  8893. if (skip)
  8894. {
  8895. if (skip > 0x1c)
  8896. skip = 0x1c;
  8897. diff /= pow(0x100, skip);
  8898. memset(target, 0, skip);
  8899. }
  8900. uint32_t n = 0xffffffff;
  8901. n = (double)n / diff;
  8902. n = htobe32(n);
  8903. memcpy(&target[skip], &n, sizeof(n));
  8904. memset(&target[skip + sizeof(n)], 0xff, 32 - (skip + sizeof(n)));
  8905. }
  8906. void set_target_to_pdiff(void * const dest_target, const double pdiff)
  8907. {
  8908. unsigned char rtarget[32];
  8909. pdiff_target_leadzero(rtarget, pdiff);
  8910. swab256(dest_target, rtarget);
  8911. if (opt_debug) {
  8912. char htarget[65];
  8913. bin2hex(htarget, rtarget, 32);
  8914. applog(LOG_DEBUG, "Generated target %s", htarget);
  8915. }
  8916. }
  8917. void set_target_to_bdiff(void * const dest_target, const double bdiff)
  8918. {
  8919. set_target_to_pdiff(dest_target, bdiff_to_pdiff(bdiff));
  8920. }
  8921. void _test_target(void * const funcp, const char * const funcname, const bool little_endian, const void * const expectp, const double diff)
  8922. {
  8923. uint8_t bufr[32], buf[32], expectr[32], expect[32];
  8924. int off;
  8925. void (*func)(void *, double) = funcp;
  8926. func(little_endian ? bufr : buf, diff);
  8927. if (little_endian)
  8928. swab256(buf, bufr);
  8929. swap32tobe(expect, expectp, 256/32);
  8930. // Fuzzy comparison: the first 32 bits set must match, and the actual target must be >= the expected
  8931. for (off = 0; off < 28 && !buf[off]; ++off)
  8932. {}
  8933. if (memcmp(&buf[off], &expect[off], 4))
  8934. {
  8935. testfail: ;
  8936. ++unittest_failures;
  8937. char hexbuf[65], expectbuf[65];
  8938. bin2hex(hexbuf, buf, 32);
  8939. bin2hex(expectbuf, expect, 32);
  8940. applogr(, LOG_WARNING, "%s test failed: diff %g got %s (expected %s)",
  8941. funcname, diff, hexbuf, expectbuf);
  8942. }
  8943. if (!little_endian)
  8944. swab256(bufr, buf);
  8945. swab256(expectr, expect);
  8946. if (!hash_target_check(expectr, bufr))
  8947. goto testfail;
  8948. }
  8949. #define TEST_TARGET(func, le, expect, diff) \
  8950. _test_target(func, #func, le, expect, diff)
  8951. void test_target()
  8952. {
  8953. uint32_t expect[8] = {0};
  8954. // bdiff 1 should be exactly 00000000ffff0000000006f29cfd29510a6caee84634e86a57257cf03152537f due to floating-point imprecision (pdiff1 / 1.0000152590218966)
  8955. expect[0] = 0x0000ffff;
  8956. TEST_TARGET(set_target_to_bdiff, true, expect, 1./0x10000);
  8957. expect[0] = 0;
  8958. expect[1] = 0xffff0000;
  8959. TEST_TARGET(set_target_to_bdiff, true, expect, 1);
  8960. expect[1] >>= 1;
  8961. TEST_TARGET(set_target_to_bdiff, true, expect, 2);
  8962. expect[1] >>= 3;
  8963. TEST_TARGET(set_target_to_bdiff, true, expect, 0x10);
  8964. expect[1] >>= 4;
  8965. TEST_TARGET(set_target_to_bdiff, true, expect, 0x100);
  8966. memset(&expect[1], '\xff', 28);
  8967. expect[0] = 0x0000ffff;
  8968. TEST_TARGET(set_target_to_pdiff, true, expect, 1./0x10000);
  8969. expect[0] = 0;
  8970. TEST_TARGET(set_target_to_pdiff, true, expect, 1);
  8971. expect[1] >>= 1;
  8972. TEST_TARGET(set_target_to_pdiff, true, expect, 2);
  8973. expect[1] >>= 3;
  8974. TEST_TARGET(set_target_to_pdiff, true, expect, 0x10);
  8975. expect[1] >>= 4;
  8976. TEST_TARGET(set_target_to_pdiff, true, expect, 0x100);
  8977. }
  8978. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  8979. {
  8980. *dst = *src;
  8981. if (dst->tr)
  8982. tmpl_incref(dst->tr);
  8983. dst->nonce1 = maybe_strdup(src->nonce1);
  8984. dst->job_id = maybe_strdup(src->job_id);
  8985. bytes_cpy(&dst->coinbase, &src->coinbase);
  8986. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  8987. }
  8988. void stratum_work_clean(struct stratum_work * const swork)
  8989. {
  8990. if (swork->tr)
  8991. tmpl_decref(swork->tr);
  8992. free(swork->nonce1);
  8993. free(swork->job_id);
  8994. bytes_free(&swork->coinbase);
  8995. bytes_free(&swork->merkle_bin);
  8996. }
  8997. bool pool_has_usable_swork(const struct pool * const pool)
  8998. {
  8999. if (opt_benchmark)
  9000. return true;
  9001. if (pool->swork.tr)
  9002. {
  9003. // GBT
  9004. struct timeval tv_now;
  9005. timer_set_now(&tv_now);
  9006. return blkmk_time_left(pool->swork.tr->tmpl, tv_now.tv_sec);
  9007. }
  9008. return pool->stratum_notify;
  9009. }
  9010. /* Generates stratum based work based on the most recent notify information
  9011. * from the pool. This will keep generating work while a pool is down so we use
  9012. * other means to detect when the pool has died in stratum_thread */
  9013. static void gen_stratum_work(struct pool *pool, struct work *work)
  9014. {
  9015. clean_work(work);
  9016. cg_wlock(&pool->data_lock);
  9017. pool->swork.data_lock_p = &pool->data_lock;
  9018. const int n2size = pool->swork.n2size;
  9019. bytes_resize(&work->nonce2, n2size);
  9020. if (pool->nonce2sz < n2size)
  9021. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, n2size - pool->nonce2sz);
  9022. memcpy(bytes_buf(&work->nonce2),
  9023. #ifdef WORDS_BIGENDIAN
  9024. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  9025. &((char*)&pool->nonce2)[pool->nonce2off],
  9026. #else
  9027. &pool->nonce2,
  9028. #endif
  9029. pool->nonce2sz);
  9030. pool->nonce2++;
  9031. work->pool = pool;
  9032. work->work_restart_id = pool->swork.work_restart_id;
  9033. gen_stratum_work2(work, &pool->swork);
  9034. cgtime(&work->tv_staged);
  9035. }
  9036. void gen_stratum_work2(struct work *work, struct stratum_work *swork)
  9037. {
  9038. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  9039. uint8_t *merkle_bin;
  9040. uint32_t *data32, *swap32;
  9041. int i;
  9042. /* Generate coinbase */
  9043. coinbase = bytes_buf(&swork->coinbase);
  9044. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  9045. /* Downgrade to a read lock to read off the variables */
  9046. if (swork->data_lock_p)
  9047. cg_dwlock(swork->data_lock_p);
  9048. /* Generate merkle root */
  9049. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  9050. memcpy(merkle_sha, merkle_root, 32);
  9051. merkle_bin = bytes_buf(&swork->merkle_bin);
  9052. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  9053. memcpy(merkle_sha + 32, merkle_bin, 32);
  9054. gen_hash(merkle_sha, merkle_root, 64);
  9055. memcpy(merkle_sha, merkle_root, 32);
  9056. }
  9057. data32 = (uint32_t *)merkle_sha;
  9058. swap32 = (uint32_t *)merkle_root;
  9059. flip32(swap32, data32);
  9060. memcpy(&work->data[0], swork->header1, 36);
  9061. memcpy(&work->data[36], merkle_root, 32);
  9062. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  9063. memcpy(&work->data[72], swork->diffbits, 4);
  9064. memset(&work->data[76], 0, 4); // nonce
  9065. memcpy(&work->data[80], workpadding_bin, 48);
  9066. work->ntime_roll_limits = swork->ntime_roll_limits;
  9067. /* Copy parameters required for share submission */
  9068. memcpy(work->target, swork->target, sizeof(work->target));
  9069. work->job_id = maybe_strdup(swork->job_id);
  9070. work->nonce1 = maybe_strdup(swork->nonce1);
  9071. if (swork->data_lock_p)
  9072. cg_runlock(swork->data_lock_p);
  9073. if (opt_debug)
  9074. {
  9075. char header[161];
  9076. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  9077. bin2hex(header, work->data, 80);
  9078. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  9079. applog(LOG_DEBUG, "Generated stratum header %s", header);
  9080. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  9081. }
  9082. calc_midstate(work);
  9083. local_work++;
  9084. work->stratum = true;
  9085. work->blk.nonce = 0;
  9086. work->id = total_work++;
  9087. work->longpoll = false;
  9088. work->getwork_mode = GETWORK_MODE_STRATUM;
  9089. calc_diff(work, 0);
  9090. }
  9091. void request_work(struct thr_info *thr)
  9092. {
  9093. struct cgpu_info *cgpu = thr->cgpu;
  9094. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  9095. /* Tell the watchdog thread this thread is waiting on getwork and
  9096. * should not be restarted */
  9097. thread_reportout(thr);
  9098. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  9099. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  9100. {
  9101. if (proc->threads)
  9102. break;
  9103. thread_reportout(proc->thr[0]);
  9104. }
  9105. cgtime(&dev_stats->_get_start);
  9106. }
  9107. // FIXME: Make this non-blocking (and remove HACK above)
  9108. struct work *get_work(struct thr_info *thr)
  9109. {
  9110. const int thr_id = thr->id;
  9111. struct cgpu_info *cgpu = thr->cgpu;
  9112. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  9113. struct cgminer_stats *pool_stats;
  9114. struct timeval tv_get;
  9115. struct work *work = NULL;
  9116. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  9117. while (!work) {
  9118. work = hash_pop(cgpu);
  9119. if (stale_work(work, false)) {
  9120. staged_full = false; // It wasn't really full, since it was stale :(
  9121. discard_work(work);
  9122. work = NULL;
  9123. wake_gws();
  9124. }
  9125. }
  9126. last_getwork = time(NULL);
  9127. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  9128. cgpu->proc_repr, work->id, thr_id);
  9129. work->thr_id = thr_id;
  9130. thread_reportin(thr);
  9131. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  9132. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  9133. {
  9134. if (proc->threads)
  9135. break;
  9136. thread_reportin(proc->thr[0]);
  9137. }
  9138. work->mined = true;
  9139. work->blk.nonce = 0;
  9140. cgtime(&tv_get);
  9141. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  9142. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  9143. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  9144. dev_stats->getwork_wait_max = tv_get;
  9145. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  9146. dev_stats->getwork_wait_min = tv_get;
  9147. ++dev_stats->getwork_calls;
  9148. pool_stats = &(work->pool->cgminer_stats);
  9149. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  9150. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  9151. pool_stats->getwork_wait_max = tv_get;
  9152. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  9153. pool_stats->getwork_wait_min = tv_get;
  9154. ++pool_stats->getwork_calls;
  9155. if (work->work_difficulty < 1)
  9156. {
  9157. const float min_nonce_diff = drv_min_nonce_diff(cgpu->drv, cgpu, work_mining_algorithm(work));
  9158. if (unlikely(work->work_difficulty < min_nonce_diff))
  9159. {
  9160. if (min_nonce_diff - work->work_difficulty > 1./0x10000000)
  9161. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  9162. cgpu->proc_repr);
  9163. work->nonce_diff = min_nonce_diff;
  9164. }
  9165. else
  9166. work->nonce_diff = work->work_difficulty;
  9167. }
  9168. else
  9169. work->nonce_diff = 1;
  9170. return work;
  9171. }
  9172. struct dupe_hash_elem {
  9173. uint8_t hash[0x20];
  9174. struct timeval tv_prune;
  9175. UT_hash_handle hh;
  9176. };
  9177. static
  9178. void _submit_work_async(struct work *work)
  9179. {
  9180. applog(LOG_DEBUG, "Pushing submit work to work thread");
  9181. if (opt_benchmark)
  9182. {
  9183. json_t * const jn = json_null(), *result = NULL;
  9184. work_check_for_block(work);
  9185. {
  9186. static struct dupe_hash_elem *dupe_hashes;
  9187. struct dupe_hash_elem *dhe, *dhetmp;
  9188. HASH_FIND(hh, dupe_hashes, &work->hash, sizeof(dhe->hash), dhe);
  9189. if (dhe)
  9190. result = json_string("duplicate");
  9191. else
  9192. {
  9193. struct timeval tv_now;
  9194. timer_set_now(&tv_now);
  9195. // Prune old entries
  9196. HASH_ITER(hh, dupe_hashes, dhe, dhetmp)
  9197. {
  9198. if (!timer_passed(&dhe->tv_prune, &tv_now))
  9199. break;
  9200. HASH_DEL(dupe_hashes, dhe);
  9201. free(dhe);
  9202. }
  9203. dhe = malloc(sizeof(*dhe));
  9204. memcpy(dhe->hash, work->hash, sizeof(dhe->hash));
  9205. timer_set_delay(&dhe->tv_prune, &tv_now, 337500000);
  9206. HASH_ADD(hh, dupe_hashes, hash, sizeof(dhe->hash), dhe);
  9207. }
  9208. }
  9209. if (result)
  9210. {}
  9211. else
  9212. if (stale_work(work, true))
  9213. {
  9214. char stalemsg[0x10];
  9215. snprintf(stalemsg, sizeof(stalemsg), "stale %us", benchmark_update_interval * (work->pool->work_restart_id - work->work_restart_id));
  9216. result = json_string(stalemsg);
  9217. }
  9218. else
  9219. result = json_incref(jn);
  9220. share_result(jn, result, jn, work, false, "");
  9221. free_work(work);
  9222. json_decref(result);
  9223. json_decref(jn);
  9224. return;
  9225. }
  9226. mutex_lock(&submitting_lock);
  9227. ++total_submitting;
  9228. DL_APPEND(submit_waiting, work);
  9229. mutex_unlock(&submitting_lock);
  9230. notifier_wake(submit_waiting_notifier);
  9231. }
  9232. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  9233. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  9234. {
  9235. if (tv_work_found)
  9236. copy_time(&work->tv_work_found, tv_work_found);
  9237. _submit_work_async(work);
  9238. }
  9239. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  9240. {
  9241. struct cgpu_info * const cgpu = thr->cgpu;
  9242. if (bad_nonce_p)
  9243. {
  9244. if (bad_nonce_p == UNKNOWN_NONCE)
  9245. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  9246. cgpu->proc_repr);
  9247. else
  9248. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  9249. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  9250. }
  9251. mutex_lock(&stats_lock);
  9252. hw_errors++;
  9253. ++cgpu->hw_errors;
  9254. if (bad_nonce_p)
  9255. {
  9256. total_bad_diff1 += nonce_diff;
  9257. cgpu->bad_diff1 += nonce_diff;
  9258. }
  9259. mutex_unlock(&stats_lock);
  9260. if (thr->cgpu->drv->hw_error)
  9261. thr->cgpu->drv->hw_error(thr);
  9262. }
  9263. void work_hash(struct work * const work)
  9264. {
  9265. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  9266. malgo->hash_data_f(work->hash, work->data);
  9267. }
  9268. static
  9269. bool test_hash(const void * const phash, const float diff)
  9270. {
  9271. const uint32_t * const hash = phash;
  9272. if (diff >= 1.)
  9273. // FIXME: > 1 should check more
  9274. return !hash[7];
  9275. const uint32_t Htarg = (uint32_t)ceil((1. / diff) - 1);
  9276. const uint32_t tmp_hash7 = le32toh(hash[7]);
  9277. applog(LOG_DEBUG, "htarget %08lx hash %08lx",
  9278. (long unsigned int)Htarg,
  9279. (long unsigned int)tmp_hash7);
  9280. return (tmp_hash7 <= Htarg);
  9281. }
  9282. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  9283. {
  9284. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  9285. *work_nonce = htole32(nonce);
  9286. work_hash(work);
  9287. if (!test_hash(work->hash, work->nonce_diff))
  9288. return TNR_BAD;
  9289. if (checktarget && !hash_target_check_v(work->hash, work->target))
  9290. {
  9291. bool high_hash = true;
  9292. struct pool * const pool = work->pool;
  9293. if (pool_diff_effective_retroactively(pool))
  9294. {
  9295. // Some stratum pools are buggy and expect difficulty changes to be immediate retroactively, so if the target has changed, check and submit just in case
  9296. if (memcmp(pool->next_target, work->target, sizeof(work->target)))
  9297. {
  9298. applog(LOG_DEBUG, "Stratum pool %u target has changed since work job issued, checking that too",
  9299. pool->pool_no);
  9300. if (hash_target_check_v(work->hash, pool->next_target))
  9301. {
  9302. high_hash = false;
  9303. work->work_difficulty = target_diff(pool->next_target);
  9304. }
  9305. }
  9306. }
  9307. if (high_hash)
  9308. return TNR_HIGH;
  9309. }
  9310. return TNR_GOOD;
  9311. }
  9312. /* Returns true if nonce for work was a valid share */
  9313. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  9314. {
  9315. return submit_noffset_nonce(thr, work, nonce, 0);
  9316. }
  9317. /* Allows drivers to submit work items where the driver has changed the ntime
  9318. * value by noffset. Must be only used with a work protocol that does not ntime
  9319. * roll itself intrinsically to generate work (eg stratum). We do not touch
  9320. * the original work struct, but the copy of it only. */
  9321. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  9322. int noffset)
  9323. {
  9324. struct work *work = make_work();
  9325. _copy_work(work, work_in, noffset);
  9326. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  9327. struct timeval tv_work_found;
  9328. enum test_nonce2_result res;
  9329. bool ret = true;
  9330. thread_reportout(thr);
  9331. cgtime(&tv_work_found);
  9332. *work_nonce = htole32(nonce);
  9333. work->thr_id = thr->id;
  9334. /* Do one last check before attempting to submit the work */
  9335. /* Side effect: sets work->data and work->hash for us */
  9336. res = test_nonce2(work, nonce);
  9337. if (unlikely(res == TNR_BAD))
  9338. {
  9339. inc_hw_errors(thr, work, nonce);
  9340. ret = false;
  9341. goto out;
  9342. }
  9343. mutex_lock(&stats_lock);
  9344. total_diff1 += work->nonce_diff;
  9345. thr ->cgpu->diff1 += work->nonce_diff;
  9346. work->pool->diff1 += work->nonce_diff;
  9347. thr->cgpu->last_device_valid_work = time(NULL);
  9348. mutex_unlock(&stats_lock);
  9349. if (noncelog_file)
  9350. noncelog(work);
  9351. if (res == TNR_HIGH)
  9352. {
  9353. // Share above target, normal
  9354. /* Check the diff of the share, even if it didn't reach the
  9355. * target, just to set the best share value if it's higher. */
  9356. share_diff(work);
  9357. goto out;
  9358. }
  9359. submit_work_async2(work, &tv_work_found);
  9360. work = NULL; // Taken by submit_work_async2
  9361. out:
  9362. if (work)
  9363. free_work(work);
  9364. thread_reportin(thr);
  9365. return ret;
  9366. }
  9367. // return true of we should stop working on this piece of work
  9368. // returning false means we will keep scanning for a nonce
  9369. // assumptions: work->blk.nonce is the number of nonces completed in the work
  9370. // see minerloop_scanhash comments for more details & usage
  9371. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t max_hashes)
  9372. {
  9373. if (work->blk.nonce == 0xffffffff || // known we are scanning a full nonce range
  9374. wdiff->tv_sec > opt_scantime || // scan-time has elapsed (user specified, default 60s)
  9375. work->blk.nonce >= 0xfffffffe - max_hashes || // are there enough nonces left in the work
  9376. max_hashes >= 0xfffffffe || // assume we are scanning a full nonce range
  9377. stale_work(work, false)) // work is stale
  9378. return true;
  9379. return false;
  9380. }
  9381. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  9382. {
  9383. struct cgpu_info *proc = thr->cgpu;
  9384. if (proc->threads > 1)
  9385. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  9386. else
  9387. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  9388. }
  9389. // Called by asynchronous minerloops, when they find their processor should be disabled
  9390. void mt_disable_start(struct thr_info *mythr)
  9391. {
  9392. struct cgpu_info *cgpu = mythr->cgpu;
  9393. struct device_drv *drv = cgpu->drv;
  9394. if (drv->thread_disable)
  9395. drv->thread_disable(mythr);
  9396. hashmeter2(mythr);
  9397. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  9398. mythr->rolling = mythr->cgpu->rolling = 0;
  9399. thread_reportout(mythr);
  9400. mythr->_mt_disable_called = true;
  9401. }
  9402. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  9403. * the driver tells us it's full so that it may extract the work item using
  9404. * the get_queued() function which adds it to the hashtable on
  9405. * cgpu->queued_work. */
  9406. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  9407. {
  9408. thread_reportout(mythr);
  9409. do {
  9410. bool need_work;
  9411. /* Do this lockless just to know if we need more unqueued work. */
  9412. need_work = (!cgpu->unqueued_work);
  9413. /* get_work is a blocking function so do it outside of lock
  9414. * to prevent deadlocks with other locks. */
  9415. if (need_work) {
  9416. struct work *work = get_work(mythr);
  9417. wr_lock(&cgpu->qlock);
  9418. /* Check we haven't grabbed work somehow between
  9419. * checking and picking up the lock. */
  9420. if (likely(!cgpu->unqueued_work))
  9421. cgpu->unqueued_work = work;
  9422. else
  9423. need_work = false;
  9424. wr_unlock(&cgpu->qlock);
  9425. if (unlikely(!need_work))
  9426. discard_work(work);
  9427. }
  9428. /* The queue_full function should be used by the driver to
  9429. * actually place work items on the physical device if it
  9430. * does have a queue. */
  9431. } while (drv->queue_full && !drv->queue_full(cgpu));
  9432. }
  9433. /* Add a work item to a cgpu's queued hashlist */
  9434. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  9435. {
  9436. cgpu->queued_count++;
  9437. HASH_ADD_INT(cgpu->queued_work, id, work);
  9438. }
  9439. /* This function is for retrieving one work item from the unqueued pointer and
  9440. * adding it to the hashtable of queued work. Code using this function must be
  9441. * able to handle NULL as a return which implies there is no work available. */
  9442. struct work *get_queued(struct cgpu_info *cgpu)
  9443. {
  9444. struct work *work = NULL;
  9445. wr_lock(&cgpu->qlock);
  9446. if (cgpu->unqueued_work) {
  9447. work = cgpu->unqueued_work;
  9448. if (unlikely(stale_work(work, false))) {
  9449. discard_work(work);
  9450. work = NULL;
  9451. wake_gws();
  9452. } else
  9453. __add_queued(cgpu, work);
  9454. cgpu->unqueued_work = NULL;
  9455. }
  9456. wr_unlock(&cgpu->qlock);
  9457. return work;
  9458. }
  9459. void add_queued(struct cgpu_info *cgpu, struct work *work)
  9460. {
  9461. wr_lock(&cgpu->qlock);
  9462. __add_queued(cgpu, work);
  9463. wr_unlock(&cgpu->qlock);
  9464. }
  9465. /* Get fresh work and add it to cgpu's queued hashlist */
  9466. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  9467. {
  9468. struct work *work = get_work(thr);
  9469. add_queued(cgpu, work);
  9470. return work;
  9471. }
  9472. /* This function is for finding an already queued work item in the
  9473. * given que hashtable. Code using this function must be able
  9474. * to handle NULL as a return which implies there is no matching work.
  9475. * The calling function must lock access to the que if it is required.
  9476. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9477. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9478. {
  9479. struct work *work, *tmp, *ret = NULL;
  9480. HASH_ITER(hh, que, work, tmp) {
  9481. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  9482. memcmp(work->data + offset, data, datalen) == 0) {
  9483. ret = work;
  9484. break;
  9485. }
  9486. }
  9487. return ret;
  9488. }
  9489. /* This function is for finding an already queued work item in the
  9490. * device's queued_work hashtable. Code using this function must be able
  9491. * to handle NULL as a return which implies there is no matching work.
  9492. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9493. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9494. {
  9495. struct work *ret;
  9496. rd_lock(&cgpu->qlock);
  9497. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9498. rd_unlock(&cgpu->qlock);
  9499. return ret;
  9500. }
  9501. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9502. {
  9503. struct work *work, *ret = NULL;
  9504. rd_lock(&cgpu->qlock);
  9505. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9506. if (work)
  9507. ret = copy_work(work);
  9508. rd_unlock(&cgpu->qlock);
  9509. return ret;
  9510. }
  9511. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  9512. {
  9513. cgpu->queued_count--;
  9514. HASH_DEL(cgpu->queued_work, work);
  9515. }
  9516. /* This iterates over a queued hashlist finding work started more than secs
  9517. * seconds ago and discards the work as completed. The driver must set the
  9518. * work->tv_work_start value appropriately. Returns the number of items aged. */
  9519. int age_queued_work(struct cgpu_info *cgpu, double secs)
  9520. {
  9521. struct work *work, *tmp;
  9522. struct timeval tv_now;
  9523. int aged = 0;
  9524. cgtime(&tv_now);
  9525. wr_lock(&cgpu->qlock);
  9526. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  9527. if (tdiff(&tv_now, &work->tv_work_start) > secs) {
  9528. __work_completed(cgpu, work);
  9529. aged++;
  9530. }
  9531. }
  9532. wr_unlock(&cgpu->qlock);
  9533. return aged;
  9534. }
  9535. /* This function should be used by queued device drivers when they're sure
  9536. * the work struct is no longer in use. */
  9537. void work_completed(struct cgpu_info *cgpu, struct work *work)
  9538. {
  9539. wr_lock(&cgpu->qlock);
  9540. __work_completed(cgpu, work);
  9541. wr_unlock(&cgpu->qlock);
  9542. free_work(work);
  9543. }
  9544. /* Combines find_queued_work_bymidstate and work_completed in one function
  9545. * withOUT destroying the work so the driver must free it. */
  9546. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9547. {
  9548. struct work *work;
  9549. wr_lock(&cgpu->qlock);
  9550. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9551. if (work)
  9552. __work_completed(cgpu, work);
  9553. wr_unlock(&cgpu->qlock);
  9554. return work;
  9555. }
  9556. void flush_queue(struct cgpu_info *cgpu)
  9557. {
  9558. struct work *work = NULL;
  9559. wr_lock(&cgpu->qlock);
  9560. work = cgpu->unqueued_work;
  9561. cgpu->unqueued_work = NULL;
  9562. wr_unlock(&cgpu->qlock);
  9563. if (work) {
  9564. free_work(work);
  9565. applog(LOG_DEBUG, "Discarded queued work item");
  9566. }
  9567. }
  9568. /* This version of hash work is for devices that are fast enough to always
  9569. * perform a full nonce range and need a queue to maintain the device busy.
  9570. * Work creation and destruction is not done from within this function
  9571. * directly. */
  9572. void hash_queued_work(struct thr_info *mythr)
  9573. {
  9574. const long cycle = opt_log_interval / 5 ? : 1;
  9575. struct timeval tv_start = {0, 0}, tv_end;
  9576. struct cgpu_info *cgpu = mythr->cgpu;
  9577. struct device_drv *drv = cgpu->drv;
  9578. const int thr_id = mythr->id;
  9579. int64_t hashes_done = 0;
  9580. if (unlikely(cgpu->deven != DEV_ENABLED))
  9581. mt_disable(mythr);
  9582. while (likely(!cgpu->shutdown)) {
  9583. struct timeval diff;
  9584. int64_t hashes;
  9585. fill_queue(mythr, cgpu, drv, thr_id);
  9586. thread_reportin(mythr);
  9587. hashes = drv->scanwork(mythr);
  9588. /* Reset the bool here in case the driver looks for it
  9589. * synchronously in the scanwork loop. */
  9590. mythr->work_restart = false;
  9591. if (unlikely(hashes == -1 )) {
  9592. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  9593. cgpu->deven = DEV_DISABLED;
  9594. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  9595. mt_disable(mythr);
  9596. }
  9597. hashes_done += hashes;
  9598. cgtime(&tv_end);
  9599. timersub(&tv_end, &tv_start, &diff);
  9600. if (diff.tv_sec >= cycle) {
  9601. hashmeter(thr_id, &diff, hashes_done);
  9602. hashes_done = 0;
  9603. copy_time(&tv_start, &tv_end);
  9604. }
  9605. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  9606. mt_disable(mythr);
  9607. if (unlikely(mythr->work_restart)) {
  9608. flush_queue(cgpu);
  9609. if (drv->flush_work)
  9610. drv->flush_work(cgpu);
  9611. }
  9612. }
  9613. // cgpu->deven = DEV_DISABLED; set in miner_thread
  9614. }
  9615. // Called by minerloop, when it is re-enabling a processor
  9616. void mt_disable_finish(struct thr_info *mythr)
  9617. {
  9618. struct device_drv *drv = mythr->cgpu->drv;
  9619. thread_reportin(mythr);
  9620. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  9621. if (drv->thread_enable)
  9622. drv->thread_enable(mythr);
  9623. mythr->_mt_disable_called = false;
  9624. }
  9625. // Called by synchronous minerloops, when they find their processor should be disabled
  9626. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  9627. void mt_disable(struct thr_info *mythr)
  9628. {
  9629. const struct cgpu_info * const cgpu = mythr->cgpu;
  9630. mt_disable_start(mythr);
  9631. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  9632. do {
  9633. notifier_read(mythr->notifier);
  9634. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  9635. mt_disable_finish(mythr);
  9636. }
  9637. enum {
  9638. STAT_SLEEP_INTERVAL = 1,
  9639. STAT_CTR_INTERVAL = 10000000,
  9640. FAILURE_INTERVAL = 30,
  9641. };
  9642. /* Stage another work item from the work returned in a longpoll */
  9643. 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)
  9644. {
  9645. bool rc;
  9646. work->rolltime = rolltime;
  9647. rc = work_decode(pool, work, val);
  9648. if (unlikely(!rc)) {
  9649. applog(LOG_ERR, "Could not convert longpoll data to work");
  9650. free_work(work);
  9651. return;
  9652. }
  9653. total_getworks++;
  9654. pool->getwork_requested++;
  9655. work->pool = pool;
  9656. copy_time(&work->tv_getwork, tv_lp);
  9657. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  9658. calc_diff(work, 0);
  9659. if (pool->enabled == POOL_REJECTING)
  9660. work->mandatory = true;
  9661. work->longpoll = true;
  9662. work->getwork_mode = GETWORK_MODE_LP;
  9663. update_last_work(work);
  9664. /* We'll be checking this work item twice, but we already know it's
  9665. * from a new block so explicitly force the new block detection now
  9666. * rather than waiting for it to hit the stage thread. This also
  9667. * allows testwork to know whether LP discovered the block or not. */
  9668. test_work_current(work);
  9669. /* Don't use backup LPs as work if we have failover-only enabled. Use
  9670. * the longpoll work from a pool that has been rejecting shares as a
  9671. * way to detect when the pool has recovered.
  9672. */
  9673. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  9674. free_work(work);
  9675. return;
  9676. }
  9677. work = clone_work(work);
  9678. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  9679. stage_work(work);
  9680. applog(LOG_DEBUG, "Converted longpoll data to work");
  9681. }
  9682. /* If we want longpoll, enable it for the chosen default pool, or, if
  9683. * the pool does not support longpoll, find the first one that does
  9684. * and use its longpoll support */
  9685. static
  9686. struct pool *_select_longpoll_pool(struct pool *cp, bool(*func)(struct pool *))
  9687. {
  9688. int i;
  9689. if (func(cp))
  9690. return cp;
  9691. for (i = 0; i < total_pools; i++) {
  9692. struct pool *pool = pools[i];
  9693. if (cp->goal != pool->goal)
  9694. continue;
  9695. if (func(pool))
  9696. return pool;
  9697. }
  9698. return NULL;
  9699. }
  9700. /* This will make the longpoll thread wait till it's the current pool, or it
  9701. * has been flagged as rejecting, before attempting to open any connections.
  9702. */
  9703. static void wait_lpcurrent(struct pool *pool)
  9704. {
  9705. mutex_lock(&lp_lock);
  9706. while (!cnx_needed(pool))
  9707. {
  9708. pool->lp_active = false;
  9709. pthread_cond_wait(&lp_cond, &lp_lock);
  9710. }
  9711. mutex_unlock(&lp_lock);
  9712. }
  9713. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  9714. struct pool *pool = vpool;
  9715. curl_socket_t sock = bfg_socket(addr->family, addr->socktype, addr->protocol);
  9716. pool->lp_socket = sock;
  9717. return sock;
  9718. }
  9719. static void *longpoll_thread(void *userdata)
  9720. {
  9721. struct pool *cp = (struct pool *)userdata;
  9722. /* This *pool is the source of the actual longpoll, not the pool we've
  9723. * tied it to */
  9724. struct timeval start, reply, end;
  9725. struct pool *pool = NULL;
  9726. char threadname[20];
  9727. CURL *curl = NULL;
  9728. int failures = 0;
  9729. char *lp_url;
  9730. int rolltime;
  9731. #ifndef HAVE_PTHREAD_CANCEL
  9732. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9733. #endif
  9734. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  9735. RenameThread(threadname);
  9736. curl = curl_easy_init();
  9737. if (unlikely(!curl)) {
  9738. applog(LOG_ERR, "CURL initialisation failed");
  9739. return NULL;
  9740. }
  9741. retry_pool:
  9742. pool = select_longpoll_pool(cp);
  9743. if (!pool) {
  9744. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  9745. while (!pool) {
  9746. cgsleep_ms(60000);
  9747. pool = select_longpoll_pool(cp);
  9748. }
  9749. }
  9750. if (pool->has_stratum) {
  9751. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9752. cp->rpc_url, pool->rpc_url);
  9753. goto out;
  9754. }
  9755. /* Any longpoll from any pool is enough for this to be true */
  9756. pool->goal->have_longpoll = true;
  9757. wait_lpcurrent(cp);
  9758. {
  9759. lp_url = pool->lp_url;
  9760. if (cp == pool)
  9761. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  9762. else
  9763. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  9764. }
  9765. while (42) {
  9766. json_t *val, *soval;
  9767. struct work *work = make_work();
  9768. char *lpreq;
  9769. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id, pool);
  9770. work->pool = pool;
  9771. if (!lpreq)
  9772. {
  9773. free_work(work);
  9774. goto lpfail;
  9775. }
  9776. wait_lpcurrent(cp);
  9777. cgtime(&start);
  9778. /* Longpoll connections can be persistent for a very long time
  9779. * and any number of issues could have come up in the meantime
  9780. * so always establish a fresh connection instead of relying on
  9781. * a persistent one. */
  9782. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  9783. curl_easy_setopt(curl, CURLOPT_FORBID_REUSE, 1);
  9784. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  9785. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  9786. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  9787. lpreq, false, true, &rolltime, pool, false);
  9788. pool->lp_socket = CURL_SOCKET_BAD;
  9789. cgtime(&reply);
  9790. free(lpreq);
  9791. if (likely(val)) {
  9792. soval = json_object_get(json_object_get(val, "result"), "submitold");
  9793. if (soval)
  9794. pool->submit_old = json_is_true(soval);
  9795. else
  9796. pool->submit_old = false;
  9797. convert_to_work(val, rolltime, pool, work, &start, &reply);
  9798. failures = 0;
  9799. json_decref(val);
  9800. } else {
  9801. /* Some pools regularly drop the longpoll request so
  9802. * only see this as longpoll failure if it happens
  9803. * immediately and just restart it the rest of the
  9804. * time. */
  9805. cgtime(&end);
  9806. free_work(work);
  9807. if (end.tv_sec - start.tv_sec <= 30)
  9808. {
  9809. if (failures == 1)
  9810. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  9811. lpfail:
  9812. cgsleep_ms(30000);
  9813. }
  9814. }
  9815. if (pool != cp) {
  9816. pool = select_longpoll_pool(cp);
  9817. if (pool->has_stratum) {
  9818. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9819. cp->rpc_url, pool->rpc_url);
  9820. break;
  9821. }
  9822. if (unlikely(!pool))
  9823. goto retry_pool;
  9824. }
  9825. if (unlikely(pool->removed))
  9826. break;
  9827. }
  9828. out:
  9829. pool->lp_active = false;
  9830. curl_easy_cleanup(curl);
  9831. return NULL;
  9832. }
  9833. static void stop_longpoll(void)
  9834. {
  9835. int i;
  9836. want_longpoll = false;
  9837. for (i = 0; i < total_pools; ++i)
  9838. {
  9839. struct pool *pool = pools[i];
  9840. if (unlikely(!pool->lp_started))
  9841. continue;
  9842. pool->lp_started = false;
  9843. pthread_cancel(pool->longpoll_thread);
  9844. }
  9845. struct mining_goal_info *goal, *tmpgoal;
  9846. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  9847. {
  9848. goal->have_longpoll = false;
  9849. }
  9850. }
  9851. static void start_longpoll(void)
  9852. {
  9853. int i;
  9854. want_longpoll = true;
  9855. for (i = 0; i < total_pools; ++i)
  9856. {
  9857. struct pool *pool = pools[i];
  9858. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  9859. continue;
  9860. pool->lp_started = true;
  9861. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  9862. quit(1, "Failed to create pool longpoll thread");
  9863. }
  9864. }
  9865. void reinit_device(struct cgpu_info *cgpu)
  9866. {
  9867. if (cgpu->drv->reinit_device)
  9868. cgpu->drv->reinit_device(cgpu);
  9869. }
  9870. static struct timeval rotate_tv;
  9871. /* We reap curls if they are unused for over a minute */
  9872. static void reap_curl(struct pool *pool)
  9873. {
  9874. struct curl_ent *ent, *iter;
  9875. struct timeval now;
  9876. int reaped = 0;
  9877. cgtime(&now);
  9878. mutex_lock(&pool->pool_lock);
  9879. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  9880. if (pool->curls < 2)
  9881. break;
  9882. if (now.tv_sec - ent->tv.tv_sec > 300) {
  9883. reaped++;
  9884. pool->curls--;
  9885. LL_DELETE(pool->curllist, ent);
  9886. curl_easy_cleanup(ent->curl);
  9887. free(ent);
  9888. }
  9889. }
  9890. mutex_unlock(&pool->pool_lock);
  9891. if (reaped)
  9892. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  9893. }
  9894. static void *watchpool_thread(void __maybe_unused *userdata)
  9895. {
  9896. int intervals = 0;
  9897. #ifndef HAVE_PTHREAD_CANCEL
  9898. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9899. #endif
  9900. RenameThread("watchpool");
  9901. while (42) {
  9902. struct timeval now;
  9903. int i;
  9904. if (++intervals > 20)
  9905. intervals = 0;
  9906. cgtime(&now);
  9907. for (i = 0; i < total_pools; i++) {
  9908. struct pool *pool = pools[i];
  9909. if (!opt_benchmark)
  9910. reap_curl(pool);
  9911. /* Get a rolling utility per pool over 10 mins */
  9912. if (intervals > 19) {
  9913. int shares = pool->diff1 - pool->last_shares;
  9914. pool->last_shares = pool->diff1;
  9915. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  9916. pool->shares = pool->utility;
  9917. }
  9918. if (pool->enabled == POOL_DISABLED)
  9919. continue;
  9920. /* Don't start testing any pools if the test threads
  9921. * from startup are still doing their first attempt. */
  9922. if (unlikely(pool->testing)) {
  9923. pthread_join(pool->test_thread, NULL);
  9924. }
  9925. /* Test pool is idle once every minute */
  9926. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  9927. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  9928. pool_resus(pool);
  9929. }
  9930. /* Only switch pools if the failback pool has been
  9931. * alive for more than 5 minutes (default) to prevent
  9932. * intermittently failing pools from being used. */
  9933. if (!pool->idle && pool->enabled == POOL_ENABLED && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio() && now.tv_sec - pool->tv_idle.tv_sec > opt_fail_switch_delay)
  9934. {
  9935. if (opt_fail_switch_delay % 60)
  9936. applog(LOG_WARNING, "Pool %d %s stable for %d second%s",
  9937. pool->pool_no, pool->rpc_url,
  9938. opt_fail_switch_delay,
  9939. (opt_fail_switch_delay == 1 ? "" : "s"));
  9940. else
  9941. applog(LOG_WARNING, "Pool %d %s stable for %d minute%s",
  9942. pool->pool_no, pool->rpc_url,
  9943. opt_fail_switch_delay / 60,
  9944. (opt_fail_switch_delay == 60 ? "" : "s"));
  9945. switch_pools(NULL);
  9946. }
  9947. }
  9948. if (current_pool()->idle)
  9949. switch_pools(NULL);
  9950. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  9951. cgtime(&rotate_tv);
  9952. switch_pools(NULL);
  9953. }
  9954. cgsleep_ms(30000);
  9955. }
  9956. return NULL;
  9957. }
  9958. void mt_enable(struct thr_info *thr)
  9959. {
  9960. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  9961. notifier_wake(thr->notifier);
  9962. }
  9963. void proc_enable(struct cgpu_info *cgpu)
  9964. {
  9965. int j;
  9966. cgpu->deven = DEV_ENABLED;
  9967. for (j = cgpu->threads ?: 1; j--; )
  9968. mt_enable(cgpu->thr[j]);
  9969. }
  9970. #define device_recovered(cgpu) proc_enable(cgpu)
  9971. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  9972. {
  9973. struct string_elist *setstr_elist;
  9974. const char *p, *p2;
  9975. char replybuf[0x2000];
  9976. size_t L;
  9977. DL_FOREACH(opt_set_device_list, setstr_elist)
  9978. {
  9979. const char * const setstr = setstr_elist->string;
  9980. p = strchr(setstr, ':');
  9981. if (!p)
  9982. p = setstr;
  9983. {
  9984. L = p - setstr;
  9985. char pattern[L + 1];
  9986. if (L)
  9987. memcpy(pattern, setstr, L);
  9988. pattern[L] = '\0';
  9989. if (!cgpu_match(pattern, cgpu))
  9990. continue;
  9991. }
  9992. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  9993. cgpu->proc_repr, __func__, setstr);
  9994. if (p[0] == ':')
  9995. ++p;
  9996. p2 = strchr(p, '=');
  9997. if (!p2)
  9998. {
  9999. L = strlen(p);
  10000. p2 = "";
  10001. }
  10002. else
  10003. {
  10004. L = p2 - p;
  10005. ++p2;
  10006. }
  10007. char opt[L + 1];
  10008. if (L)
  10009. memcpy(opt, p, L);
  10010. opt[L] = '\0';
  10011. L = strlen(p2);
  10012. char setval[L + 1];
  10013. if (L)
  10014. memcpy(setval, p2, L);
  10015. setval[L] = '\0';
  10016. enum bfg_set_device_replytype success;
  10017. p = proc_set_device(cgpu, opt, setval, replybuf, &success);
  10018. switch (success)
  10019. {
  10020. case SDR_OK:
  10021. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s%s%s",
  10022. cgpu->proc_repr, setstr,
  10023. p ? ": " : "", p ?: "");
  10024. break;
  10025. case SDR_ERR:
  10026. case SDR_HELP:
  10027. case SDR_UNKNOWN:
  10028. applog(LOG_DEBUG, "%"PRIpreprv": Applying rule %s: %s",
  10029. cgpu->proc_repr, setstr, p);
  10030. break;
  10031. case SDR_AUTO:
  10032. case SDR_NOSUPP:
  10033. applog(LOG_DEBUG, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  10034. cgpu->proc_repr, setstr);
  10035. }
  10036. }
  10037. cgpu->already_set_defaults = true;
  10038. }
  10039. void drv_set_defaults(const struct device_drv * const drv, const void *datap, void *userp, const char * const devpath, const char * const serial, const int mode)
  10040. {
  10041. struct device_drv dummy_drv = *drv;
  10042. struct cgpu_info dummy_cgpu = {
  10043. .drv = &dummy_drv,
  10044. .device = &dummy_cgpu,
  10045. .device_id = -1,
  10046. .proc_id = -1,
  10047. .device_data = userp,
  10048. .device_path = devpath,
  10049. .dev_serial = serial,
  10050. };
  10051. strcpy(dummy_cgpu.proc_repr, drv->name);
  10052. switch (mode)
  10053. {
  10054. case 0:
  10055. dummy_drv.set_device = datap;
  10056. break;
  10057. case 1:
  10058. dummy_drv.set_device = NULL;
  10059. dummy_cgpu.set_device_funcs = datap;
  10060. break;
  10061. }
  10062. cgpu_set_defaults(&dummy_cgpu);
  10063. }
  10064. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  10065. * the screen at regular intervals, and restarts threads if they appear to have
  10066. * died. */
  10067. #define WATCHDOG_SICK_TIME 60
  10068. #define WATCHDOG_DEAD_TIME 600
  10069. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  10070. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  10071. static void *watchdog_thread(void __maybe_unused *userdata)
  10072. {
  10073. const unsigned int interval = WATCHDOG_INTERVAL;
  10074. struct timeval zero_tv;
  10075. #ifndef HAVE_PTHREAD_CANCEL
  10076. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  10077. #endif
  10078. RenameThread("watchdog");
  10079. memset(&zero_tv, 0, sizeof(struct timeval));
  10080. cgtime(&rotate_tv);
  10081. while (1) {
  10082. int i;
  10083. struct timeval now;
  10084. sleep(interval);
  10085. discard_stale();
  10086. hashmeter(-1, &zero_tv, 0);
  10087. #ifdef HAVE_CURSES
  10088. const int ts = total_staged(true);
  10089. if (curses_active_locked()) {
  10090. change_logwinsize();
  10091. curses_print_status(ts);
  10092. _refresh_devstatus(true);
  10093. touchwin(logwin);
  10094. wrefresh(logwin);
  10095. unlock_curses();
  10096. }
  10097. #endif
  10098. cgtime(&now);
  10099. if (!sched_paused && !should_run()) {
  10100. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  10101. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  10102. if (!schedstart.enable) {
  10103. quit(0, "Terminating execution as planned");
  10104. break;
  10105. }
  10106. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  10107. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  10108. sched_paused = true;
  10109. rd_lock(&mining_thr_lock);
  10110. for (i = 0; i < mining_threads; i++)
  10111. mining_thr[i]->pause = true;
  10112. rd_unlock(&mining_thr_lock);
  10113. } else if (sched_paused && should_run()) {
  10114. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  10115. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  10116. if (schedstop.enable)
  10117. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  10118. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  10119. sched_paused = false;
  10120. for (i = 0; i < mining_threads; i++) {
  10121. struct thr_info *thr;
  10122. thr = get_thread(i);
  10123. thr->pause = false;
  10124. }
  10125. for (i = 0; i < total_devices; ++i)
  10126. {
  10127. struct cgpu_info *cgpu = get_devices(i);
  10128. /* Don't touch disabled devices */
  10129. if (cgpu->deven == DEV_DISABLED)
  10130. continue;
  10131. proc_enable(cgpu);
  10132. }
  10133. }
  10134. for (i = 0; i < total_devices; ++i) {
  10135. struct cgpu_info *cgpu = get_devices(i);
  10136. if (!cgpu->disable_watchdog)
  10137. bfg_watchdog(cgpu, &now);
  10138. }
  10139. }
  10140. return NULL;
  10141. }
  10142. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  10143. {
  10144. struct thr_info *thr = cgpu->thr[0];
  10145. enum dev_enable *denable;
  10146. char *dev_str = cgpu->proc_repr;
  10147. if (likely(drv_ready(cgpu)))
  10148. {
  10149. if (unlikely(!cgpu->already_set_defaults))
  10150. cgpu_set_defaults(cgpu);
  10151. if (cgpu->drv->get_stats)
  10152. cgpu->drv->get_stats(cgpu);
  10153. }
  10154. denable = &cgpu->deven;
  10155. if (cgpu->drv->watchdog)
  10156. cgpu->drv->watchdog(cgpu, tvp_now);
  10157. /* Thread is disabled */
  10158. if (*denable == DEV_DISABLED)
  10159. return;
  10160. else
  10161. if (*denable == DEV_RECOVER_ERR) {
  10162. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  10163. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  10164. dev_str);
  10165. if (cgpu->reinit_backoff < 300)
  10166. cgpu->reinit_backoff *= 2;
  10167. device_recovered(cgpu);
  10168. }
  10169. return;
  10170. }
  10171. else
  10172. if (*denable == DEV_RECOVER) {
  10173. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  10174. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  10175. dev_str);
  10176. device_recovered(cgpu);
  10177. }
  10178. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  10179. return;
  10180. }
  10181. else
  10182. if (cgpu->temp > cgpu->cutofftemp)
  10183. {
  10184. applog(LOG_WARNING, "%s hit thermal cutoff limit at %dC, disabling!",
  10185. dev_str, (int)cgpu->temp);
  10186. *denable = DEV_RECOVER;
  10187. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  10188. run_cmd(cmd_idle);
  10189. }
  10190. if (thr->getwork) {
  10191. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  10192. int thrid;
  10193. bool cgpu_idle = true;
  10194. thr->rolling = 0;
  10195. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  10196. if (!cgpu->thr[thrid]->getwork)
  10197. cgpu_idle = false;
  10198. if (cgpu_idle) {
  10199. cgpu->rolling = 0;
  10200. cgpu->status = LIFE_WAIT;
  10201. }
  10202. }
  10203. return;
  10204. }
  10205. else if (cgpu->status == LIFE_WAIT)
  10206. cgpu->status = LIFE_WELL;
  10207. #ifdef USE_CPUMINING
  10208. if (!strcmp(cgpu->drv->dname, "cpu"))
  10209. return;
  10210. #endif
  10211. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  10212. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  10213. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  10214. cgpu->status = LIFE_WELL;
  10215. cgpu->device_last_well = time(NULL);
  10216. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  10217. thr->rolling = cgpu->rolling = 0;
  10218. cgpu->status = LIFE_SICK;
  10219. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  10220. cgtime(&thr->sick);
  10221. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  10222. run_cmd(cmd_sick);
  10223. if (opt_restart && cgpu->drv->reinit_device) {
  10224. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  10225. reinit_device(cgpu);
  10226. }
  10227. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  10228. cgpu->status = LIFE_DEAD;
  10229. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  10230. cgtime(&thr->sick);
  10231. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  10232. run_cmd(cmd_dead);
  10233. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  10234. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  10235. /* Attempt to restart a GPU that's sick or dead once every minute */
  10236. cgtime(&thr->sick);
  10237. if (opt_restart)
  10238. reinit_device(cgpu);
  10239. }
  10240. }
  10241. static void log_print_status(struct cgpu_info *cgpu)
  10242. {
  10243. char logline[255];
  10244. get_statline(logline, sizeof(logline), cgpu);
  10245. applog(LOG_WARNING, "%s", logline);
  10246. }
  10247. void print_summary(void)
  10248. {
  10249. struct timeval diff;
  10250. int hours, mins, secs, i;
  10251. double utility, efficiency = 0.0;
  10252. char xfer[(ALLOC_H2B_SPACED*2)+4+1], bw[(ALLOC_H2B_SPACED*2)+6+1];
  10253. int pool_secs;
  10254. timersub(&total_tv_end, &total_tv_start, &diff);
  10255. hours = diff.tv_sec / 3600;
  10256. mins = (diff.tv_sec % 3600) / 60;
  10257. secs = diff.tv_sec % 60;
  10258. utility = total_accepted / total_secs * 60;
  10259. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  10260. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  10261. applog(LOG_WARNING, "Started at %s", datestamp);
  10262. if (total_pools == 1)
  10263. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  10264. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  10265. if (opt_n_threads > 0)
  10266. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  10267. #endif
  10268. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  10269. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  10270. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  10271. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  10272. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  10273. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  10274. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  10275. total_rejected, total_stale,
  10276. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  10277. );
  10278. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  10279. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  10280. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  10281. applog(LOG_WARNING, "Network transfer: %s (%s)",
  10282. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  10283. (float)total_bytes_rcvd,
  10284. (float)total_bytes_sent),
  10285. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  10286. (float)(total_bytes_rcvd / total_secs),
  10287. (float)(total_bytes_sent / total_secs)));
  10288. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  10289. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  10290. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  10291. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  10292. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  10293. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  10294. if (total_pools > 1) {
  10295. for (i = 0; i < total_pools; i++) {
  10296. struct pool *pool = pools[i];
  10297. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  10298. if (pool->solved)
  10299. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  10300. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  10301. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  10302. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  10303. pool->rejected, pool->stale_shares,
  10304. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  10305. );
  10306. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  10307. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  10308. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  10309. applog(LOG_WARNING, " Network transfer: %s (%s)",
  10310. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  10311. (float)pool->cgminer_pool_stats.net_bytes_received,
  10312. (float)pool->cgminer_pool_stats.net_bytes_sent),
  10313. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  10314. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  10315. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  10316. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  10317. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  10318. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  10319. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  10320. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  10321. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  10322. }
  10323. }
  10324. if (opt_quit_summary != BQS_NONE)
  10325. {
  10326. if (opt_quit_summary == BQS_DEFAULT)
  10327. {
  10328. if (total_devices < 25)
  10329. opt_quit_summary = BQS_PROCS;
  10330. else
  10331. opt_quit_summary = BQS_DEVS;
  10332. }
  10333. if (opt_quit_summary == BQS_DETAILED)
  10334. include_serial_in_statline = true;
  10335. applog(LOG_WARNING, "Summary of per device statistics:\n");
  10336. for (i = 0; i < total_devices; ++i) {
  10337. struct cgpu_info *cgpu = get_devices(i);
  10338. if (!cgpu->proc_id)
  10339. {
  10340. // Device summary line
  10341. opt_show_procs = false;
  10342. log_print_status(cgpu);
  10343. opt_show_procs = true;
  10344. }
  10345. if ((opt_quit_summary == BQS_PROCS || opt_quit_summary == BQS_DETAILED) && cgpu->procs > 1)
  10346. log_print_status(cgpu);
  10347. }
  10348. }
  10349. if (opt_shares) {
  10350. applog(LOG_WARNING, "Mined %g accepted shares of %g requested\n", total_diff_accepted, opt_shares);
  10351. if (opt_shares > total_diff_accepted)
  10352. applog(LOG_WARNING, "WARNING - Mined only %g shares of %g requested.", total_diff_accepted, opt_shares);
  10353. }
  10354. applog(LOG_WARNING, " ");
  10355. fflush(stderr);
  10356. fflush(stdout);
  10357. }
  10358. void _bfg_clean_up(bool restarting)
  10359. {
  10360. #ifdef USE_OPENCL
  10361. clear_adl(nDevs);
  10362. #endif
  10363. #ifdef HAVE_LIBUSB
  10364. if (likely(have_libusb))
  10365. libusb_exit(NULL);
  10366. #endif
  10367. cgtime(&total_tv_end);
  10368. #ifdef WIN32
  10369. timeEndPeriod(1);
  10370. #endif
  10371. if (!restarting) {
  10372. /* Attempting to disable curses or print a summary during a
  10373. * restart can lead to a deadlock. */
  10374. #ifdef HAVE_CURSES
  10375. disable_curses();
  10376. #endif
  10377. if (!opt_realquiet && successful_connect)
  10378. print_summary();
  10379. }
  10380. if (opt_n_threads > 0)
  10381. free(cpus);
  10382. curl_global_cleanup();
  10383. #ifdef WIN32
  10384. WSACleanup();
  10385. #endif
  10386. }
  10387. void _quit(int status)
  10388. {
  10389. if (status) {
  10390. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  10391. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  10392. int *p = NULL;
  10393. // NOTE debugger can bypass with: p = &p
  10394. *p = status; // Segfault, hopefully dumping core
  10395. }
  10396. }
  10397. #if defined(unix) || defined(__APPLE__)
  10398. if (forkpid > 0) {
  10399. kill(forkpid, SIGTERM);
  10400. forkpid = 0;
  10401. }
  10402. #endif
  10403. exit(status);
  10404. }
  10405. #ifdef HAVE_CURSES
  10406. char *curses_input(const char *query)
  10407. {
  10408. char *input;
  10409. echo();
  10410. input = malloc(255);
  10411. if (!input)
  10412. quit(1, "Failed to malloc input");
  10413. leaveok(logwin, false);
  10414. wlogprint("%s:\n", query);
  10415. wgetnstr(logwin, input, 255);
  10416. if (!strlen(input))
  10417. {
  10418. free(input);
  10419. input = NULL;
  10420. }
  10421. leaveok(logwin, true);
  10422. noecho();
  10423. return input;
  10424. }
  10425. #endif
  10426. static void *test_pool_thread(void *arg)
  10427. {
  10428. struct pool *pool = (struct pool *)arg;
  10429. if (pool_active(pool, false)) {
  10430. pool_tset(pool, &pool->lagging);
  10431. pool_tclear(pool, &pool->idle);
  10432. bool first_pool = false;
  10433. cg_wlock(&control_lock);
  10434. if (!pools_active) {
  10435. currentpool = pool;
  10436. if (pool->pool_no != 0)
  10437. first_pool = true;
  10438. pools_active = true;
  10439. }
  10440. cg_wunlock(&control_lock);
  10441. if (unlikely(first_pool))
  10442. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  10443. else
  10444. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  10445. switch_pools(NULL);
  10446. } else
  10447. pool_died(pool);
  10448. pool->testing = false;
  10449. return NULL;
  10450. }
  10451. /* Always returns true that the pool details were added unless we are not
  10452. * live, implying this is the only pool being added, so if no pools are
  10453. * active it returns false. */
  10454. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  10455. {
  10456. size_t siz;
  10457. pool_set_uri(pool, url);
  10458. pool->rpc_user = user;
  10459. pool->rpc_pass = pass;
  10460. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  10461. pool->rpc_userpass = malloc(siz);
  10462. if (!pool->rpc_userpass)
  10463. quit(1, "Failed to malloc userpass");
  10464. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  10465. pool->testing = true;
  10466. pool->idle = true;
  10467. enable_pool(pool);
  10468. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  10469. if (!live) {
  10470. pthread_join(pool->test_thread, NULL);
  10471. return pools_active;
  10472. }
  10473. return true;
  10474. }
  10475. #ifdef HAVE_CURSES
  10476. static bool input_pool(bool live)
  10477. {
  10478. char *url = NULL, *user = NULL, *pass = NULL;
  10479. struct pool *pool;
  10480. bool ret = false;
  10481. immedok(logwin, true);
  10482. wlogprint("Input server details.\n");
  10483. url = curses_input("URL");
  10484. if (!url)
  10485. goto out;
  10486. user = curses_input("Username");
  10487. if (!user)
  10488. goto out;
  10489. pass = curses_input("Password");
  10490. if (!pass)
  10491. pass = calloc(1, 1);
  10492. pool = add_pool();
  10493. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  10494. strncmp(url, "https://", 8)) {
  10495. char *httpinput;
  10496. httpinput = malloc(256);
  10497. if (!httpinput)
  10498. quit(1, "Failed to malloc httpinput");
  10499. strcpy(httpinput, "http://");
  10500. strncat(httpinput, url, 248);
  10501. free(url);
  10502. url = httpinput;
  10503. }
  10504. ret = add_pool_details(pool, live, url, user, pass);
  10505. out:
  10506. immedok(logwin, false);
  10507. if (!ret) {
  10508. if (url)
  10509. free(url);
  10510. if (user)
  10511. free(user);
  10512. if (pass)
  10513. free(pass);
  10514. }
  10515. return ret;
  10516. }
  10517. #endif
  10518. #if BLKMAKER_VERSION > 1 && defined(USE_SHA256D)
  10519. static
  10520. bool _add_local_gbt(const char * const filepath, void *userp)
  10521. {
  10522. const bool * const live_p = userp;
  10523. struct pool *pool;
  10524. char buf[0x100];
  10525. char *rpcuser = NULL, *rpcpass = NULL, *rpcconnect = NULL;
  10526. int rpcport = 0, rpcssl = -101;
  10527. FILE * const F = fopen(filepath, "r");
  10528. if (!F)
  10529. applogr(false, LOG_WARNING, "%s: Failed to open %s for reading", "add_local_gbt", filepath);
  10530. while (fgets(buf, sizeof(buf), F))
  10531. {
  10532. if (!strncasecmp(buf, "rpcuser=", 8))
  10533. rpcuser = trimmed_strdup(&buf[8]);
  10534. else
  10535. if (!strncasecmp(buf, "rpcpassword=", 12))
  10536. rpcpass = trimmed_strdup(&buf[12]);
  10537. else
  10538. if (!strncasecmp(buf, "rpcport=", 8))
  10539. rpcport = atoi(&buf[8]);
  10540. else
  10541. if (!strncasecmp(buf, "rpcssl=", 7))
  10542. rpcssl = atoi(&buf[7]);
  10543. else
  10544. if (!strncasecmp(buf, "rpcconnect=", 11))
  10545. rpcconnect = trimmed_strdup(&buf[11]);
  10546. else
  10547. continue;
  10548. if (rpcuser && rpcpass && rpcport && rpcssl != -101 && rpcconnect)
  10549. break;
  10550. }
  10551. fclose(F);
  10552. if (!rpcpass)
  10553. {
  10554. applog(LOG_DEBUG, "%s: Did not find rpcpassword in %s", "add_local_gbt", filepath);
  10555. err:
  10556. free(rpcuser);
  10557. free(rpcpass);
  10558. goto out;
  10559. }
  10560. if (!rpcport)
  10561. rpcport = 8332;
  10562. if (rpcssl == -101)
  10563. rpcssl = 0;
  10564. const bool have_cbaddr = get_mining_goal("default")->generation_script;
  10565. const int uri_sz = 0x30;
  10566. char * const uri = malloc(uri_sz);
  10567. snprintf(uri, uri_sz, "http%s://%s:%d/%s#allblocks", rpcssl ? "s" : "", rpcconnect ?: "localhost", rpcport, have_cbaddr ? "" : "#getcbaddr");
  10568. char hfuri[0x40];
  10569. if (rpcconnect)
  10570. snprintf(hfuri, sizeof(hfuri), "%s:%d", rpcconnect, rpcport);
  10571. else
  10572. snprintf(hfuri, sizeof(hfuri), "port %d", rpcport);
  10573. applog(LOG_DEBUG, "Local bitcoin RPC server on %s found in %s", hfuri, filepath);
  10574. for (int i = 0; i < total_pools; ++i)
  10575. {
  10576. struct pool *pool = pools[i];
  10577. if (!(strcmp(pool->rpc_url, uri) || strcmp(pool->rpc_pass, rpcpass)))
  10578. {
  10579. applog(LOG_DEBUG, "Server on %s is already configured, not adding as failover", hfuri);
  10580. free(uri);
  10581. goto err;
  10582. }
  10583. }
  10584. pool = add_pool();
  10585. if (!pool)
  10586. {
  10587. applog(LOG_ERR, "%s: Error adding pool for bitcoin configured in %s", "add_local_gbt", filepath);
  10588. goto err;
  10589. }
  10590. if (!rpcuser)
  10591. rpcuser = "";
  10592. pool->quota = 0;
  10593. adjust_quota_gcd();
  10594. pool->failover_only = true;
  10595. add_pool_details(pool, *live_p, uri, rpcuser, rpcpass);
  10596. applog(LOG_NOTICE, "Added local bitcoin RPC server on %s as pool %d", hfuri, pool->pool_no);
  10597. out:
  10598. return false;
  10599. }
  10600. static
  10601. void add_local_gbt(bool live)
  10602. {
  10603. appdata_file_call("Bitcoin", "bitcoin.conf", _add_local_gbt, &live);
  10604. }
  10605. #endif
  10606. #if defined(unix) || defined(__APPLE__)
  10607. static void fork_monitor()
  10608. {
  10609. // Make a pipe: [readFD, writeFD]
  10610. int pfd[2];
  10611. int r = pipe(pfd);
  10612. if (r < 0) {
  10613. perror("pipe - failed to create pipe for --monitor");
  10614. exit(1);
  10615. }
  10616. // Make stderr write end of pipe
  10617. fflush(stderr);
  10618. r = dup2(pfd[1], 2);
  10619. if (r < 0) {
  10620. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  10621. exit(1);
  10622. }
  10623. r = close(pfd[1]);
  10624. if (r < 0) {
  10625. perror("close - failed to close write end of pipe for --monitor");
  10626. exit(1);
  10627. }
  10628. // Don't allow a dying monitor to kill the main process
  10629. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  10630. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  10631. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  10632. perror("signal - failed to edit signal mask for --monitor");
  10633. exit(1);
  10634. }
  10635. // Fork a child process
  10636. forkpid = fork();
  10637. if (forkpid < 0) {
  10638. perror("fork - failed to fork child process for --monitor");
  10639. exit(1);
  10640. }
  10641. // Child: launch monitor command
  10642. if (0 == forkpid) {
  10643. // Make stdin read end of pipe
  10644. r = dup2(pfd[0], 0);
  10645. if (r < 0) {
  10646. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  10647. exit(1);
  10648. }
  10649. close(pfd[0]);
  10650. if (r < 0) {
  10651. perror("close - in child, failed to close read end of pipe for --monitor");
  10652. exit(1);
  10653. }
  10654. // Launch user specified command
  10655. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  10656. perror("execl - in child failed to exec user specified command for --monitor");
  10657. exit(1);
  10658. }
  10659. // Parent: clean up unused fds and bail
  10660. r = close(pfd[0]);
  10661. if (r < 0) {
  10662. perror("close - failed to close read end of pipe for --monitor");
  10663. exit(1);
  10664. }
  10665. }
  10666. #endif // defined(unix)
  10667. #ifdef HAVE_CURSES
  10668. #ifdef USE_UNICODE
  10669. static
  10670. wchar_t select_unicode_char(const wchar_t *opt)
  10671. {
  10672. for ( ; *opt; ++opt)
  10673. if (iswprint(*opt))
  10674. return *opt;
  10675. return '?';
  10676. }
  10677. #endif
  10678. void enable_curses(void) {
  10679. int x;
  10680. __maybe_unused int y;
  10681. lock_curses();
  10682. if (curses_active) {
  10683. unlock_curses();
  10684. return;
  10685. }
  10686. #ifdef USE_UNICODE
  10687. if (use_unicode)
  10688. {
  10689. setlocale(LC_CTYPE, "");
  10690. if (iswprint(0xb0))
  10691. have_unicode_degrees = true;
  10692. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  10693. }
  10694. #endif
  10695. mainwin = initscr();
  10696. start_color();
  10697. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  10698. if (ERR != use_default_colors())
  10699. default_bgcolor = -1;
  10700. #endif
  10701. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  10702. {
  10703. menu_attr = COLOR_PAIR(1);
  10704. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  10705. attr_bad |= COLOR_PAIR(2);
  10706. }
  10707. keypad(mainwin, true);
  10708. getmaxyx(mainwin, y, x);
  10709. statuswin = newwin(logstart, x, 0, 0);
  10710. leaveok(statuswin, true);
  10711. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  10712. // We resize the window later anyway, so just start it off at 1 :)
  10713. logwin = newwin(1, 0, logcursor, 0);
  10714. idlok(logwin, true);
  10715. scrollok(logwin, true);
  10716. leaveok(logwin, true);
  10717. cbreak();
  10718. noecho();
  10719. nonl();
  10720. curses_active = true;
  10721. statusy = logstart;
  10722. unlock_curses();
  10723. }
  10724. #endif
  10725. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  10726. #ifndef USE_CPUMINING
  10727. struct device_drv cpu_drv;
  10728. struct device_drv cpu_drv = {
  10729. .name = "CPU",
  10730. };
  10731. #endif
  10732. static int cgminer_id_count = 0;
  10733. static int device_line_id_count;
  10734. void register_device(struct cgpu_info *cgpu)
  10735. {
  10736. cgpu->deven = DEV_ENABLED;
  10737. wr_lock(&devices_lock);
  10738. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  10739. wr_unlock(&devices_lock);
  10740. if (!cgpu->proc_id)
  10741. cgpu->device_line_id = device_line_id_count++;
  10742. int thr_objs = cgpu->threads ?: 1;
  10743. mining_threads += thr_objs;
  10744. base_queue += thr_objs + cgpu->extra_work_queue;
  10745. {
  10746. const struct device_drv * const drv = cgpu->drv;
  10747. struct mining_algorithm *malgo;
  10748. LL_FOREACH(mining_algorithms, malgo)
  10749. {
  10750. if (drv_min_nonce_diff(drv, cgpu, malgo) < 0)
  10751. continue;
  10752. malgo->base_queue += thr_objs + cgpu->extra_work_queue;
  10753. }
  10754. }
  10755. #ifdef HAVE_CURSES
  10756. adj_width(mining_threads, &dev_width);
  10757. #endif
  10758. rwlock_init(&cgpu->qlock);
  10759. cgpu->queued_work = NULL;
  10760. }
  10761. struct _cgpu_devid_counter {
  10762. char name[4];
  10763. int lastid;
  10764. UT_hash_handle hh;
  10765. };
  10766. void renumber_cgpu(struct cgpu_info *cgpu)
  10767. {
  10768. static struct _cgpu_devid_counter *devids = NULL;
  10769. struct _cgpu_devid_counter *d;
  10770. HASH_FIND_STR(devids, cgpu->drv->name, d);
  10771. if (d)
  10772. cgpu->device_id = ++d->lastid;
  10773. else {
  10774. d = malloc(sizeof(*d));
  10775. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  10776. cgpu->device_id = d->lastid = 0;
  10777. HASH_ADD_STR(devids, name, d);
  10778. }
  10779. // Build repr strings
  10780. sprintf(cgpu->dev_repr, "%s%2u", cgpu->drv->name, cgpu->device_id % 100);
  10781. sprintf(cgpu->dev_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id % 100);
  10782. strcpy(cgpu->proc_repr, cgpu->dev_repr);
  10783. sprintf(cgpu->proc_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id);
  10784. const int lpcount = cgpu->procs;
  10785. if (lpcount > 1)
  10786. {
  10787. int ns;
  10788. struct cgpu_info *slave;
  10789. int lpdigits = 1;
  10790. for (int i = lpcount; i > 26 && lpdigits < 3; i /= 26)
  10791. ++lpdigits;
  10792. if (lpdigits > max_lpdigits)
  10793. max_lpdigits = lpdigits;
  10794. memset(&cgpu->proc_repr[5], 'a', lpdigits);
  10795. cgpu->proc_repr[5 + lpdigits] = '\0';
  10796. ns = strlen(cgpu->proc_repr_ns);
  10797. strcpy(&cgpu->proc_repr_ns[ns], &cgpu->proc_repr[5]);
  10798. slave = cgpu;
  10799. for (int i = 1; i < lpcount; ++i)
  10800. {
  10801. slave = slave->next_proc;
  10802. strcpy(slave->proc_repr, cgpu->proc_repr);
  10803. strcpy(slave->proc_repr_ns, cgpu->proc_repr_ns);
  10804. for (int x = i, y = lpdigits; --y, x; x /= 26)
  10805. {
  10806. slave->proc_repr_ns[ns + y] =
  10807. slave->proc_repr[5 + y] += (x % 26);
  10808. }
  10809. }
  10810. }
  10811. }
  10812. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  10813. {
  10814. sha256(buffer, length, digest);
  10815. return true;
  10816. }
  10817. static
  10818. bool drv_algo_check(const struct device_drv * const drv)
  10819. {
  10820. struct mining_goal_info *goal, *tmpgoal;
  10821. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  10822. {
  10823. if (drv_min_nonce_diff(drv, NULL, goal->malgo) >= 0)
  10824. return true;
  10825. }
  10826. return false;
  10827. }
  10828. #ifndef HAVE_PTHREAD_CANCEL
  10829. extern void setup_pthread_cancel_workaround();
  10830. extern struct sigaction pcwm_orig_term_handler;
  10831. #endif
  10832. bool bfg_need_detect_rescan;
  10833. extern void probe_device(struct lowlevel_device_info *);
  10834. static void schedule_rescan(const struct timeval *);
  10835. static
  10836. void drv_detect_all()
  10837. {
  10838. bool rescanning = false;
  10839. rescan:
  10840. bfg_need_detect_rescan = false;
  10841. #ifdef HAVE_BFG_LOWLEVEL
  10842. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  10843. LL_FOREACH_SAFE(infolist, info, infotmp)
  10844. probe_device(info);
  10845. LL_FOREACH_SAFE(infolist, info, infotmp)
  10846. pthread_join(info->probe_pth, NULL);
  10847. #endif
  10848. struct driver_registration *reg;
  10849. BFG_FOREACH_DRIVER_BY_PRIORITY(reg)
  10850. {
  10851. const struct device_drv * const drv = reg->drv;
  10852. if (!(drv_algo_check(drv) && drv->drv_detect))
  10853. continue;
  10854. drv->drv_detect();
  10855. }
  10856. #ifdef HAVE_BFG_LOWLEVEL
  10857. lowlevel_scan_free();
  10858. #endif
  10859. if (bfg_need_detect_rescan)
  10860. {
  10861. if (rescanning)
  10862. {
  10863. applog(LOG_DEBUG, "Device rescan requested a second time, delaying");
  10864. struct timeval tv_when;
  10865. timer_set_delay_from_now(&tv_when, rescan_delay_ms * 1000);
  10866. schedule_rescan(&tv_when);
  10867. }
  10868. else
  10869. {
  10870. rescanning = true;
  10871. applog(LOG_DEBUG, "Device rescan requested");
  10872. goto rescan;
  10873. }
  10874. }
  10875. }
  10876. static
  10877. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  10878. {
  10879. struct thr_info *thr;
  10880. int j;
  10881. struct device_drv *api = cgpu->drv;
  10882. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10883. int threadobj = cgpu->threads;
  10884. if (!threadobj)
  10885. // Create a fake thread object to handle hashmeter etc
  10886. threadobj = 1;
  10887. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  10888. cgpu->thr[threadobj] = NULL;
  10889. cgpu->status = LIFE_INIT;
  10890. if (opt_devices_enabled_list)
  10891. {
  10892. struct string_elist *enablestr_elist;
  10893. cgpu->deven = DEV_DISABLED;
  10894. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  10895. {
  10896. const char * const enablestr = enablestr_elist->string;
  10897. if (cgpu_match(enablestr, cgpu))
  10898. {
  10899. cgpu->deven = DEV_ENABLED;
  10900. break;
  10901. }
  10902. }
  10903. }
  10904. cgpu->max_hashes = 0;
  10905. BFGINIT(cgpu->cutofftemp, opt_cutofftemp);
  10906. BFGINIT(cgpu->targettemp, cgpu->cutofftemp - 6);
  10907. // Setup thread structs before starting any of the threads, in case they try to interact
  10908. for (j = 0; j < threadobj; ++j, ++*kp) {
  10909. thr = get_thread(*kp);
  10910. thr->id = *kp;
  10911. thr->cgpu = cgpu;
  10912. thr->device_thread = j;
  10913. thr->work_restart_notifier[1] = INVSOCK;
  10914. thr->mutex_request[1] = INVSOCK;
  10915. thr->_job_transition_in_progress = true;
  10916. timerclear(&thr->tv_morework);
  10917. thr->scanhash_working = true;
  10918. thr->hashes_done = 0;
  10919. timerclear(&thr->tv_hashes_done);
  10920. cgtime(&thr->tv_lastupdate);
  10921. thr->tv_poll.tv_sec = -1;
  10922. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  10923. cgpu->thr[j] = thr;
  10924. }
  10925. if (!cgpu->device->threads)
  10926. notifier_init_invalid(cgpu->thr[0]->notifier);
  10927. else
  10928. if (!cgpu->threads)
  10929. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  10930. else
  10931. for (j = 0; j < cgpu->threads; ++j)
  10932. {
  10933. thr = cgpu->thr[j];
  10934. notifier_init(thr->notifier);
  10935. }
  10936. }
  10937. static
  10938. void start_cgpu(struct cgpu_info *cgpu)
  10939. {
  10940. struct thr_info *thr;
  10941. int j;
  10942. for (j = 0; j < cgpu->threads; ++j) {
  10943. thr = cgpu->thr[j];
  10944. /* Enable threads for devices set not to mine but disable
  10945. * their queue in case we wish to enable them later */
  10946. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  10947. continue;
  10948. thread_reportout(thr);
  10949. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  10950. quit(1, "thread %d create failed", thr->id);
  10951. notifier_wake(thr->notifier);
  10952. }
  10953. if (cgpu->deven == DEV_ENABLED)
  10954. proc_enable(cgpu);
  10955. }
  10956. static
  10957. void _scan_serial(void *p)
  10958. {
  10959. const char *s = p;
  10960. struct string_elist *iter, *tmp;
  10961. struct string_elist *orig_scan_devices = scan_devices;
  10962. if (s)
  10963. {
  10964. // Make temporary scan_devices list
  10965. scan_devices = NULL;
  10966. string_elist_add("noauto", &scan_devices);
  10967. add_serial(s);
  10968. }
  10969. drv_detect_all();
  10970. if (s)
  10971. {
  10972. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  10973. {
  10974. string_elist_del(&scan_devices, iter);
  10975. }
  10976. scan_devices = orig_scan_devices;
  10977. }
  10978. }
  10979. #ifdef HAVE_BFG_LOWLEVEL
  10980. static
  10981. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  10982. {
  10983. if (!(false
  10984. || (info->serial && !strcasecmp(ser, info->serial))
  10985. || (info->path && !strcasecmp(ser, info->path ))
  10986. || (info->devid && !strcasecmp(ser, info->devid ))
  10987. ))
  10988. {
  10989. char *devid = devpath_to_devid(ser);
  10990. if (!devid)
  10991. return false;
  10992. const bool different = strcmp(info->devid, devid);
  10993. free(devid);
  10994. if (different)
  10995. return false;
  10996. }
  10997. return true;
  10998. }
  10999. static
  11000. bool _probe_device_do_probe(const struct device_drv * const drv, const struct lowlevel_device_info * const info, bool * const request_rescan_p)
  11001. {
  11002. bfg_probe_result_flags = 0;
  11003. if (drv->lowl_probe(info))
  11004. {
  11005. if (!(bfg_probe_result_flags & BPR_CONTINUE_PROBES))
  11006. return true;
  11007. }
  11008. else
  11009. if (request_rescan_p && opt_hotplug && !(bfg_probe_result_flags & BPR_DONT_RESCAN))
  11010. *request_rescan_p = true;
  11011. return false;
  11012. }
  11013. bool dummy_check_never_true = false;
  11014. static
  11015. void *probe_device_thread(void *p)
  11016. {
  11017. struct lowlevel_device_info * const infolist = p;
  11018. struct lowlevel_device_info *info = infolist;
  11019. bool request_rescan = false;
  11020. {
  11021. char threadname[5 + strlen(info->devid) + 1];
  11022. sprintf(threadname, "probe_%s", info->devid);
  11023. RenameThread(threadname);
  11024. }
  11025. // If already in use, ignore
  11026. if (bfg_claim_any(NULL, NULL, info->devid))
  11027. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  11028. __func__, info->product);
  11029. // if lowlevel device matches specific user assignment, probe requested driver(s)
  11030. struct string_elist *sd_iter, *sd_tmp;
  11031. struct driver_registration *dreg;
  11032. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  11033. {
  11034. const char * const dname = sd_iter->string;
  11035. const char * const colon = strpbrk(dname, ":@");
  11036. if (!(colon && colon != dname))
  11037. continue;
  11038. const char * const ser = &colon[1];
  11039. LL_FOREACH2(infolist, info, same_devid_next)
  11040. {
  11041. if (!_probe_device_match(info, ser))
  11042. continue;
  11043. const size_t dnamelen = (colon - dname);
  11044. char dname_nt[dnamelen + 1];
  11045. memcpy(dname_nt, dname, dnamelen);
  11046. dname_nt[dnamelen] = '\0';
  11047. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg) {
  11048. const struct device_drv * const drv = dreg->drv;
  11049. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  11050. continue;
  11051. if (strcasecmp(drv->dname, dname_nt) && strcasecmp(drv->name, dname_nt))
  11052. continue;
  11053. if (_probe_device_do_probe(drv, info, &request_rescan))
  11054. return NULL;
  11055. }
  11056. }
  11057. }
  11058. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  11059. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg)
  11060. {
  11061. const struct device_drv * const drv = dreg->drv;
  11062. if (!drv_algo_check(drv))
  11063. continue;
  11064. // Check for "noauto" flag
  11065. // NOTE: driver-specific configuration overrides general
  11066. bool doauto = true;
  11067. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  11068. {
  11069. const char * const dname = sd_iter->string;
  11070. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  11071. const char *colon = strchr(dname, ':');
  11072. if (!colon)
  11073. colon = &dname[-1];
  11074. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  11075. continue;
  11076. const ssize_t dnamelen = (colon - dname);
  11077. if (dnamelen >= 0) {
  11078. char dname_nt[dnamelen + 1];
  11079. memcpy(dname_nt, dname, dnamelen);
  11080. dname_nt[dnamelen] = '\0';
  11081. if (strcasecmp(drv->dname, dname_nt) && strcasecmp(drv->name, dname_nt))
  11082. continue;
  11083. }
  11084. doauto = (tolower(colon[1]) == 'a');
  11085. if (dnamelen != -1)
  11086. break;
  11087. }
  11088. if (doauto && drv->lowl_match)
  11089. {
  11090. LL_FOREACH2(infolist, info, same_devid_next)
  11091. {
  11092. /*
  11093. The below call to applog is absolutely necessary
  11094. Starting with commit 76d0cc183b1c9ddcc0ef34d2e43bc696ef9de92e installing BFGMiner on
  11095. Mac OS X using Homebrew results in a binary that segfaults on startup
  11096. There are two unresolved issues:
  11097. 1) The BFGMiner authors cannot find a way to install BFGMiner with Homebrew that results
  11098. in debug symbols being available to help troubleshoot the issue
  11099. 2) The issue disappears when unrelated code changes are made, such as adding the following
  11100. call to applog with infolist and / or p
  11101. We would encourage revisiting this in the future to come up with a more concrete solution
  11102. Reproducing should only require commenting / removing the following line and installing
  11103. BFGMiner using "brew install bfgminer --HEAD"
  11104. */
  11105. if (dummy_check_never_true)
  11106. applog(LOG_DEBUG, "lowl_match: %p(%s) %p %p %p", drv, drv->dname, info, infolist, p);
  11107. if (!drv->lowl_match(info))
  11108. continue;
  11109. if (_probe_device_do_probe(drv, info, &request_rescan))
  11110. return NULL;
  11111. }
  11112. }
  11113. }
  11114. // probe driver(s) with 'all' enabled
  11115. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  11116. {
  11117. const char * const dname = sd_iter->string;
  11118. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  11119. const char * const colon = strchr(dname, ':');
  11120. if (!colon)
  11121. {
  11122. LL_FOREACH2(infolist, info, same_devid_next)
  11123. {
  11124. if (
  11125. #ifdef NEED_BFG_LOWL_VCOM
  11126. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  11127. #endif
  11128. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  11129. {
  11130. bool dont_rescan = false;
  11131. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg)
  11132. {
  11133. const struct device_drv * const drv = dreg->drv;
  11134. if (!drv_algo_check(drv))
  11135. continue;
  11136. if (drv->lowl_probe_by_name_only)
  11137. continue;
  11138. if (!drv->lowl_probe)
  11139. continue;
  11140. if (_probe_device_do_probe(drv, info, NULL))
  11141. return NULL;
  11142. if (bfg_probe_result_flags & BPR_DONT_RESCAN)
  11143. dont_rescan = true;
  11144. }
  11145. if (opt_hotplug && !dont_rescan)
  11146. request_rescan = true;
  11147. break;
  11148. }
  11149. }
  11150. continue;
  11151. }
  11152. if (strcasecmp(&colon[1], "all"))
  11153. continue;
  11154. const size_t dnamelen = (colon - dname);
  11155. char dname_nt[dnamelen + 1];
  11156. memcpy(dname_nt, dname, dnamelen);
  11157. dname_nt[dnamelen] = '\0';
  11158. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg) {
  11159. const struct device_drv * const drv = dreg->drv;
  11160. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  11161. continue;
  11162. if (strcasecmp(drv->dname, dname_nt) && strcasecmp(drv->name, dname_nt))
  11163. continue;
  11164. LL_FOREACH2(infolist, info, same_devid_next)
  11165. {
  11166. if (info->lowl->exclude_from_all)
  11167. continue;
  11168. if (_probe_device_do_probe(drv, info, NULL))
  11169. return NULL;
  11170. }
  11171. }
  11172. }
  11173. // Only actually request a rescan if we never found any cgpu
  11174. if (request_rescan)
  11175. bfg_need_detect_rescan = true;
  11176. return NULL;
  11177. }
  11178. void probe_device(struct lowlevel_device_info * const info)
  11179. {
  11180. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  11181. }
  11182. #endif
  11183. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  11184. {
  11185. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  11186. int devcount, i, mining_threads_new = 0;
  11187. unsigned int k;
  11188. struct cgpu_info *cgpu;
  11189. struct thr_info *thr;
  11190. void *p;
  11191. mutex_lock(&mutex);
  11192. devcount = total_devices;
  11193. addfunc(arg);
  11194. if (!total_devices_new)
  11195. goto out;
  11196. wr_lock(&devices_lock);
  11197. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  11198. if (unlikely(!p))
  11199. {
  11200. wr_unlock(&devices_lock);
  11201. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  11202. goto out;
  11203. }
  11204. devices = p;
  11205. wr_unlock(&devices_lock);
  11206. for (i = 0; i < total_devices_new; ++i)
  11207. {
  11208. cgpu = devices_new[i];
  11209. mining_threads_new += cgpu->threads ?: 1;
  11210. }
  11211. wr_lock(&mining_thr_lock);
  11212. mining_threads_new += mining_threads;
  11213. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  11214. if (unlikely(!p))
  11215. {
  11216. wr_unlock(&mining_thr_lock);
  11217. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  11218. goto out;
  11219. }
  11220. mining_thr = p;
  11221. wr_unlock(&mining_thr_lock);
  11222. for (i = mining_threads; i < mining_threads_new; ++i) {
  11223. mining_thr[i] = calloc(1, sizeof(*thr));
  11224. if (!mining_thr[i])
  11225. {
  11226. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  11227. for ( ; --i >= mining_threads; )
  11228. free(mining_thr[i]);
  11229. goto out;
  11230. }
  11231. }
  11232. k = mining_threads;
  11233. for (i = 0; i < total_devices_new; ++i)
  11234. {
  11235. cgpu = devices_new[i];
  11236. allocate_cgpu(cgpu, &k);
  11237. }
  11238. for (i = 0; i < total_devices_new; ++i)
  11239. {
  11240. cgpu = devices_new[i];
  11241. start_cgpu(cgpu);
  11242. register_device(cgpu);
  11243. ++total_devices;
  11244. }
  11245. #ifdef HAVE_CURSES
  11246. switch_logsize();
  11247. #endif
  11248. out:
  11249. total_devices_new = 0;
  11250. devcount = total_devices - devcount;
  11251. mutex_unlock(&mutex);
  11252. return devcount;
  11253. }
  11254. int scan_serial(const char *s)
  11255. {
  11256. return create_new_cgpus(_scan_serial, (void*)s);
  11257. }
  11258. static pthread_mutex_t rescan_mutex = PTHREAD_MUTEX_INITIALIZER;
  11259. static bool rescan_active;
  11260. static struct timeval tv_rescan;
  11261. static notifier_t rescan_notifier;
  11262. static
  11263. void *rescan_thread(__maybe_unused void *p)
  11264. {
  11265. pthread_detach(pthread_self());
  11266. RenameThread("rescan");
  11267. struct timeval tv_timeout, tv_now;
  11268. fd_set rfds;
  11269. while (true)
  11270. {
  11271. mutex_lock(&rescan_mutex);
  11272. tv_timeout = tv_rescan;
  11273. if (!timer_isset(&tv_timeout))
  11274. {
  11275. rescan_active = false;
  11276. mutex_unlock(&rescan_mutex);
  11277. break;
  11278. }
  11279. mutex_unlock(&rescan_mutex);
  11280. FD_ZERO(&rfds);
  11281. FD_SET(rescan_notifier[0], &rfds);
  11282. const int maxfd = rescan_notifier[0];
  11283. timer_set_now(&tv_now);
  11284. if (select(maxfd+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now)) > 0)
  11285. notifier_read(rescan_notifier);
  11286. mutex_lock(&rescan_mutex);
  11287. if (timer_passed(&tv_rescan, NULL))
  11288. {
  11289. timer_unset(&tv_rescan);
  11290. mutex_unlock(&rescan_mutex);
  11291. applog(LOG_DEBUG, "Rescan timer expired, triggering");
  11292. scan_serial(NULL);
  11293. }
  11294. else
  11295. mutex_unlock(&rescan_mutex);
  11296. }
  11297. return NULL;
  11298. }
  11299. static
  11300. void _schedule_rescan(const struct timeval * const tvp_when)
  11301. {
  11302. if (rescan_active)
  11303. {
  11304. if (timercmp(tvp_when, &tv_rescan, <))
  11305. applog(LOG_DEBUG, "schedule_rescan: New schedule is before current, waiting it out");
  11306. else
  11307. {
  11308. applog(LOG_DEBUG, "schedule_rescan: New schedule is after current, delaying rescan");
  11309. tv_rescan = *tvp_when;
  11310. }
  11311. return;
  11312. }
  11313. applog(LOG_DEBUG, "schedule_rescan: Scheduling rescan (no rescans currently pending)");
  11314. tv_rescan = *tvp_when;
  11315. rescan_active = true;
  11316. static pthread_t pth;
  11317. if (unlikely(pthread_create(&pth, NULL, rescan_thread, NULL)))
  11318. applog(LOG_ERR, "Failed to start rescan thread");
  11319. }
  11320. static
  11321. void schedule_rescan(const struct timeval * const tvp_when)
  11322. {
  11323. mutex_lock(&rescan_mutex);
  11324. _schedule_rescan(tvp_when);
  11325. mutex_unlock(&rescan_mutex);
  11326. }
  11327. static
  11328. void hotplug_trigger()
  11329. {
  11330. applog(LOG_DEBUG, "%s: Scheduling rescan immediately", __func__);
  11331. struct timeval tv_now;
  11332. timer_set_now(&tv_now);
  11333. schedule_rescan(&tv_now);
  11334. }
  11335. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  11336. static
  11337. void *hotplug_thread(__maybe_unused void *p)
  11338. {
  11339. pthread_detach(pthread_self());
  11340. RenameThread("hotplug");
  11341. struct udev * const udev = udev_new();
  11342. if (unlikely(!udev))
  11343. applogfailr(NULL, LOG_ERR, "udev_new");
  11344. struct udev_monitor * const mon = udev_monitor_new_from_netlink(udev, "udev");
  11345. if (unlikely(!mon))
  11346. applogfailr(NULL, LOG_ERR, "udev_monitor_new_from_netlink");
  11347. if (unlikely(udev_monitor_enable_receiving(mon)))
  11348. applogfailr(NULL, LOG_ERR, "udev_monitor_enable_receiving");
  11349. const int epfd = epoll_create(1);
  11350. if (unlikely(epfd == -1))
  11351. applogfailr(NULL, LOG_ERR, "epoll_create");
  11352. {
  11353. const int fd = udev_monitor_get_fd(mon);
  11354. struct epoll_event ev = {
  11355. .events = EPOLLIN | EPOLLPRI,
  11356. .data.fd = fd,
  11357. };
  11358. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev))
  11359. applogfailr(NULL, LOG_ERR, "epoll_ctl");
  11360. }
  11361. struct epoll_event ev;
  11362. int rv;
  11363. bool pending = false;
  11364. while (true)
  11365. {
  11366. rv = epoll_wait(epfd, &ev, 1, pending ? hotplug_delay_ms : -1);
  11367. if (rv == -1)
  11368. {
  11369. if (errno == EAGAIN || errno == EINTR)
  11370. continue;
  11371. break;
  11372. }
  11373. if (!rv)
  11374. {
  11375. hotplug_trigger();
  11376. pending = false;
  11377. continue;
  11378. }
  11379. struct udev_device * const device = udev_monitor_receive_device(mon);
  11380. if (!device)
  11381. continue;
  11382. const char * const action = udev_device_get_action(device);
  11383. applog(LOG_DEBUG, "%s: Received %s event", __func__, action);
  11384. if (!strcmp(action, "add"))
  11385. pending = true;
  11386. udev_device_unref(device);
  11387. }
  11388. applogfailr(NULL, LOG_ERR, "epoll_wait");
  11389. }
  11390. #elif defined(WIN32)
  11391. static UINT_PTR _hotplug_wintimer_id;
  11392. VOID CALLBACK hotplug_win_timer(HWND hwnd, UINT msg, UINT_PTR idEvent, DWORD dwTime)
  11393. {
  11394. KillTimer(NULL, _hotplug_wintimer_id);
  11395. _hotplug_wintimer_id = 0;
  11396. hotplug_trigger();
  11397. }
  11398. LRESULT CALLBACK hotplug_win_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  11399. {
  11400. if (msg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED)
  11401. {
  11402. applog(LOG_DEBUG, "%s: Received DBT_DEVNODES_CHANGED event", __func__);
  11403. _hotplug_wintimer_id = SetTimer(NULL, _hotplug_wintimer_id, hotplug_delay_ms, hotplug_win_timer);
  11404. }
  11405. return DefWindowProc(hwnd, msg, wParam, lParam);
  11406. }
  11407. static
  11408. void *hotplug_thread(__maybe_unused void *p)
  11409. {
  11410. pthread_detach(pthread_self());
  11411. WNDCLASS DummyWinCls = {
  11412. .lpszClassName = "BFGDummyWinCls",
  11413. .lpfnWndProc = hotplug_win_callback,
  11414. };
  11415. ATOM a = RegisterClass(&DummyWinCls);
  11416. if (unlikely(!a))
  11417. applogfailinfor(NULL, LOG_ERR, "RegisterClass", "%d", (int)GetLastError());
  11418. HWND hwnd = CreateWindow((void*)(intptr_t)a, NULL, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
  11419. if (unlikely(!hwnd))
  11420. applogfailinfor(NULL, LOG_ERR, "CreateWindow", "%d", (int)GetLastError());
  11421. MSG msg;
  11422. while (GetMessage(&msg, NULL, 0, 0))
  11423. {
  11424. TranslateMessage(&msg);
  11425. DispatchMessage(&msg);
  11426. }
  11427. quit(0, "WM_QUIT received");
  11428. return NULL;
  11429. }
  11430. #endif
  11431. #ifdef HAVE_BFG_HOTPLUG
  11432. static
  11433. void hotplug_start()
  11434. {
  11435. pthread_t pth;
  11436. if (unlikely(pthread_create(&pth, NULL, hotplug_thread, NULL)))
  11437. applog(LOG_ERR, "Failed to start hotplug thread");
  11438. }
  11439. #endif
  11440. static void probe_pools(void)
  11441. {
  11442. int i;
  11443. for (i = 0; i < total_pools; i++) {
  11444. struct pool *pool = pools[i];
  11445. pool->testing = true;
  11446. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  11447. }
  11448. }
  11449. static void raise_fd_limits(void)
  11450. {
  11451. #ifdef HAVE_SETRLIMIT
  11452. struct rlimit fdlimit;
  11453. rlim_t old_soft_limit;
  11454. char frombuf[0x10] = "unlimited";
  11455. char hardbuf[0x10] = "unlimited";
  11456. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  11457. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  11458. old_soft_limit = fdlimit.rlim_cur;
  11459. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  11460. fdlimit.rlim_cur = FD_SETSIZE;
  11461. else
  11462. fdlimit.rlim_cur = fdlimit.rlim_max;
  11463. if (fdlimit.rlim_max != RLIM_INFINITY)
  11464. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  11465. if (old_soft_limit != RLIM_INFINITY)
  11466. snprintf(frombuf, sizeof(frombuf), "%lu", (unsigned long)old_soft_limit);
  11467. if (fdlimit.rlim_cur == old_soft_limit)
  11468. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11469. (unsigned long)old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  11470. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  11471. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11472. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11473. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11474. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11475. #else
  11476. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  11477. #endif
  11478. }
  11479. static
  11480. void bfg_atexit(void)
  11481. {
  11482. puts("");
  11483. }
  11484. extern void bfg_init_threadlocal();
  11485. extern void stratumsrv_start();
  11486. extern void test_aan_pll(void);
  11487. int main(int argc, char *argv[])
  11488. {
  11489. struct sigaction handler;
  11490. struct thr_info *thr;
  11491. unsigned int k;
  11492. int i;
  11493. int rearrange_pools = 0;
  11494. char *s;
  11495. #ifdef WIN32
  11496. LoadLibrary("backtrace.dll");
  11497. #endif
  11498. atexit(bfg_atexit);
  11499. b58_sha256_impl = my_blkmaker_sha256_callback;
  11500. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  11501. bfg_init_threadlocal();
  11502. #ifndef HAVE_PTHREAD_CANCEL
  11503. setup_pthread_cancel_workaround();
  11504. #endif
  11505. bfg_init_checksums();
  11506. #ifdef WIN32
  11507. {
  11508. WSADATA wsa;
  11509. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  11510. if (i)
  11511. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  11512. }
  11513. #endif
  11514. /* This dangerous functions tramples random dynamically allocated
  11515. * variables so do it before anything at all */
  11516. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  11517. quit(1, "Failed to curl_global_init");
  11518. initial_args = malloc(sizeof(char *) * (argc + 1));
  11519. for (i = 0; i < argc; i++)
  11520. initial_args[i] = strdup(argv[i]);
  11521. initial_args[argc] = NULL;
  11522. mutex_init(&hash_lock);
  11523. mutex_init(&console_lock);
  11524. cglock_init(&control_lock);
  11525. mutex_init(&stats_lock);
  11526. mutex_init(&sharelog_lock);
  11527. cglock_init(&ch_lock);
  11528. mutex_init(&sshare_lock);
  11529. rwlock_init(&blk_lock);
  11530. rwlock_init(&netacc_lock);
  11531. rwlock_init(&mining_thr_lock);
  11532. rwlock_init(&devices_lock);
  11533. mutex_init(&lp_lock);
  11534. if (unlikely(pthread_cond_init(&lp_cond, bfg_condattr)))
  11535. quit(1, "Failed to pthread_cond_init lp_cond");
  11536. if (unlikely(pthread_cond_init(&gws_cond, bfg_condattr)))
  11537. quit(1, "Failed to pthread_cond_init gws_cond");
  11538. notifier_init(submit_waiting_notifier);
  11539. timer_unset(&tv_rescan);
  11540. notifier_init(rescan_notifier);
  11541. /* Create a unique get work queue */
  11542. getq = tq_new();
  11543. if (!getq)
  11544. quit(1, "Failed to create getq");
  11545. /* We use the getq mutex as the staged lock */
  11546. stgd_lock = &getq->mutex;
  11547. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  11548. init_max_name_len();
  11549. #endif
  11550. handler.sa_handler = &sighandler;
  11551. handler.sa_flags = 0;
  11552. sigemptyset(&handler.sa_mask);
  11553. #ifdef HAVE_PTHREAD_CANCEL
  11554. sigaction(SIGTERM, &handler, &termhandler);
  11555. #else
  11556. // Need to let pthread_cancel emulation handle SIGTERM first
  11557. termhandler = pcwm_orig_term_handler;
  11558. pcwm_orig_term_handler = handler;
  11559. #endif
  11560. sigaction(SIGINT, &handler, &inthandler);
  11561. #ifndef WIN32
  11562. signal(SIGPIPE, SIG_IGN);
  11563. #else
  11564. timeBeginPeriod(1);
  11565. #endif
  11566. opt_kernel_path = CGMINER_PREFIX;
  11567. cgminer_path = alloca(PATH_MAX);
  11568. s = strdup(argv[0]);
  11569. strcpy(cgminer_path, dirname(s));
  11570. free(s);
  11571. strcat(cgminer_path, "/");
  11572. #if defined(USE_CPUMINING) && defined(WIN32)
  11573. {
  11574. char buf[32];
  11575. int gev = GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, sizeof(buf));
  11576. if (gev > 0 && gev < sizeof(buf))
  11577. {
  11578. setup_benchmark_pool();
  11579. double rate = bench_algo_stage3(atoi(buf));
  11580. // Write result to shared memory for parent
  11581. char unique_name[64];
  11582. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32))
  11583. {
  11584. HANDLE map_handle = CreateFileMapping(
  11585. INVALID_HANDLE_VALUE, // use paging file
  11586. NULL, // default security attributes
  11587. PAGE_READWRITE, // read/write access
  11588. 0, // size: high 32-bits
  11589. 4096, // size: low 32-bits
  11590. unique_name // name of map object
  11591. );
  11592. if (NULL != map_handle) {
  11593. void *shared_mem = MapViewOfFile(
  11594. map_handle, // object to map view of
  11595. FILE_MAP_WRITE, // read/write access
  11596. 0, // high offset: map from
  11597. 0, // low offset: beginning
  11598. 0 // default: map entire file
  11599. );
  11600. if (NULL != shared_mem)
  11601. CopyMemory(shared_mem, &rate, sizeof(rate));
  11602. (void)UnmapViewOfFile(shared_mem);
  11603. }
  11604. (void)CloseHandle(map_handle);
  11605. }
  11606. exit(0);
  11607. }
  11608. }
  11609. #endif
  11610. #ifdef HAVE_CURSES
  11611. devcursor = 8;
  11612. logstart = devcursor;
  11613. logcursor = logstart;
  11614. #endif
  11615. mutex_init(&submitting_lock);
  11616. // Ensure at least the default goal is created
  11617. get_mining_goal("default");
  11618. #ifdef USE_OPENCL
  11619. opencl_early_init();
  11620. #endif
  11621. schedstart.tm.tm_sec = 1;
  11622. schedstop .tm.tm_sec = 1;
  11623. opt_register_table(opt_early_table, NULL);
  11624. opt_register_table(opt_config_table, NULL);
  11625. opt_register_table(opt_cmdline_table, NULL);
  11626. opt_early_parse(argc, argv, applog_and_exit);
  11627. if (!config_loaded)
  11628. {
  11629. load_default_config();
  11630. rearrange_pools = total_pools;
  11631. }
  11632. opt_free_table();
  11633. /* parse command line */
  11634. opt_register_table(opt_config_table,
  11635. "Options for both config file and command line");
  11636. opt_register_table(opt_cmdline_table,
  11637. "Options for command line only");
  11638. opt_parse(&argc, argv, applog_and_exit);
  11639. if (argc != 1)
  11640. quit(1, "Unexpected extra commandline arguments");
  11641. if (rearrange_pools && rearrange_pools < total_pools)
  11642. {
  11643. // Prioritise commandline pools before default-config pools
  11644. for (i = 0; i < rearrange_pools; ++i)
  11645. pools[i]->prio += rearrange_pools;
  11646. for ( ; i < total_pools; ++i)
  11647. pools[i]->prio -= rearrange_pools;
  11648. }
  11649. #ifndef HAVE_PTHREAD_CANCEL
  11650. // Can't do this any earlier, or config isn't loaded
  11651. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  11652. #endif
  11653. #ifdef HAVE_PWD_H
  11654. struct passwd *user_info = NULL;
  11655. if (opt_setuid != NULL) {
  11656. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  11657. quit(1, "Unable to find setuid user information");
  11658. }
  11659. }
  11660. #endif
  11661. #ifdef HAVE_CHROOT
  11662. if (chroot_dir != NULL) {
  11663. #ifdef HAVE_PWD_H
  11664. if (user_info == NULL && getuid() == 0) {
  11665. applog(LOG_WARNING, "Running as root inside chroot");
  11666. }
  11667. #endif
  11668. if (chroot(chroot_dir) != 0) {
  11669. quit(1, "Unable to chroot");
  11670. }
  11671. if (chdir("/"))
  11672. quit(1, "Unable to chdir to chroot");
  11673. }
  11674. #endif
  11675. #ifdef HAVE_PWD_H
  11676. if (user_info != NULL) {
  11677. if (setgid((*user_info).pw_gid) != 0)
  11678. quit(1, "Unable to setgid");
  11679. if (setuid((*user_info).pw_uid) != 0)
  11680. quit(1, "Unable to setuid");
  11681. }
  11682. #endif
  11683. raise_fd_limits();
  11684. if (opt_benchmark) {
  11685. while (total_pools)
  11686. remove_pool(pools[0]);
  11687. setup_benchmark_pool();
  11688. }
  11689. if (opt_unittest) {
  11690. test_cgpu_match();
  11691. test_intrange();
  11692. test_decimal_width();
  11693. test_domain_funcs();
  11694. #ifdef USE_SCRYPT
  11695. test_scrypt();
  11696. #endif
  11697. test_target();
  11698. test_uri_get_param();
  11699. utf8_test();
  11700. #ifdef USE_JINGTIAN
  11701. test_aan_pll();
  11702. #endif
  11703. if (unittest_failures)
  11704. quit(1, "Unit tests failed");
  11705. }
  11706. #ifdef HAVE_CURSES
  11707. if (opt_realquiet || opt_display_devs)
  11708. use_curses = false;
  11709. setlocale(LC_ALL, "C");
  11710. if (use_curses)
  11711. enable_curses();
  11712. #endif
  11713. #ifdef HAVE_LIBUSB
  11714. int err = libusb_init(NULL);
  11715. if (err)
  11716. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  11717. else
  11718. have_libusb = true;
  11719. #endif
  11720. applog(LOG_WARNING, "Started %s", packagename);
  11721. {
  11722. struct bfg_loaded_configfile *configfile;
  11723. LL_FOREACH(bfg_loaded_configfiles, configfile)
  11724. {
  11725. char * const cnfbuf = configfile->filename;
  11726. int fileconf_load = configfile->fileconf_load;
  11727. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  11728. switch (fileconf_load) {
  11729. case 0:
  11730. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  11731. applog(LOG_WARNING, "Configuration file could not be used.");
  11732. break;
  11733. case -1:
  11734. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  11735. if (use_curses)
  11736. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  11737. break;
  11738. default:
  11739. break;
  11740. }
  11741. }
  11742. }
  11743. i = strlen(opt_kernel_path) + 2;
  11744. char __kernel_path[i];
  11745. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  11746. opt_kernel_path = __kernel_path;
  11747. if (want_per_device_stats)
  11748. opt_log_output = true;
  11749. bfg_devapi_init();
  11750. drv_detect_all();
  11751. total_devices = total_devices_new;
  11752. devices = devices_new;
  11753. total_devices_new = 0;
  11754. devices_new = NULL;
  11755. if (opt_display_devs) {
  11756. int devcount = 0;
  11757. applog(LOG_ERR, "Devices detected:");
  11758. for (i = 0; i < total_devices; ++i) {
  11759. struct cgpu_info *cgpu = devices[i];
  11760. char buf[0x100];
  11761. if (cgpu->device != cgpu)
  11762. continue;
  11763. if (cgpu->name)
  11764. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  11765. else
  11766. if (cgpu->dev_manufacturer)
  11767. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  11768. else
  11769. if (cgpu->dev_product)
  11770. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  11771. else
  11772. strcpy(buf, " Device");
  11773. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  11774. if (cgpu->dev_serial)
  11775. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  11776. if (cgpu->device_path)
  11777. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  11778. tailsprintf(buf, sizeof(buf), ")");
  11779. _applog(LOG_NOTICE, buf);
  11780. ++devcount;
  11781. }
  11782. quit(0, "%d devices listed", devcount);
  11783. }
  11784. mining_threads = 0;
  11785. for (i = 0; i < total_devices; ++i)
  11786. register_device(devices[i]);
  11787. if (!total_devices) {
  11788. applog(LOG_WARNING, "No devices detected!");
  11789. if (use_curses)
  11790. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  11791. else
  11792. applog(LOG_WARNING, "Waiting for devices");
  11793. }
  11794. #ifdef HAVE_CURSES
  11795. switch_logsize();
  11796. #endif
  11797. #if BLKMAKER_VERSION > 1 && defined(USE_SHA256D)
  11798. if (opt_load_bitcoin_conf && !(get_mining_goal("default")->malgo->algo != POW_SHA256D || opt_benchmark))
  11799. add_local_gbt(total_pools);
  11800. #endif
  11801. if (!total_pools) {
  11802. applog(LOG_WARNING, "Need to specify at least one pool server.");
  11803. #ifdef HAVE_CURSES
  11804. if (!use_curses || !input_pool(false))
  11805. #endif
  11806. quit(1, "Pool setup failed");
  11807. }
  11808. for (i = 0; i < total_pools; i++) {
  11809. struct pool *pool = pools[i];
  11810. size_t siz;
  11811. if (!pool->rpc_url)
  11812. quit(1, "No URI supplied for pool %u", i);
  11813. if (!pool->rpc_userpass) {
  11814. if (!pool->rpc_user || !pool->rpc_pass)
  11815. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  11816. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  11817. pool->rpc_userpass = malloc(siz);
  11818. if (!pool->rpc_userpass)
  11819. quit(1, "Failed to malloc userpass");
  11820. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  11821. }
  11822. }
  11823. /* Set the currentpool to pool with priority 0 */
  11824. validate_pool_priorities();
  11825. for (i = 0; i < total_pools; i++) {
  11826. struct pool *pool = pools[i];
  11827. if (!pool->prio)
  11828. currentpool = pool;
  11829. }
  11830. #ifdef HAVE_SYSLOG_H
  11831. if (use_syslog)
  11832. openlog(PACKAGE, LOG_PID, LOG_USER);
  11833. #endif
  11834. #if defined(unix) || defined(__APPLE__)
  11835. if (opt_stderr_cmd)
  11836. fork_monitor();
  11837. #endif // defined(unix)
  11838. mining_thr = calloc(mining_threads, sizeof(thr));
  11839. if (!mining_thr)
  11840. quit(1, "Failed to calloc mining_thr");
  11841. for (i = 0; i < mining_threads; i++) {
  11842. mining_thr[i] = calloc(1, sizeof(*thr));
  11843. if (!mining_thr[i])
  11844. quit(1, "Failed to calloc mining_thr[%d]", i);
  11845. }
  11846. total_control_threads = 6;
  11847. control_thr = calloc(total_control_threads, sizeof(*thr));
  11848. if (!control_thr)
  11849. quit(1, "Failed to calloc control_thr");
  11850. if (opt_benchmark)
  11851. goto begin_bench;
  11852. applog(LOG_NOTICE, "Probing for an alive pool");
  11853. do {
  11854. bool still_testing;
  11855. int i;
  11856. /* Look for at least one active pool before starting */
  11857. probe_pools();
  11858. do {
  11859. sleep(1);
  11860. if (pools_active)
  11861. break;
  11862. still_testing = false;
  11863. for (int i = 0; i < total_pools; ++i)
  11864. if (pools[i]->testing)
  11865. still_testing = true;
  11866. } while (still_testing);
  11867. if (!pools_active) {
  11868. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  11869. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  11870. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  11871. for (i = 0; i < total_pools; i++) {
  11872. struct pool *pool;
  11873. pool = pools[i];
  11874. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  11875. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  11876. }
  11877. #ifdef HAVE_CURSES
  11878. if (use_curses) {
  11879. halfdelay(150);
  11880. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  11881. if (getch() != ERR)
  11882. quit(0, "No servers could be used! Exiting.");
  11883. cbreak();
  11884. } else
  11885. #endif
  11886. quit(0, "No servers could be used! Exiting.");
  11887. }
  11888. } while (!pools_active);
  11889. #ifdef USE_SCRYPT
  11890. if (detect_algo == 1 && get_mining_goal("default")->malgo->algo != POW_SCRYPT) {
  11891. applog(LOG_NOTICE, "Detected scrypt algorithm");
  11892. set_malgo_scrypt();
  11893. }
  11894. #endif
  11895. detect_algo = 0;
  11896. begin_bench:
  11897. total_mhashes_done = 0;
  11898. for (i = 0; i < total_devices; i++) {
  11899. struct cgpu_info *cgpu = devices[i];
  11900. cgpu->rolling = cgpu->total_mhashes = 0;
  11901. }
  11902. cgtime(&total_tv_start);
  11903. cgtime(&total_tv_end);
  11904. miner_started = total_tv_start;
  11905. time_t miner_start_ts = time(NULL);
  11906. if (schedstart.tm.tm_sec)
  11907. localtime_r(&miner_start_ts, &schedstart.tm);
  11908. if (schedstop.tm.tm_sec)
  11909. localtime_r(&miner_start_ts, &schedstop .tm);
  11910. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  11911. // Initialise processors and threads
  11912. k = 0;
  11913. for (i = 0; i < total_devices; ++i) {
  11914. struct cgpu_info *cgpu = devices[i];
  11915. allocate_cgpu(cgpu, &k);
  11916. }
  11917. // Start threads
  11918. for (i = 0; i < total_devices; ++i) {
  11919. struct cgpu_info *cgpu = devices[i];
  11920. start_cgpu(cgpu);
  11921. }
  11922. #ifdef USE_OPENCL
  11923. for (i = 0; i < nDevs; i++)
  11924. pause_dynamic_threads(i);
  11925. #endif
  11926. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  11927. if (opt_n_threads > 0)
  11928. applog(LOG_INFO, "%d cpu miner threads started, using '%s' algorithm.",
  11929. opt_n_threads, algo_names[opt_algo]);
  11930. #endif
  11931. cgtime(&total_tv_start);
  11932. cgtime(&total_tv_end);
  11933. if (!opt_benchmark)
  11934. {
  11935. pthread_t submit_thread;
  11936. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  11937. quit(1, "submit_work thread create failed");
  11938. }
  11939. watchpool_thr_id = 1;
  11940. thr = &control_thr[watchpool_thr_id];
  11941. /* start watchpool thread */
  11942. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  11943. quit(1, "watchpool thread create failed");
  11944. pthread_detach(thr->pth);
  11945. watchdog_thr_id = 2;
  11946. thr = &control_thr[watchdog_thr_id];
  11947. /* start watchdog thread */
  11948. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  11949. quit(1, "watchdog thread create failed");
  11950. pthread_detach(thr->pth);
  11951. #ifdef USE_OPENCL
  11952. /* Create reinit gpu thread */
  11953. gpur_thr_id = 3;
  11954. thr = &control_thr[gpur_thr_id];
  11955. thr->q = tq_new();
  11956. if (!thr->q)
  11957. quit(1, "tq_new failed for gpur_thr_id");
  11958. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  11959. quit(1, "reinit_gpu thread create failed");
  11960. #endif
  11961. /* Create API socket thread */
  11962. api_thr_id = 4;
  11963. thr = &control_thr[api_thr_id];
  11964. if (thr_info_create(thr, NULL, api_thread, thr))
  11965. quit(1, "API thread create failed");
  11966. #ifdef USE_LIBMICROHTTPD
  11967. if (httpsrv_port != -1)
  11968. httpsrv_start(httpsrv_port);
  11969. #endif
  11970. #ifdef USE_LIBEVENT
  11971. if (stratumsrv_port != -1)
  11972. stratumsrv_start();
  11973. #endif
  11974. #ifdef HAVE_BFG_HOTPLUG
  11975. if (opt_hotplug)
  11976. hotplug_start();
  11977. #endif
  11978. #ifdef HAVE_CURSES
  11979. /* Create curses input thread for keyboard input. Create this last so
  11980. * that we know all threads are created since this can call kill_work
  11981. * to try and shut down ll previous threads. */
  11982. input_thr_id = 5;
  11983. thr = &control_thr[input_thr_id];
  11984. if (thr_info_create(thr, NULL, input_thread, thr))
  11985. quit(1, "input thread create failed");
  11986. pthread_detach(thr->pth);
  11987. #endif
  11988. /* Just to be sure */
  11989. if (total_control_threads != 6)
  11990. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  11991. /* Once everything is set up, main() becomes the getwork scheduler */
  11992. while (42) {
  11993. int ts, max_staged = opt_queue;
  11994. struct pool *pool, *cp;
  11995. bool lagging = false;
  11996. struct curl_ent *ce;
  11997. struct work *work;
  11998. struct mining_algorithm *malgo = NULL;
  11999. cp = current_pool();
  12000. // Generally, each processor needs a new work, and all at once during work restarts
  12001. max_staged += base_queue;
  12002. mutex_lock(stgd_lock);
  12003. ts = __total_staged(false);
  12004. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  12005. lagging = true;
  12006. /* Wait until hash_pop tells us we need to create more work */
  12007. if (ts > max_staged) {
  12008. {
  12009. LL_FOREACH(mining_algorithms, malgo)
  12010. {
  12011. if (!malgo->goal_refs)
  12012. continue;
  12013. if (!malgo->base_queue)
  12014. continue;
  12015. if (malgo->staged < malgo->base_queue + opt_queue)
  12016. {
  12017. mutex_unlock(stgd_lock);
  12018. pool = select_pool(lagging, malgo);
  12019. if (pool)
  12020. {
  12021. work = make_work();
  12022. work->spare = true;
  12023. goto retry;
  12024. }
  12025. mutex_lock(stgd_lock);
  12026. }
  12027. }
  12028. malgo = NULL;
  12029. }
  12030. staged_full = true;
  12031. pthread_cond_wait(&gws_cond, stgd_lock);
  12032. ts = __total_staged(false);
  12033. }
  12034. mutex_unlock(stgd_lock);
  12035. if (ts > max_staged)
  12036. continue;
  12037. work = make_work();
  12038. if (lagging && !pool_tset(cp, &cp->lagging)) {
  12039. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  12040. cp->getfail_occasions++;
  12041. total_go++;
  12042. }
  12043. pool = select_pool(lagging, malgo);
  12044. retry:
  12045. if (pool->has_stratum) {
  12046. while (!pool->stratum_active || !pool->stratum_notify) {
  12047. struct pool *altpool = select_pool(true, malgo);
  12048. if (altpool == pool && pool->has_stratum)
  12049. cgsleep_ms(5000);
  12050. pool = altpool;
  12051. goto retry;
  12052. }
  12053. gen_stratum_work(pool, work);
  12054. applog(LOG_DEBUG, "Generated stratum work");
  12055. stage_work(work);
  12056. continue;
  12057. }
  12058. if (pool->last_work_copy) {
  12059. mutex_lock(&pool->last_work_lock);
  12060. struct work *last_work = pool->last_work_copy;
  12061. if (!last_work)
  12062. {}
  12063. else
  12064. if (can_roll(last_work) && should_roll(last_work)) {
  12065. struct timeval tv_now;
  12066. cgtime(&tv_now);
  12067. free_work(work);
  12068. work = make_clone(pool->last_work_copy);
  12069. mutex_unlock(&pool->last_work_lock);
  12070. roll_work(work);
  12071. applog(LOG_DEBUG, "Generated work from latest GBT job in get_work_thread with %d seconds left", (int)blkmk_time_left(work->tr->tmpl, tv_now.tv_sec));
  12072. stage_work(work);
  12073. continue;
  12074. } else if (last_work->tr && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tr->tmpl) > (unsigned long)mining_threads) {
  12075. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  12076. } else {
  12077. free_work(last_work);
  12078. pool->last_work_copy = NULL;
  12079. }
  12080. mutex_unlock(&pool->last_work_lock);
  12081. }
  12082. if (clone_available()) {
  12083. applog(LOG_DEBUG, "Cloned getwork work");
  12084. free_work(work);
  12085. continue;
  12086. }
  12087. if (opt_benchmark) {
  12088. get_benchmark_work(work, opt_benchmark_intense);
  12089. applog(LOG_DEBUG, "Generated benchmark work");
  12090. stage_work(work);
  12091. continue;
  12092. }
  12093. work->pool = pool;
  12094. ce = pop_curl_entry3(pool, 2);
  12095. /* obtain new work from bitcoin via JSON-RPC */
  12096. if (!get_upstream_work(work, ce->curl)) {
  12097. struct pool *next_pool;
  12098. /* Make sure the pool just hasn't stopped serving
  12099. * requests but is up as we'll keep hammering it */
  12100. push_curl_entry(ce, pool);
  12101. ++pool->seq_getfails;
  12102. pool_died(pool);
  12103. next_pool = select_pool(!opt_fail_only, malgo);
  12104. if (pool == next_pool) {
  12105. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  12106. cgsleep_ms(5000);
  12107. } else {
  12108. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  12109. pool = next_pool;
  12110. }
  12111. goto retry;
  12112. }
  12113. if (ts >= max_staged)
  12114. pool_tclear(pool, &pool->lagging);
  12115. if (pool_tclear(pool, &pool->idle))
  12116. pool_resus(pool);
  12117. applog(LOG_DEBUG, "Generated getwork work");
  12118. stage_work(work);
  12119. push_curl_entry(ce, pool);
  12120. }
  12121. return 0;
  12122. }