miner.c 356 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781
  1. /*
  2. * Copyright 2011-2014 Con Kolivas
  3. * Copyright 2011-2014 Luke Dashjr
  4. * Copyright 2014 Nate Woolls
  5. * Copyright 2012-2013 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. #include "version.h"
  91. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_NANOFURY) || defined(USE_X6500) || defined(USE_ZTEX)
  92. # define USE_FPGA
  93. #endif
  94. enum bfg_quit_summary {
  95. BQS_DEFAULT,
  96. BQS_NONE,
  97. BQS_DEVS,
  98. BQS_PROCS,
  99. BQS_DETAILED,
  100. };
  101. struct strategies strategies[] = {
  102. { "Failover" },
  103. { "Round Robin" },
  104. { "Rotate" },
  105. { "Load Balance" },
  106. { "Balance" },
  107. };
  108. static char packagename[256];
  109. bool opt_protocol;
  110. bool opt_dev_protocol;
  111. static bool opt_benchmark, opt_benchmark_intense;
  112. static bool want_longpoll = true;
  113. static bool want_gbt = true;
  114. static bool want_getwork = true;
  115. #if BLKMAKER_VERSION > 1
  116. static bool opt_load_bitcoin_conf = true;
  117. static uint32_t coinbase_script_block_id;
  118. static uint32_t template_nonce;
  119. #endif
  120. #if BLKMAKER_VERSION > 0
  121. char *opt_coinbase_sig;
  122. #endif
  123. static enum bfg_quit_summary opt_quit_summary = BQS_DEFAULT;
  124. static bool include_serial_in_statline;
  125. char *request_target_str;
  126. float request_pdiff = 1.0;
  127. double request_bdiff;
  128. static bool want_stratum = true;
  129. int opt_skip_checks;
  130. bool want_per_device_stats;
  131. bool use_syslog;
  132. bool opt_quiet_work_updates = true;
  133. bool opt_quiet;
  134. bool opt_realquiet;
  135. int loginput_size;
  136. bool opt_compact;
  137. bool opt_show_procs;
  138. const int opt_cutofftemp = 95;
  139. int opt_hysteresis = 3;
  140. static int opt_retries = -1;
  141. int opt_fail_pause = 5;
  142. int opt_log_interval = 20;
  143. int opt_queue = 1;
  144. int opt_scantime = 60;
  145. int opt_expiry = 120;
  146. int opt_expiry_lp = 3600;
  147. unsigned long long global_hashrate;
  148. static bool opt_unittest = false;
  149. unsigned unittest_failures;
  150. unsigned long global_quota_gcd = 1;
  151. time_t last_getwork;
  152. #ifdef USE_OPENCL
  153. int opt_dynamic_interval = 7;
  154. int nDevs;
  155. int opt_g_threads = -1;
  156. #endif
  157. #ifdef USE_SCRYPT
  158. static char detect_algo = 1;
  159. #else
  160. static char detect_algo;
  161. #endif
  162. bool opt_restart = true;
  163. #ifdef USE_LIBMICROHTTPD
  164. #include "httpsrv.h"
  165. int httpsrv_port = -1;
  166. #endif
  167. #ifdef USE_LIBEVENT
  168. int stratumsrv_port = -1;
  169. #endif
  170. const
  171. int rescan_delay_ms = 1000;
  172. #ifdef HAVE_BFG_HOTPLUG
  173. bool opt_hotplug = 1;
  174. const
  175. int hotplug_delay_ms = 100;
  176. #else
  177. const bool opt_hotplug;
  178. #endif
  179. struct string_elist *scan_devices;
  180. static struct string_elist *opt_set_device_list;
  181. bool opt_force_dev_init;
  182. static struct string_elist *opt_devices_enabled_list;
  183. static bool opt_display_devs;
  184. int total_devices;
  185. struct cgpu_info **devices;
  186. int total_devices_new;
  187. struct cgpu_info **devices_new;
  188. bool have_opencl;
  189. int opt_n_threads = -1;
  190. int mining_threads;
  191. int base_queue;
  192. int num_processors;
  193. #ifdef HAVE_CURSES
  194. bool use_curses = true;
  195. #else
  196. bool use_curses;
  197. #endif
  198. int last_logstatusline_len;
  199. #ifdef HAVE_LIBUSB
  200. bool have_libusb;
  201. #endif
  202. static bool opt_submit_stale = true;
  203. static float opt_shares;
  204. static int opt_submit_threads = 0x40;
  205. bool opt_fail_only;
  206. int opt_fail_switch_delay = 300;
  207. bool opt_autofan;
  208. bool opt_autoengine;
  209. bool opt_noadl;
  210. char *opt_api_allow = NULL;
  211. char *opt_api_groups;
  212. char *opt_api_description = PACKAGE_STRING;
  213. int opt_api_port = 4028;
  214. bool opt_api_listen;
  215. bool opt_api_mcast;
  216. char *opt_api_mcast_addr = API_MCAST_ADDR;
  217. char *opt_api_mcast_code = API_MCAST_CODE;
  218. char *opt_api_mcast_des = "";
  219. int opt_api_mcast_port = 4028;
  220. bool opt_api_network;
  221. bool opt_delaynet;
  222. bool opt_disable_pool;
  223. bool opt_disable_client_reconnect = false;
  224. static bool no_work;
  225. bool opt_worktime;
  226. bool opt_weighed_stats;
  227. char *opt_kernel_path;
  228. char *cgminer_path;
  229. #if defined(USE_BITFORCE)
  230. bool opt_bfl_noncerange;
  231. #endif
  232. #define QUIET (opt_quiet || opt_realquiet)
  233. struct thr_info *control_thr;
  234. struct thr_info **mining_thr;
  235. static int watchpool_thr_id;
  236. static int watchdog_thr_id;
  237. #ifdef HAVE_CURSES
  238. static int input_thr_id;
  239. #endif
  240. int gpur_thr_id;
  241. static int api_thr_id;
  242. static int total_control_threads;
  243. pthread_mutex_t hash_lock;
  244. static pthread_mutex_t *stgd_lock;
  245. pthread_mutex_t console_lock;
  246. cglock_t ch_lock;
  247. static pthread_rwlock_t blk_lock;
  248. static pthread_mutex_t sshare_lock;
  249. pthread_rwlock_t netacc_lock;
  250. pthread_rwlock_t mining_thr_lock;
  251. pthread_rwlock_t devices_lock;
  252. static pthread_mutex_t lp_lock;
  253. static pthread_cond_t lp_cond;
  254. pthread_cond_t gws_cond;
  255. bool shutting_down;
  256. double total_rolling;
  257. double total_mhashes_done;
  258. static struct timeval total_tv_start, total_tv_end;
  259. static struct timeval miner_started;
  260. cglock_t control_lock;
  261. pthread_mutex_t stats_lock;
  262. static pthread_mutex_t submitting_lock;
  263. static int total_submitting;
  264. static struct work *submit_waiting;
  265. notifier_t submit_waiting_notifier;
  266. int hw_errors;
  267. int total_accepted, total_rejected;
  268. int total_getworks, total_stale, total_discarded;
  269. uint64_t total_bytes_rcvd, total_bytes_sent;
  270. double total_diff1, total_bad_diff1;
  271. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  272. static int staged_rollable, staged_spare;
  273. unsigned int new_blocks;
  274. unsigned int found_blocks;
  275. unsigned int local_work;
  276. unsigned int total_go, total_ro;
  277. struct pool **pools;
  278. static struct pool *currentpool = NULL;
  279. int total_pools, enabled_pools;
  280. enum pool_strategy pool_strategy = POOL_FAILOVER;
  281. int opt_rotate_period;
  282. static int total_urls, total_users, total_passes;
  283. static
  284. #ifndef HAVE_CURSES
  285. const
  286. #endif
  287. bool curses_active;
  288. #ifdef HAVE_CURSES
  289. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  290. const
  291. #endif
  292. short default_bgcolor = COLOR_BLACK;
  293. static int attr_title = A_BOLD;
  294. #endif
  295. static
  296. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  297. bool use_unicode;
  298. static
  299. bool have_unicode_degrees;
  300. static
  301. wchar_t unicode_micro = 'u';
  302. #else
  303. const bool use_unicode;
  304. static
  305. const bool have_unicode_degrees;
  306. #ifdef HAVE_CURSES
  307. static
  308. const char unicode_micro = 'u';
  309. #endif
  310. #endif
  311. #ifdef HAVE_CURSES
  312. #define U8_BAD_START "\xef\x80\x81"
  313. #define U8_BAD_END "\xef\x80\x80"
  314. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  315. /* logstart is where the log window should start */
  316. static int devcursor, logstart, logcursor;
  317. bool selecting_device;
  318. unsigned selected_device;
  319. #endif
  320. static int max_lpdigits;
  321. // current_hash was replaced with goal->current_goal_detail
  322. // current_block_id was replaced with blkchain->currentblk->block_id
  323. static char datestamp[40];
  324. static char best_share[ALLOC_H2B_SHORTV] = "0";
  325. double best_diff = 0;
  326. struct mining_algorithm *mining_algorithms;
  327. struct mining_goal_info *mining_goals;
  328. int active_goals = 1;
  329. int swork_id;
  330. /* For creating a hash database of stratum shares submitted that have not had
  331. * a response yet */
  332. struct stratum_share {
  333. UT_hash_handle hh;
  334. bool block;
  335. struct work *work;
  336. int id;
  337. };
  338. static struct stratum_share *stratum_shares = NULL;
  339. char *opt_socks_proxy = NULL;
  340. static const char def_conf[] = "bfgminer.conf";
  341. static bool config_loaded;
  342. static int include_count;
  343. #define JSON_INCLUDE_CONF "include"
  344. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  345. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  346. #define JSON_MAX_DEPTH 10
  347. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  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_STR(mining_goals, 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. }
  1071. /* Pool variant of test and set */
  1072. static bool pool_tset(struct pool *pool, bool *var)
  1073. {
  1074. bool ret;
  1075. mutex_lock(&pool->pool_lock);
  1076. ret = *var;
  1077. *var = true;
  1078. mutex_unlock(&pool->pool_lock);
  1079. return ret;
  1080. }
  1081. bool pool_tclear(struct pool *pool, bool *var)
  1082. {
  1083. bool ret;
  1084. mutex_lock(&pool->pool_lock);
  1085. ret = *var;
  1086. *var = false;
  1087. mutex_unlock(&pool->pool_lock);
  1088. return ret;
  1089. }
  1090. struct pool *current_pool(void)
  1091. {
  1092. struct pool *pool;
  1093. cg_rlock(&control_lock);
  1094. pool = currentpool;
  1095. cg_runlock(&control_lock);
  1096. return pool;
  1097. }
  1098. #if defined(USE_CPUMINING) && !defined(USE_SHA256D)
  1099. static
  1100. char *arg_ignored(const char * const arg)
  1101. {
  1102. return NULL;
  1103. }
  1104. #endif
  1105. static
  1106. char *set_bool_ignore_arg(const char * const arg, bool * const b)
  1107. {
  1108. return opt_set_bool(b);
  1109. }
  1110. char *set_int_range(const char *arg, int *i, int min, int max)
  1111. {
  1112. char *err = opt_set_intval(arg, i);
  1113. if (err)
  1114. return err;
  1115. if (*i < min || *i > max)
  1116. return "Value out of range";
  1117. return NULL;
  1118. }
  1119. static char *set_int_0_to_9999(const char *arg, int *i)
  1120. {
  1121. return set_int_range(arg, i, 0, 9999);
  1122. }
  1123. static char *set_int_1_to_65535(const char *arg, int *i)
  1124. {
  1125. return set_int_range(arg, i, 1, 65535);
  1126. }
  1127. static char *set_int_0_to_10(const char *arg, int *i)
  1128. {
  1129. return set_int_range(arg, i, 0, 10);
  1130. }
  1131. static char *set_int_1_to_10(const char *arg, int *i)
  1132. {
  1133. return set_int_range(arg, i, 1, 10);
  1134. }
  1135. char *set_strdup(const char *arg, char **p)
  1136. {
  1137. *p = strdup((char *)arg);
  1138. return NULL;
  1139. }
  1140. #if BLKMAKER_VERSION > 1
  1141. static
  1142. char *set_b58addr(const char * const arg, bytes_t * const b)
  1143. {
  1144. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  1145. if (!scriptsz)
  1146. return "Invalid address";
  1147. char *script = malloc(scriptsz);
  1148. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  1149. free(script);
  1150. return "Failed to convert address to script";
  1151. }
  1152. bytes_assimilate_raw(b, script, scriptsz, scriptsz);
  1153. return NULL;
  1154. }
  1155. static char *set_generate_addr2(struct mining_goal_info *, const char *);
  1156. static
  1157. char *set_generate_addr(char *arg)
  1158. {
  1159. char * const colon = strchr(arg, ':');
  1160. struct mining_goal_info *goal;
  1161. if (colon)
  1162. {
  1163. colon[0] = '\0';
  1164. goal = get_mining_goal(arg);
  1165. arg = &colon[1];
  1166. }
  1167. else
  1168. goal = get_mining_goal("default");
  1169. return set_generate_addr2(goal, arg);
  1170. }
  1171. static
  1172. char *set_generate_addr2(struct mining_goal_info * const goal, const char * const arg)
  1173. {
  1174. bytes_t newscript = BYTES_INIT;
  1175. char *estr = set_b58addr(arg, &newscript);
  1176. if (estr)
  1177. {
  1178. bytes_free(&newscript);
  1179. return estr;
  1180. }
  1181. if (!goal->generation_script)
  1182. {
  1183. goal->generation_script = malloc(sizeof(*goal->generation_script));
  1184. bytes_init(goal->generation_script);
  1185. }
  1186. bytes_assimilate(goal->generation_script, &newscript);
  1187. bytes_free(&newscript);
  1188. return NULL;
  1189. }
  1190. #endif
  1191. static
  1192. char *set_quit_summary(const char * const arg)
  1193. {
  1194. if (!(strcasecmp(arg, "none") && strcasecmp(arg, "no")))
  1195. opt_quit_summary = BQS_NONE;
  1196. else
  1197. if (!(strcasecmp(arg, "devs") && strcasecmp(arg, "devices")))
  1198. opt_quit_summary = BQS_DEVS;
  1199. else
  1200. if (!(strcasecmp(arg, "procs") && strcasecmp(arg, "processors") && strcasecmp(arg, "chips") && strcasecmp(arg, "cores")))
  1201. opt_quit_summary = BQS_PROCS;
  1202. else
  1203. if (!(strcasecmp(arg, "detailed") && strcasecmp(arg, "detail") && strcasecmp(arg, "all")))
  1204. opt_quit_summary = BQS_DETAILED;
  1205. else
  1206. return "Quit summary must be one of none/devs/procs/detailed";
  1207. return NULL;
  1208. }
  1209. static void pdiff_target_leadzero(void *, double);
  1210. char *set_request_diff(const char *arg, float *p)
  1211. {
  1212. unsigned char target[32];
  1213. char *e = opt_set_floatval(arg, p);
  1214. if (e)
  1215. return e;
  1216. request_bdiff = (double)*p * 0.9999847412109375;
  1217. pdiff_target_leadzero(target, *p);
  1218. request_target_str = malloc(65);
  1219. bin2hex(request_target_str, target, 32);
  1220. return NULL;
  1221. }
  1222. #ifdef NEED_BFG_LOWL_VCOM
  1223. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1224. #ifdef WIN32
  1225. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1226. {
  1227. char dev[PATH_MAX];
  1228. char *devp = dev;
  1229. size_t bufLen = 0x100;
  1230. tryagain: ;
  1231. char buf[bufLen];
  1232. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1233. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1234. bufLen *= 2;
  1235. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1236. goto tryagain;
  1237. }
  1238. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1239. }
  1240. size_t tLen;
  1241. memcpy(devp, "\\\\.\\", 4);
  1242. devp = &devp[4];
  1243. for (char *t = buf; *t; t += tLen) {
  1244. tLen = strlen(t) + 1;
  1245. if (strncmp("COM", t, 3))
  1246. continue;
  1247. memcpy(devp, t, tLen);
  1248. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1249. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1250. }
  1251. }
  1252. #else
  1253. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1254. {
  1255. char dev[PATH_MAX];
  1256. char *devp = dev;
  1257. DIR *D;
  1258. struct dirent *de;
  1259. const char devdir[] = "/dev";
  1260. const size_t devdirlen = sizeof(devdir) - 1;
  1261. char *devpath = devp;
  1262. char *devfile = devpath + devdirlen + 1;
  1263. D = opendir(devdir);
  1264. if (!D)
  1265. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1266. memcpy(devpath, devdir, devdirlen);
  1267. devpath[devdirlen] = '/';
  1268. while ( (de = readdir(D)) ) {
  1269. if (!strncmp(de->d_name, "cu.", 3)
  1270. //don't probe Bluetooth devices - causes bus errors and segfaults
  1271. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1272. goto trydev;
  1273. if (strncmp(de->d_name, "tty", 3))
  1274. continue;
  1275. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1276. continue;
  1277. trydev:
  1278. strcpy(devfile, de->d_name);
  1279. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1280. }
  1281. closedir(D);
  1282. }
  1283. #endif
  1284. #endif
  1285. static char *add_serial(const char *arg)
  1286. {
  1287. string_elist_add(arg, &scan_devices);
  1288. return NULL;
  1289. }
  1290. static
  1291. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1292. {
  1293. string_elist_add(arg, elist);
  1294. return NULL;
  1295. }
  1296. bool get_intrange(const char *arg, int *val1, int *val2)
  1297. {
  1298. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1299. char *p, *p2;
  1300. *val1 = strtol(arg, &p, 0);
  1301. if (arg == p)
  1302. // Zero-length ending number, invalid
  1303. return false;
  1304. while (true)
  1305. {
  1306. if (!p[0])
  1307. {
  1308. *val2 = *val1;
  1309. return true;
  1310. }
  1311. if (p[0] == '-')
  1312. break;
  1313. if (!isspace(p[0]))
  1314. // Garbage, invalid
  1315. return false;
  1316. ++p;
  1317. }
  1318. p2 = &p[1];
  1319. *val2 = strtol(p2, &p, 0);
  1320. if (p2 == p)
  1321. // Zero-length ending number, invalid
  1322. return false;
  1323. while (true)
  1324. {
  1325. if (!p[0])
  1326. return true;
  1327. if (!isspace(p[0]))
  1328. // Garbage, invalid
  1329. return false;
  1330. ++p;
  1331. }
  1332. }
  1333. static
  1334. void _test_intrange(const char *s, const int v[2])
  1335. {
  1336. int a[2];
  1337. if (!get_intrange(s, &a[0], &a[1]))
  1338. {
  1339. ++unittest_failures;
  1340. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1341. }
  1342. for (int i = 0; i < 2; ++i)
  1343. if (unlikely(a[i] != v[i]))
  1344. {
  1345. ++unittest_failures;
  1346. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1347. }
  1348. }
  1349. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1350. static
  1351. void _test_intrange_fail(const char *s)
  1352. {
  1353. int a[2];
  1354. if (get_intrange(s, &a[0], &a[1]))
  1355. {
  1356. ++unittest_failures;
  1357. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1358. }
  1359. }
  1360. static
  1361. void test_intrange()
  1362. {
  1363. _test_intrange("-1--2", -1, -2);
  1364. _test_intrange("-1-2", -1, 2);
  1365. _test_intrange("1--2", 1, -2);
  1366. _test_intrange("1-2", 1, 2);
  1367. _test_intrange("111-222", 111, 222);
  1368. _test_intrange(" 11 - 22 ", 11, 22);
  1369. _test_intrange("+11-+22", 11, 22);
  1370. _test_intrange("-1", -1, -1);
  1371. _test_intrange_fail("all");
  1372. _test_intrange_fail("1-");
  1373. _test_intrange_fail("");
  1374. _test_intrange_fail("1-54x");
  1375. }
  1376. static char *set_devices(char *arg)
  1377. {
  1378. if (*arg) {
  1379. if (*arg == '?') {
  1380. opt_display_devs = true;
  1381. return NULL;
  1382. }
  1383. } else
  1384. return "Invalid device parameters";
  1385. string_elist_add(arg, &opt_devices_enabled_list);
  1386. return NULL;
  1387. }
  1388. static char *set_balance(enum pool_strategy *strategy)
  1389. {
  1390. *strategy = POOL_BALANCE;
  1391. return NULL;
  1392. }
  1393. static char *set_loadbalance(enum pool_strategy *strategy)
  1394. {
  1395. *strategy = POOL_LOADBALANCE;
  1396. return NULL;
  1397. }
  1398. static char *set_rotate(const char *arg, int *i)
  1399. {
  1400. pool_strategy = POOL_ROTATE;
  1401. return set_int_range(arg, i, 0, 9999);
  1402. }
  1403. static char *set_rr(enum pool_strategy *strategy)
  1404. {
  1405. *strategy = POOL_ROUNDROBIN;
  1406. return NULL;
  1407. }
  1408. static
  1409. char *set_benchmark_intense()
  1410. {
  1411. opt_benchmark = true;
  1412. opt_benchmark_intense = true;
  1413. return NULL;
  1414. }
  1415. /* Detect that url is for a stratum protocol either via the presence of
  1416. * stratum+tcp or by detecting a stratum server response */
  1417. bool detect_stratum(struct pool *pool, char *url)
  1418. {
  1419. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1420. return false;
  1421. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1422. pool_set_uri(pool, strdup(url));
  1423. pool->has_stratum = true;
  1424. pool->stratum_url = pool->sockaddr_url;
  1425. return true;
  1426. }
  1427. return false;
  1428. }
  1429. static struct pool *add_url(void)
  1430. {
  1431. total_urls++;
  1432. if (total_urls > total_pools)
  1433. add_pool();
  1434. return pools[total_urls - 1];
  1435. }
  1436. static void setup_url(struct pool *pool, char *arg)
  1437. {
  1438. if (detect_stratum(pool, arg))
  1439. return;
  1440. opt_set_charp(arg, &pool->rpc_url);
  1441. if (strncmp(arg, "http://", 7) &&
  1442. strncmp(arg, "https://", 8)) {
  1443. const size_t L = strlen(arg);
  1444. char *httpinput;
  1445. httpinput = malloc(8 + L);
  1446. if (!httpinput)
  1447. quit(1, "Failed to malloc httpinput");
  1448. sprintf(httpinput, "http://%s", arg);
  1449. pool_set_uri(pool, httpinput);
  1450. }
  1451. }
  1452. static char *set_url(char *arg)
  1453. {
  1454. struct pool *pool = add_url();
  1455. setup_url(pool, arg);
  1456. return NULL;
  1457. }
  1458. static char *set_quota(char *arg)
  1459. {
  1460. char *semicolon = strchr(arg, ';'), *url;
  1461. int len, qlen, quota;
  1462. struct pool *pool;
  1463. if (!semicolon)
  1464. return "No semicolon separated quota;URL pair found";
  1465. len = strlen(arg);
  1466. *semicolon = '\0';
  1467. qlen = strlen(arg);
  1468. if (!qlen)
  1469. return "No parameter for quota found";
  1470. len -= qlen + 1;
  1471. if (len < 1)
  1472. return "No parameter for URL found";
  1473. quota = atoi(arg);
  1474. if (quota < 0)
  1475. return "Invalid negative parameter for quota set";
  1476. url = arg + qlen + 1;
  1477. pool = add_url();
  1478. setup_url(pool, url);
  1479. pool->quota = quota;
  1480. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1481. adjust_quota_gcd();
  1482. return NULL;
  1483. }
  1484. static char *set_user(const char *arg)
  1485. {
  1486. struct pool *pool;
  1487. total_users++;
  1488. if (total_users > total_pools)
  1489. add_pool();
  1490. pool = pools[total_users - 1];
  1491. opt_set_charp(arg, &pool->rpc_user);
  1492. return NULL;
  1493. }
  1494. static char *set_pass(const char *arg)
  1495. {
  1496. struct pool *pool;
  1497. total_passes++;
  1498. if (total_passes > total_pools)
  1499. add_pool();
  1500. pool = pools[total_passes - 1];
  1501. opt_set_charp(arg, &pool->rpc_pass);
  1502. return NULL;
  1503. }
  1504. static char *set_userpass(const char *arg)
  1505. {
  1506. struct pool *pool;
  1507. char *updup;
  1508. if (total_users != total_passes)
  1509. return "User + pass options must be balanced before userpass";
  1510. ++total_users;
  1511. ++total_passes;
  1512. if (total_users > total_pools)
  1513. add_pool();
  1514. pool = pools[total_users - 1];
  1515. updup = strdup(arg);
  1516. opt_set_charp(arg, &pool->rpc_userpass);
  1517. pool->rpc_user = updup;
  1518. pool->rpc_pass = strchr(updup, ':');
  1519. if (pool->rpc_pass)
  1520. pool->rpc_pass++[0] = '\0';
  1521. else
  1522. pool->rpc_pass = &updup[strlen(updup)];
  1523. return NULL;
  1524. }
  1525. static char *set_cbcaddr(char *arg)
  1526. {
  1527. struct pool *pool;
  1528. char *p, *addr;
  1529. bytes_t target_script = BYTES_INIT;
  1530. if (!total_pools)
  1531. return "Define pool first, then the --coinbase-check-addr list";
  1532. pool = pools[total_pools - 1];
  1533. /* NOTE: 'x' is a new prefix which leads both mainnet and testnet address, we would
  1534. * need support it later, but now leave the code just so.
  1535. *
  1536. * Regarding details of address prefix 'x', check the below URL:
  1537. * https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Serialization_format
  1538. */
  1539. pool->cb_param.testnet = (arg[0] != '1' && arg[0] != '3' && arg[0] != 'x');
  1540. for (; (addr = strtok_r(arg, ",", &p)); arg = NULL)
  1541. {
  1542. struct bytes_hashtbl *ah;
  1543. if (set_b58addr(addr, &target_script))
  1544. /* No bother to free memory since we are going to exit anyway */
  1545. return "Invalid address in --coinbase-check-address list";
  1546. HASH_FIND(hh, pool->cb_param.scripts, bytes_buf(&target_script), bytes_len(&target_script), ah);
  1547. if (!ah)
  1548. {
  1549. /* Note: for the below allocated memory we have good way to release its memory
  1550. * since we can't be sure there are no reference to the pool struct when remove_pool()
  1551. * get called.
  1552. *
  1553. * We just hope the remove_pool() would not be called many many times during
  1554. * the whole running life of this program.
  1555. */
  1556. ah = malloc(sizeof(*ah));
  1557. bytes_init(&ah->b);
  1558. bytes_assimilate(&ah->b, &target_script);
  1559. HASH_ADD(hh, pool->cb_param.scripts, b.buf, bytes_len(&ah->b), ah);
  1560. }
  1561. }
  1562. bytes_free(&target_script);
  1563. return NULL;
  1564. }
  1565. static char *set_cbctotal(const char *arg)
  1566. {
  1567. struct pool *pool;
  1568. if (!total_pools)
  1569. return "Define pool first, then the --coinbase-check-total argument";
  1570. pool = pools[total_pools - 1];
  1571. pool->cb_param.total = atoll(arg);
  1572. if (pool->cb_param.total < 0)
  1573. return "The total payout amount in coinbase should be greater than 0";
  1574. return NULL;
  1575. }
  1576. static char *set_cbcperc(const char *arg)
  1577. {
  1578. struct pool *pool;
  1579. if (!total_pools)
  1580. return "Define pool first, then the --coinbase-check-percent argument";
  1581. pool = pools[total_pools - 1];
  1582. if (!pool->cb_param.scripts)
  1583. return "Define --coinbase-check-addr list first, then the --coinbase-check-total argument";
  1584. pool->cb_param.perc = atof(arg) / 100;
  1585. if (pool->cb_param.perc < 0.0 || pool->cb_param.perc > 1.0)
  1586. return "The percentage should be between 0 and 100";
  1587. return NULL;
  1588. }
  1589. static
  1590. 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)
  1591. {
  1592. *out_success = SDR_ERR;
  1593. if (!(strcasecmp(optname, "malgo") && strcasecmp(optname, "algo")))
  1594. {
  1595. if (!newvalue)
  1596. return "Goal option 'malgo' requires a value (eg, SHA256d)";
  1597. struct mining_algorithm * const new_malgo = mining_algorithm_by_alias(newvalue);
  1598. if (!new_malgo)
  1599. return "Unrecognised mining algorithm";
  1600. goal_set_malgo(goal, new_malgo);
  1601. goto success;
  1602. }
  1603. #if BLKMAKER_VERSION > 1
  1604. 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))
  1605. {
  1606. if (!newvalue)
  1607. return "Missing value for 'generate-to' goal option";
  1608. const char * const emsg = set_generate_addr2(goal, newvalue);
  1609. if (emsg)
  1610. return emsg;
  1611. goto success;
  1612. }
  1613. #endif
  1614. *out_success = SDR_UNKNOWN;
  1615. return "Unknown goal option";
  1616. success:
  1617. *out_success = SDR_OK;
  1618. return NULL;
  1619. }
  1620. // May leak replybuf if returning an error
  1621. static
  1622. const char *set_goal_params(struct mining_goal_info * const goal, char *arg)
  1623. {
  1624. bytes_t replybuf = BYTES_INIT;
  1625. for (char *param, *nextptr; (param = strtok_r(arg, ",", &nextptr)); arg = NULL)
  1626. {
  1627. char *val = strchr(param, '=');
  1628. if (val)
  1629. val++[0] = '\0';
  1630. enum bfg_set_device_replytype success;
  1631. const char * const emsg = goal_set(goal, param, val, &replybuf, &success);
  1632. if (success != SDR_OK)
  1633. return emsg ?: "Error setting goal param";
  1634. }
  1635. bytes_free(&replybuf);
  1636. return NULL;
  1637. }
  1638. static
  1639. const char *set_pool_goal(const char * const arg)
  1640. {
  1641. struct pool *pool;
  1642. if (!total_pools)
  1643. return "Usage of --pool-goal before pools are defined does not make sense";
  1644. pool = pools[total_pools - 1];
  1645. char *param = strchr(arg, ':');
  1646. if (param)
  1647. param++[0] = '\0';
  1648. pool->goal = get_mining_goal(arg);
  1649. if (param)
  1650. return set_goal_params(pool->goal, param);
  1651. return NULL;
  1652. }
  1653. static char *set_pool_priority(const char *arg)
  1654. {
  1655. struct pool *pool;
  1656. if (!total_pools)
  1657. return "Usage of --pool-priority before pools are defined does not make sense";
  1658. pool = pools[total_pools - 1];
  1659. opt_set_intval(arg, &pool->prio);
  1660. return NULL;
  1661. }
  1662. static char *set_pool_proxy(const char *arg)
  1663. {
  1664. struct pool *pool;
  1665. if (!total_pools)
  1666. return "Usage of --pool-proxy before pools are defined does not make sense";
  1667. if (!our_curl_supports_proxy_uris())
  1668. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1669. pool = pools[total_pools - 1];
  1670. opt_set_charp(arg, &pool->rpc_proxy);
  1671. return NULL;
  1672. }
  1673. static char *set_pool_force_rollntime(const char *arg)
  1674. {
  1675. struct pool *pool;
  1676. if (!total_pools)
  1677. return "Usage of --force-rollntime before pools are defined does not make sense";
  1678. pool = pools[total_pools - 1];
  1679. opt_set_intval(arg, &pool->force_rollntime);
  1680. return NULL;
  1681. }
  1682. static char *enable_debug(bool *flag)
  1683. {
  1684. *flag = true;
  1685. opt_debug_console = true;
  1686. /* Turn on verbose output, too. */
  1687. opt_log_output = true;
  1688. return NULL;
  1689. }
  1690. static char *set_schedtime(const char *arg, struct schedtime *st)
  1691. {
  1692. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1693. {
  1694. if (strcasecmp(arg, "now"))
  1695. return "Invalid time set, should be HH:MM";
  1696. } else
  1697. schedstop.tm.tm_sec = 0;
  1698. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1699. return "Invalid time set.";
  1700. st->enable = true;
  1701. return NULL;
  1702. }
  1703. static
  1704. char *set_log_file(char *arg)
  1705. {
  1706. char *r = "";
  1707. long int i = strtol(arg, &r, 10);
  1708. int fd, stderr_fd = fileno(stderr);
  1709. if ((!*r) && i >= 0 && i <= INT_MAX)
  1710. fd = i;
  1711. else
  1712. if (!strcmp(arg, "-"))
  1713. {
  1714. fd = fileno(stdout);
  1715. if (unlikely(fd == -1))
  1716. return "Standard output missing for log-file";
  1717. }
  1718. else
  1719. {
  1720. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1721. if (unlikely(fd == -1))
  1722. return "Failed to open log-file";
  1723. }
  1724. close(stderr_fd);
  1725. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1726. return "Failed to dup2 for log-file";
  1727. close(fd);
  1728. return NULL;
  1729. }
  1730. static
  1731. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1732. {
  1733. char *r = "";
  1734. long int i = strtol(arg, &r, 10);
  1735. static char *err = NULL;
  1736. const size_t errbufsz = 0x100;
  1737. free(err);
  1738. err = NULL;
  1739. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1740. *F = fdopen((int)i, mode);
  1741. if (!*F)
  1742. {
  1743. err = malloc(errbufsz);
  1744. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1745. (int)i, purpose);
  1746. return err;
  1747. }
  1748. } else if (!strcmp(arg, "-")) {
  1749. *F = (mode[0] == 'a') ? stdout : stdin;
  1750. if (!*F)
  1751. {
  1752. err = malloc(errbufsz);
  1753. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1754. (mode[0] == 'a') ? "out" : "in", purpose);
  1755. return err;
  1756. }
  1757. } else {
  1758. *F = fopen(arg, mode);
  1759. if (!*F)
  1760. {
  1761. err = malloc(errbufsz);
  1762. snprintf(err, errbufsz, "Failed to open %s for %s",
  1763. arg, purpose);
  1764. return err;
  1765. }
  1766. }
  1767. return NULL;
  1768. }
  1769. static char *set_noncelog(char *arg)
  1770. {
  1771. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1772. }
  1773. static char *set_sharelog(char *arg)
  1774. {
  1775. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1776. }
  1777. static
  1778. void _add_set_device_option(const char * const func, const char * const buf)
  1779. {
  1780. applog(LOG_DEBUG, "%s: Using --set-device %s", func, buf);
  1781. string_elist_add(buf, &opt_set_device_list);
  1782. }
  1783. #define add_set_device_option(...) do{ \
  1784. char _tmp1718[0x100]; \
  1785. snprintf(_tmp1718, sizeof(_tmp1718), __VA_ARGS__); \
  1786. _add_set_device_option(__func__, _tmp1718); \
  1787. }while(0)
  1788. char *set_temp_cutoff(char *arg)
  1789. {
  1790. if (strchr(arg, ','))
  1791. return "temp-cutoff no longer supports comma-delimited syntax, use --set-device for better control";
  1792. applog(LOG_WARNING, "temp-cutoff is deprecated! Use --set-device for better control");
  1793. add_set_device_option("all:temp-cutoff=%s", arg);
  1794. return NULL;
  1795. }
  1796. char *set_temp_target(char *arg)
  1797. {
  1798. if (strchr(arg, ','))
  1799. return "temp-target no longer supports comma-delimited syntax, use --set-device for better control";
  1800. applog(LOG_WARNING, "temp-target is deprecated! Use --set-device for better control");
  1801. add_set_device_option("all:temp-target=%s", arg);
  1802. return NULL;
  1803. }
  1804. #ifdef USE_OPENCL
  1805. static
  1806. char *set_no_opencl_binaries(__maybe_unused void * const dummy)
  1807. {
  1808. applog(LOG_WARNING, "The --no-opencl-binaries option is deprecated! Use --set-device OCL:binary=no");
  1809. add_set_device_option("OCL:binary=no");
  1810. return NULL;
  1811. }
  1812. #endif
  1813. static
  1814. char *disable_pool_redirect(__maybe_unused void * const dummy)
  1815. {
  1816. opt_disable_client_reconnect = true;
  1817. want_stratum = false;
  1818. return NULL;
  1819. }
  1820. static char *set_api_allow(const char *arg)
  1821. {
  1822. opt_set_charp(arg, &opt_api_allow);
  1823. return NULL;
  1824. }
  1825. static char *set_api_groups(const char *arg)
  1826. {
  1827. opt_set_charp(arg, &opt_api_groups);
  1828. return NULL;
  1829. }
  1830. static char *set_api_description(const char *arg)
  1831. {
  1832. opt_set_charp(arg, &opt_api_description);
  1833. return NULL;
  1834. }
  1835. static char *set_api_mcast_des(const char *arg)
  1836. {
  1837. opt_set_charp(arg, &opt_api_mcast_des);
  1838. return NULL;
  1839. }
  1840. #ifdef USE_ICARUS
  1841. extern const struct bfg_set_device_definition icarus_set_device_funcs[];
  1842. static char *set_icarus_options(const char *arg)
  1843. {
  1844. if (strchr(arg, ','))
  1845. return "icarus-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1846. applog(LOG_WARNING, "icarus-options is deprecated! See README.FPGA for better control");
  1847. char *opts = strdup(arg), *argdup;
  1848. argdup = opts;
  1849. const struct bfg_set_device_definition *sdf = icarus_set_device_funcs;
  1850. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1851. char *saveptr, *opt;
  1852. for (int i = 0; i < 4; ++i, ++sdf)
  1853. {
  1854. opt = strtok_r(opts, ":", &saveptr);
  1855. opts = NULL;
  1856. if (!opt)
  1857. break;
  1858. if (!opt[0])
  1859. continue;
  1860. for (int j = 0; j < 4; ++j)
  1861. add_set_device_option("%s:%s=%s", drivers[j], sdf->optname, opt);
  1862. }
  1863. free(argdup);
  1864. return NULL;
  1865. }
  1866. static char *set_icarus_timing(const char *arg)
  1867. {
  1868. if (strchr(arg, ','))
  1869. return "icarus-timing no longer supports comma-delimited syntax, see README.FPGA for better control";
  1870. applog(LOG_WARNING, "icarus-timing is deprecated! See README.FPGA for better control");
  1871. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1872. for (int j = 0; j < 4; ++j)
  1873. add_set_device_option("%s:timing=%s", drivers[j], arg);
  1874. return NULL;
  1875. }
  1876. #endif
  1877. #ifdef USE_AVALON
  1878. extern const struct bfg_set_device_definition avalon_set_device_funcs[];
  1879. static char *set_avalon_options(const char *arg)
  1880. {
  1881. if (strchr(arg, ','))
  1882. return "avalon-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1883. applog(LOG_WARNING, "avalon-options is deprecated! See README.FPGA for better control");
  1884. char *opts = strdup(arg), *argdup;
  1885. argdup = opts;
  1886. const struct bfg_set_device_definition *sdf = avalon_set_device_funcs;
  1887. char *saveptr, *opt;
  1888. for (int i = 0; i < 5; ++i, ++sdf)
  1889. {
  1890. opt = strtok_r(opts, ":", &saveptr);
  1891. opts = NULL;
  1892. if (!opt)
  1893. break;
  1894. if (!opt[0])
  1895. continue;
  1896. add_set_device_option("avalon:%s=%s", sdf->optname, opt);
  1897. }
  1898. free(argdup);
  1899. return NULL;
  1900. }
  1901. #endif
  1902. #ifdef USE_KLONDIKE
  1903. static char *set_klondike_options(const char *arg)
  1904. {
  1905. int hashclock;
  1906. double temptarget;
  1907. switch (sscanf(arg, "%d:%lf", &hashclock, &temptarget))
  1908. {
  1909. default:
  1910. return "Unrecognised --klondike-options";
  1911. case 2:
  1912. add_set_device_option("klondike:temp-target=%lf", temptarget);
  1913. // fallthru
  1914. case 1:
  1915. add_set_device_option("klondike:clock=%d", hashclock);
  1916. }
  1917. applog(LOG_WARNING, "klondike-options is deprecated! Use --set-device for better control");
  1918. return NULL;
  1919. }
  1920. #endif
  1921. __maybe_unused
  1922. static char *set_null(const char __maybe_unused *arg)
  1923. {
  1924. return NULL;
  1925. }
  1926. /* These options are available from config file or commandline */
  1927. static struct opt_table opt_config_table[] = {
  1928. #ifdef USE_CPUMINING
  1929. #ifdef USE_SHA256D
  1930. OPT_WITH_ARG("--algo",
  1931. set_algo, show_algo, &opt_algo,
  1932. "Specify sha256 implementation for CPU mining:\n"
  1933. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1934. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1935. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1936. #ifdef WANT_SSE2_4WAY
  1937. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1938. #endif
  1939. #ifdef WANT_VIA_PADLOCK
  1940. "\n\tvia\t\tVIA padlock implementation"
  1941. #endif
  1942. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1943. #ifdef WANT_CRYPTOPP_ASM32
  1944. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1945. #endif
  1946. #ifdef WANT_X8632_SSE2
  1947. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1948. #endif
  1949. #ifdef WANT_X8664_SSE2
  1950. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1951. #endif
  1952. #ifdef WANT_X8664_SSE4
  1953. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1954. #endif
  1955. #ifdef WANT_ALTIVEC_4WAY
  1956. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1957. #endif
  1958. ),
  1959. OPT_WITH_ARG("-a",
  1960. set_algo, show_algo, &opt_algo,
  1961. opt_hidden),
  1962. #else
  1963. // NOTE: Silently ignoring option, since it is plausable a non-SHA256d miner was using it just to skip benchmarking
  1964. OPT_WITH_ARG("--algo|-a", arg_ignored, NULL, NULL, opt_hidden),
  1965. #endif /* USE_SHA256D */
  1966. #endif /* USE_CPUMINING */
  1967. OPT_WITH_ARG("--api-allow",
  1968. set_api_allow, NULL, NULL,
  1969. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1970. OPT_WITH_ARG("--api-description",
  1971. set_api_description, NULL, NULL,
  1972. "Description placed in the API status header, default: BFGMiner version"),
  1973. OPT_WITH_ARG("--api-groups",
  1974. set_api_groups, NULL, NULL,
  1975. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1976. OPT_WITHOUT_ARG("--api-listen",
  1977. opt_set_bool, &opt_api_listen,
  1978. "Enable API, default: disabled"),
  1979. OPT_WITHOUT_ARG("--api-mcast",
  1980. opt_set_bool, &opt_api_mcast,
  1981. "Enable API Multicast listener, default: disabled"),
  1982. OPT_WITH_ARG("--api-mcast-addr",
  1983. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  1984. "API Multicast listen address"),
  1985. OPT_WITH_ARG("--api-mcast-code",
  1986. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  1987. "Code expected in the API Multicast message, don't use '-'"),
  1988. OPT_WITH_ARG("--api-mcast-des",
  1989. set_api_mcast_des, NULL, NULL,
  1990. "Description appended to the API Multicast reply, default: ''"),
  1991. OPT_WITH_ARG("--api-mcast-port",
  1992. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  1993. "API Multicast listen port"),
  1994. OPT_WITHOUT_ARG("--api-network",
  1995. opt_set_bool, &opt_api_network,
  1996. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1997. OPT_WITH_ARG("--api-port",
  1998. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1999. "Port number of miner API"),
  2000. #ifdef HAVE_ADL
  2001. OPT_WITHOUT_ARG("--auto-fan",
  2002. opt_set_bool, &opt_autofan,
  2003. opt_hidden),
  2004. OPT_WITHOUT_ARG("--auto-gpu",
  2005. opt_set_bool, &opt_autoengine,
  2006. opt_hidden),
  2007. #endif
  2008. OPT_WITHOUT_ARG("--balance",
  2009. set_balance, &pool_strategy,
  2010. "Change multipool strategy from failover to even share balance"),
  2011. OPT_WITHOUT_ARG("--benchmark",
  2012. opt_set_bool, &opt_benchmark,
  2013. "Run BFGMiner in benchmark mode - produces no shares"),
  2014. OPT_WITHOUT_ARG("--benchmark-intense",
  2015. set_benchmark_intense, &opt_benchmark_intense,
  2016. "Run BFGMiner in intensive benchmark mode - produces no shares"),
  2017. #if defined(USE_BITFORCE)
  2018. OPT_WITHOUT_ARG("--bfl-range",
  2019. opt_set_bool, &opt_bfl_noncerange,
  2020. "Use nonce range on bitforce devices if supported"),
  2021. #endif
  2022. #ifdef HAVE_CHROOT
  2023. OPT_WITH_ARG("--chroot-dir",
  2024. opt_set_charp, NULL, &chroot_dir,
  2025. "Chroot to a directory right after startup"),
  2026. #endif
  2027. OPT_WITH_ARG("--cmd-idle",
  2028. opt_set_charp, NULL, &cmd_idle,
  2029. "Execute a command when a device is allowed to be idle (rest or wait)"),
  2030. OPT_WITH_ARG("--cmd-sick",
  2031. opt_set_charp, NULL, &cmd_sick,
  2032. "Execute a command when a device is declared sick"),
  2033. OPT_WITH_ARG("--cmd-dead",
  2034. opt_set_charp, NULL, &cmd_dead,
  2035. "Execute a command when a device is declared dead"),
  2036. #if BLKMAKER_VERSION > 0
  2037. OPT_WITH_ARG("--coinbase-sig",
  2038. set_strdup, NULL, &opt_coinbase_sig,
  2039. "Set coinbase signature when possible"),
  2040. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  2041. set_strdup, NULL, &opt_coinbase_sig,
  2042. opt_hidden),
  2043. #endif
  2044. #ifdef HAVE_CURSES
  2045. OPT_WITHOUT_ARG("--compact",
  2046. opt_set_bool, &opt_compact,
  2047. "Use compact display without per device statistics"),
  2048. #endif
  2049. #ifdef USE_CPUMINING
  2050. OPT_WITH_ARG("--cpu-threads",
  2051. force_nthreads_int, opt_show_intval, &opt_n_threads,
  2052. "Number of miner CPU threads"),
  2053. OPT_WITH_ARG("-t",
  2054. force_nthreads_int, opt_show_intval, &opt_n_threads,
  2055. opt_hidden),
  2056. #endif
  2057. OPT_WITHOUT_ARG("--debug|-D",
  2058. enable_debug, &opt_debug,
  2059. "Enable debug output"),
  2060. OPT_WITHOUT_ARG("--debuglog",
  2061. opt_set_bool, &opt_debug,
  2062. "Enable debug logging"),
  2063. OPT_WITHOUT_ARG("--device-protocol-dump",
  2064. opt_set_bool, &opt_dev_protocol,
  2065. "Verbose dump of device protocol-level activities"),
  2066. OPT_WITH_ARG("--device|-d",
  2067. set_devices, NULL, NULL,
  2068. "Enable only devices matching pattern (default: all)"),
  2069. OPT_WITHOUT_ARG("--disable-rejecting",
  2070. opt_set_bool, &opt_disable_pool,
  2071. "Automatically disable pools that continually reject shares"),
  2072. #ifdef USE_LIBMICROHTTPD
  2073. OPT_WITH_ARG("--http-port",
  2074. opt_set_intval, opt_show_intval, &httpsrv_port,
  2075. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  2076. #endif
  2077. OPT_WITH_ARG("--expiry",
  2078. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  2079. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  2080. OPT_WITH_ARG("-E",
  2081. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  2082. opt_hidden),
  2083. OPT_WITH_ARG("--expiry-lp",
  2084. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  2085. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  2086. OPT_WITHOUT_ARG("--failover-only",
  2087. opt_set_bool, &opt_fail_only,
  2088. "Don't leak work to backup pools when primary pool is lagging"),
  2089. OPT_WITH_ARG("--failover-switch-delay",
  2090. set_int_1_to_65535, opt_show_intval, &opt_fail_switch_delay,
  2091. "Delay in seconds before switching back to a failed pool"),
  2092. #ifdef USE_FPGA
  2093. OPT_WITHOUT_ARG("--force-dev-init",
  2094. opt_set_bool, &opt_force_dev_init,
  2095. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  2096. #endif
  2097. #if BLKMAKER_VERSION > 1
  2098. OPT_WITH_ARG("--generate-to",
  2099. set_generate_addr, NULL, NULL,
  2100. "Set an address to generate to for solo mining"),
  2101. 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",
  2102. set_generate_addr, NULL, NULL,
  2103. opt_hidden),
  2104. #endif
  2105. #ifdef USE_OPENCL
  2106. OPT_WITH_ARG("--gpu-dyninterval",
  2107. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  2108. opt_hidden),
  2109. OPT_WITH_ARG("--gpu-platform",
  2110. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  2111. "Select OpenCL platform ID to use for GPU mining"),
  2112. OPT_WITH_ARG("--gpu-threads|-g",
  2113. set_gpu_threads, opt_show_intval, &opt_g_threads,
  2114. opt_hidden),
  2115. #ifdef HAVE_ADL
  2116. OPT_WITH_ARG("--gpu-engine",
  2117. set_gpu_engine, NULL, NULL,
  2118. opt_hidden),
  2119. OPT_WITH_ARG("--gpu-fan",
  2120. set_gpu_fan, NULL, NULL,
  2121. opt_hidden),
  2122. OPT_WITH_ARG("--gpu-map",
  2123. set_gpu_map, NULL, NULL,
  2124. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  2125. OPT_WITH_ARG("--gpu-memclock",
  2126. set_gpu_memclock, NULL, NULL,
  2127. opt_hidden),
  2128. OPT_WITH_ARG("--gpu-memdiff",
  2129. set_gpu_memdiff, NULL, NULL,
  2130. opt_hidden),
  2131. OPT_WITH_ARG("--gpu-powertune",
  2132. set_gpu_powertune, NULL, NULL,
  2133. opt_hidden),
  2134. OPT_WITHOUT_ARG("--gpu-reorder",
  2135. opt_set_bool, &opt_reorder,
  2136. "Attempt to reorder GPU devices according to PCI Bus ID"),
  2137. OPT_WITH_ARG("--gpu-vddc",
  2138. set_gpu_vddc, NULL, NULL,
  2139. opt_hidden),
  2140. #endif
  2141. #ifdef USE_SCRYPT
  2142. OPT_WITH_ARG("--lookup-gap",
  2143. set_lookup_gap, NULL, NULL,
  2144. opt_hidden),
  2145. #endif
  2146. OPT_WITH_ARG("--intensity|-I",
  2147. set_intensity, NULL, NULL,
  2148. opt_hidden),
  2149. #endif
  2150. #if defined(USE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  2151. OPT_WITH_ARG("--kernel-path",
  2152. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2153. "Specify a path to where bitstream and kernel files are"),
  2154. OPT_WITH_ARG("-K",
  2155. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2156. opt_hidden),
  2157. #endif
  2158. #ifdef USE_OPENCL
  2159. OPT_WITH_ARG("--kernel|-k",
  2160. set_kernel, NULL, NULL,
  2161. opt_hidden),
  2162. #endif
  2163. #ifdef USE_ICARUS
  2164. OPT_WITH_ARG("--icarus-options",
  2165. set_icarus_options, NULL, NULL,
  2166. opt_hidden),
  2167. OPT_WITH_ARG("--icarus-timing",
  2168. set_icarus_timing, NULL, NULL,
  2169. opt_hidden),
  2170. #endif
  2171. #ifdef USE_AVALON
  2172. OPT_WITH_ARG("--avalon-options",
  2173. set_avalon_options, NULL, NULL,
  2174. opt_hidden),
  2175. #endif
  2176. #ifdef USE_KLONDIKE
  2177. OPT_WITH_ARG("--klondike-options",
  2178. set_klondike_options, NULL, NULL,
  2179. "Set klondike options clock:temptarget"),
  2180. #endif
  2181. OPT_WITHOUT_ARG("--load-balance",
  2182. set_loadbalance, &pool_strategy,
  2183. "Change multipool strategy from failover to quota based balance"),
  2184. OPT_WITH_ARG("--log|-l",
  2185. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  2186. "Interval in seconds between log output"),
  2187. OPT_WITH_ARG("--log-file|-L",
  2188. set_log_file, NULL, NULL,
  2189. "Append log file for output messages"),
  2190. OPT_WITH_ARG("--logfile",
  2191. set_log_file, NULL, NULL,
  2192. opt_hidden),
  2193. OPT_WITHOUT_ARG("--log-microseconds",
  2194. opt_set_bool, &opt_log_microseconds,
  2195. "Include microseconds in log output"),
  2196. #if defined(unix) || defined(__APPLE__)
  2197. OPT_WITH_ARG("--monitor|-m",
  2198. opt_set_charp, NULL, &opt_stderr_cmd,
  2199. "Use custom pipe cmd for output messages"),
  2200. #endif // defined(unix)
  2201. OPT_WITHOUT_ARG("--net-delay",
  2202. opt_set_bool, &opt_delaynet,
  2203. "Impose small delays in networking to avoid overloading slow routers"),
  2204. OPT_WITHOUT_ARG("--no-adl",
  2205. opt_set_bool, &opt_noadl,
  2206. #ifdef HAVE_ADL
  2207. "Disable the ATI display library used for monitoring and setting GPU parameters"
  2208. #else
  2209. opt_hidden
  2210. #endif
  2211. ),
  2212. OPT_WITHOUT_ARG("--no-gbt",
  2213. opt_set_invbool, &want_gbt,
  2214. "Disable getblocktemplate support"),
  2215. OPT_WITHOUT_ARG("--no-getwork",
  2216. opt_set_invbool, &want_getwork,
  2217. "Disable getwork support"),
  2218. OPT_WITHOUT_ARG("--no-hotplug",
  2219. #ifdef HAVE_BFG_HOTPLUG
  2220. opt_set_invbool, &opt_hotplug,
  2221. "Disable hotplug detection"
  2222. #else
  2223. set_null, &opt_hotplug,
  2224. opt_hidden
  2225. #endif
  2226. ),
  2227. OPT_WITHOUT_ARG("--no-local-bitcoin",
  2228. #if BLKMAKER_VERSION > 1
  2229. opt_set_invbool, &opt_load_bitcoin_conf,
  2230. "Disable adding pools for local bitcoin RPC servers"),
  2231. #else
  2232. set_null, NULL, opt_hidden),
  2233. #endif
  2234. OPT_WITHOUT_ARG("--no-longpoll",
  2235. opt_set_invbool, &want_longpoll,
  2236. "Disable X-Long-Polling support"),
  2237. OPT_WITHOUT_ARG("--no-pool-disable",
  2238. opt_set_invbool, &opt_disable_pool,
  2239. opt_hidden),
  2240. OPT_WITHOUT_ARG("--no-client-reconnect",
  2241. opt_set_invbool, &opt_disable_client_reconnect,
  2242. opt_hidden),
  2243. OPT_WITHOUT_ARG("--no-pool-redirect",
  2244. disable_pool_redirect, NULL,
  2245. "Ignore pool requests to redirect to another server"),
  2246. OPT_WITHOUT_ARG("--no-restart",
  2247. opt_set_invbool, &opt_restart,
  2248. "Do not attempt to restart devices that hang"
  2249. ),
  2250. OPT_WITHOUT_ARG("--no-show-processors",
  2251. opt_set_invbool, &opt_show_procs,
  2252. opt_hidden),
  2253. OPT_WITHOUT_ARG("--no-show-procs",
  2254. opt_set_invbool, &opt_show_procs,
  2255. opt_hidden),
  2256. OPT_WITHOUT_ARG("--no-stratum",
  2257. opt_set_invbool, &want_stratum,
  2258. "Disable Stratum detection"),
  2259. OPT_WITHOUT_ARG("--no-submit-stale",
  2260. opt_set_invbool, &opt_submit_stale,
  2261. "Don't submit shares if they are detected as stale"),
  2262. #ifdef USE_OPENCL
  2263. OPT_WITHOUT_ARG("--no-opencl-binaries",
  2264. set_no_opencl_binaries, NULL,
  2265. opt_hidden),
  2266. #endif
  2267. OPT_WITHOUT_ARG("--no-unicode",
  2268. #ifdef USE_UNICODE
  2269. opt_set_invbool, &use_unicode,
  2270. "Don't use Unicode characters in TUI"
  2271. #else
  2272. set_null, &use_unicode,
  2273. opt_hidden
  2274. #endif
  2275. ),
  2276. OPT_WITH_ARG("--noncelog",
  2277. set_noncelog, NULL, NULL,
  2278. "Create log of all nonces found"),
  2279. OPT_WITH_ARG("--pass|-p",
  2280. set_pass, NULL, NULL,
  2281. "Password for bitcoin JSON-RPC server"),
  2282. OPT_WITHOUT_ARG("--per-device-stats",
  2283. opt_set_bool, &want_per_device_stats,
  2284. "Force verbose mode and output per-device statistics"),
  2285. OPT_WITH_ARG("--userpass|-O",
  2286. set_userpass, NULL, NULL,
  2287. "Username:Password pair for bitcoin JSON-RPC server"),
  2288. OPT_WITH_ARG("--pool-goal",
  2289. set_pool_goal, NULL, NULL,
  2290. "Named goal for the previous-defined pool"),
  2291. OPT_WITH_ARG("--pool-priority",
  2292. set_pool_priority, NULL, NULL,
  2293. "Priority for just the previous-defined pool"),
  2294. OPT_WITH_ARG("--pool-proxy|-x",
  2295. set_pool_proxy, NULL, NULL,
  2296. "Proxy URI to use for connecting to just the previous-defined pool"),
  2297. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  2298. set_pool_force_rollntime, NULL, NULL,
  2299. opt_hidden),
  2300. OPT_WITHOUT_ARG("--protocol-dump|-P",
  2301. opt_set_bool, &opt_protocol,
  2302. "Verbose dump of protocol-level activities"),
  2303. OPT_WITH_ARG("--queue|-Q",
  2304. set_int_0_to_9999, opt_show_intval, &opt_queue,
  2305. "Minimum number of work items to have queued (0+)"),
  2306. OPT_WITHOUT_ARG("--quiet|-q",
  2307. opt_set_bool, &opt_quiet,
  2308. "Disable logging output, display status and errors"),
  2309. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  2310. opt_set_bool, &opt_quiet_work_updates,
  2311. opt_hidden),
  2312. OPT_WITH_ARG("--quit-summary",
  2313. set_quit_summary, NULL, NULL,
  2314. "Summary printed when you quit: none/devs/procs/detailed"),
  2315. OPT_WITH_ARG("--quota|-U",
  2316. set_quota, NULL, NULL,
  2317. "quota;URL combination for server with load-balance strategy quotas"),
  2318. OPT_WITHOUT_ARG("--real-quiet",
  2319. opt_set_bool, &opt_realquiet,
  2320. "Disable all output"),
  2321. OPT_WITH_ARG("--request-diff",
  2322. set_request_diff, opt_show_floatval, &request_pdiff,
  2323. "Request a specific difficulty from pools"),
  2324. OPT_WITH_ARG("--retries",
  2325. opt_set_intval, opt_show_intval, &opt_retries,
  2326. "Number of times to retry failed submissions before giving up (-1 means never)"),
  2327. OPT_WITH_ARG("--retry-pause",
  2328. set_null, NULL, NULL,
  2329. opt_hidden),
  2330. OPT_WITH_ARG("--rotate",
  2331. set_rotate, opt_show_intval, &opt_rotate_period,
  2332. "Change multipool strategy from failover to regularly rotate at N minutes"),
  2333. OPT_WITHOUT_ARG("--round-robin",
  2334. set_rr, &pool_strategy,
  2335. "Change multipool strategy from failover to round robin on failure"),
  2336. OPT_WITH_ARG("--scan|-S",
  2337. add_serial, NULL, NULL,
  2338. "Configure how to scan for mining devices"),
  2339. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  2340. add_serial, NULL, NULL,
  2341. opt_hidden),
  2342. OPT_WITH_ARG("--scan-time",
  2343. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2344. "Upper bound on time spent scanning current work, in seconds"),
  2345. OPT_WITH_ARG("-s",
  2346. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2347. opt_hidden),
  2348. OPT_WITH_ARG("--scantime",
  2349. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2350. opt_hidden),
  2351. OPT_WITH_ARG("--sched-start",
  2352. set_schedtime, NULL, &schedstart,
  2353. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  2354. OPT_WITH_ARG("--sched-stop",
  2355. set_schedtime, NULL, &schedstop,
  2356. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  2357. #ifdef USE_SCRYPT
  2358. OPT_WITHOUT_ARG("--scrypt",
  2359. set_malgo_scrypt, NULL,
  2360. "Use the scrypt algorithm for mining (non-bitcoin)"),
  2361. #endif
  2362. OPT_WITH_ARG("--set-device|--set",
  2363. opt_string_elist_add, NULL, &opt_set_device_list,
  2364. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  2365. #if defined(USE_SCRYPT) && defined(USE_OPENCL)
  2366. OPT_WITH_ARG("--shaders",
  2367. set_shaders, NULL, NULL,
  2368. opt_hidden),
  2369. #endif
  2370. #ifdef HAVE_PWD_H
  2371. OPT_WITH_ARG("--setuid",
  2372. opt_set_charp, NULL, &opt_setuid,
  2373. "Username of an unprivileged user to run as"),
  2374. #endif
  2375. OPT_WITH_ARG("--sharelog",
  2376. set_sharelog, NULL, NULL,
  2377. "Append share log to file"),
  2378. OPT_WITH_ARG("--shares",
  2379. opt_set_floatval, NULL, &opt_shares,
  2380. "Quit after mining 2^32 * N hashes worth of shares (default: unlimited)"),
  2381. OPT_WITHOUT_ARG("--show-processors",
  2382. opt_set_bool, &opt_show_procs,
  2383. "Show per processor statistics in summary"),
  2384. OPT_WITHOUT_ARG("--show-procs",
  2385. opt_set_bool, &opt_show_procs,
  2386. opt_hidden),
  2387. OPT_WITH_ARG("--skip-security-checks",
  2388. set_int_0_to_9999, NULL, &opt_skip_checks,
  2389. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  2390. OPT_WITH_ARG("--socks-proxy",
  2391. opt_set_charp, NULL, &opt_socks_proxy,
  2392. "Set socks proxy (host:port)"),
  2393. #ifdef USE_LIBEVENT
  2394. OPT_WITH_ARG("--stratum-port",
  2395. opt_set_intval, opt_show_intval, &stratumsrv_port,
  2396. "Port number to listen on for stratum miners (-1 means disabled)"),
  2397. #endif
  2398. OPT_WITHOUT_ARG("--submit-stale",
  2399. opt_set_bool, &opt_submit_stale,
  2400. opt_hidden),
  2401. OPT_WITH_ARG("--submit-threads",
  2402. opt_set_intval, opt_show_intval, &opt_submit_threads,
  2403. "Minimum number of concurrent share submissions (default: 64)"),
  2404. #ifdef HAVE_SYSLOG_H
  2405. OPT_WITHOUT_ARG("--syslog",
  2406. opt_set_bool, &use_syslog,
  2407. "Use system log for output messages (default: standard error)"),
  2408. #endif
  2409. OPT_WITH_ARG("--temp-cutoff",
  2410. set_temp_cutoff, NULL, &opt_cutofftemp,
  2411. opt_hidden),
  2412. OPT_WITH_ARG("--temp-hysteresis",
  2413. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2414. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2415. #ifdef HAVE_ADL
  2416. OPT_WITH_ARG("--temp-overheat",
  2417. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2418. opt_hidden),
  2419. #endif
  2420. OPT_WITH_ARG("--temp-target",
  2421. set_temp_target, NULL, NULL,
  2422. opt_hidden),
  2423. OPT_WITHOUT_ARG("--text-only|-T",
  2424. opt_set_invbool, &use_curses,
  2425. #ifdef HAVE_CURSES
  2426. "Disable ncurses formatted screen output"
  2427. #else
  2428. opt_hidden
  2429. #endif
  2430. ),
  2431. #if defined(USE_SCRYPT) && defined(USE_OPENCL)
  2432. OPT_WITH_ARG("--thread-concurrency",
  2433. set_thread_concurrency, NULL, NULL,
  2434. opt_hidden),
  2435. #endif
  2436. #ifdef USE_UNICODE
  2437. OPT_WITHOUT_ARG("--unicode",
  2438. opt_set_bool, &use_unicode,
  2439. "Use Unicode characters in TUI"),
  2440. #endif
  2441. OPT_WITH_ARG("--url|-o",
  2442. set_url, NULL, NULL,
  2443. "URL for bitcoin JSON-RPC server"),
  2444. OPT_WITH_ARG("--user|-u",
  2445. set_user, NULL, NULL,
  2446. "Username for bitcoin JSON-RPC server"),
  2447. #ifdef USE_OPENCL
  2448. OPT_WITH_ARG("--vectors|-v",
  2449. set_vector, NULL, NULL,
  2450. opt_hidden),
  2451. #endif
  2452. OPT_WITHOUT_ARG("--verbose",
  2453. opt_set_bool, &opt_log_output,
  2454. "Log verbose output to stderr as well as status output"),
  2455. OPT_WITHOUT_ARG("--verbose-work-updates|--verbose-work-update",
  2456. opt_set_invbool, &opt_quiet_work_updates,
  2457. opt_hidden),
  2458. OPT_WITHOUT_ARG("--weighed-stats",
  2459. opt_set_bool, &opt_weighed_stats,
  2460. "Display statistics weighed to difficulty 1"),
  2461. #ifdef USE_OPENCL
  2462. OPT_WITH_ARG("--worksize|-w",
  2463. set_worksize, NULL, NULL,
  2464. opt_hidden),
  2465. #endif
  2466. OPT_WITHOUT_ARG("--unittest",
  2467. opt_set_bool, &opt_unittest, opt_hidden),
  2468. OPT_WITH_ARG("--coinbase-check-addr",
  2469. set_cbcaddr, NULL, NULL,
  2470. "A list of address to check against in coinbase payout list received from the previous-defined pool, separated by ','"),
  2471. OPT_WITH_ARG("--cbcheck-addr|--cbc-addr|--cbcaddr",
  2472. set_cbcaddr, NULL, NULL,
  2473. opt_hidden),
  2474. OPT_WITH_ARG("--coinbase-check-total",
  2475. set_cbctotal, NULL, NULL,
  2476. "The least total payout amount expected in coinbase received from the previous-defined pool"),
  2477. OPT_WITH_ARG("--cbcheck-total|--cbc-total|--cbctotal",
  2478. set_cbctotal, NULL, NULL,
  2479. opt_hidden),
  2480. OPT_WITH_ARG("--coinbase-check-percent",
  2481. set_cbcperc, NULL, NULL,
  2482. "The least benefit percentage expected for the sum of addr(s) listed in --cbaddr argument for previous-defined pool"),
  2483. OPT_WITH_ARG("--cbcheck-percent|--cbc-percent|--cbcpercent|--cbcperc",
  2484. set_cbcperc, NULL, NULL,
  2485. opt_hidden),
  2486. OPT_WITHOUT_ARG("--worktime",
  2487. opt_set_bool, &opt_worktime,
  2488. "Display extra work time debug information"),
  2489. OPT_WITH_ARG("--pools",
  2490. opt_set_bool, NULL, NULL, opt_hidden),
  2491. OPT_ENDTABLE
  2492. };
  2493. static char *load_config(const char *arg, void __maybe_unused *unused);
  2494. static char *parse_config(json_t *config, bool fileconf, int * const fileconf_load_p)
  2495. {
  2496. static char err_buf[200];
  2497. struct opt_table *opt;
  2498. json_t *val;
  2499. if (fileconf && !*fileconf_load_p)
  2500. *fileconf_load_p = 1;
  2501. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2502. char *p, *name, *sp;
  2503. /* We don't handle subtables. */
  2504. assert(!(opt->type & OPT_SUBTABLE));
  2505. if (!opt->names)
  2506. continue;
  2507. /* Pull apart the option name(s). */
  2508. name = strdup(opt->names);
  2509. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2510. char *err = "Invalid value";
  2511. /* Ignore short options. */
  2512. if (p[1] != '-')
  2513. continue;
  2514. val = json_object_get(config, p+2);
  2515. if (!val)
  2516. continue;
  2517. if (opt->type & OPT_HASARG) {
  2518. if (json_is_string(val)) {
  2519. err = opt->cb_arg(json_string_value(val),
  2520. opt->u.arg);
  2521. } else if (json_is_number(val)) {
  2522. char buf[256], *p, *q;
  2523. snprintf(buf, 256, "%f", json_number_value(val));
  2524. if ( (p = strchr(buf, '.')) ) {
  2525. // Trim /\.0*$/ to work properly with integer-only arguments
  2526. q = p;
  2527. while (*(++q) == '0') {}
  2528. if (*q == '\0')
  2529. *p = '\0';
  2530. }
  2531. err = opt->cb_arg(buf, opt->u.arg);
  2532. } else if (json_is_array(val)) {
  2533. int n, size = json_array_size(val);
  2534. err = NULL;
  2535. for (n = 0; n < size && !err; n++) {
  2536. if (json_is_string(json_array_get(val, n)))
  2537. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2538. else if (json_is_object(json_array_get(val, n)))
  2539. err = parse_config(json_array_get(val, n), false, fileconf_load_p);
  2540. }
  2541. }
  2542. } else if (opt->type & OPT_NOARG) {
  2543. if (json_is_true(val))
  2544. err = opt->cb(opt->u.arg);
  2545. else if (json_is_boolean(val)) {
  2546. if (opt->cb == (void*)opt_set_bool)
  2547. err = opt_set_invbool(opt->u.arg);
  2548. else if (opt->cb == (void*)opt_set_invbool)
  2549. err = opt_set_bool(opt->u.arg);
  2550. }
  2551. }
  2552. if (err) {
  2553. /* Allow invalid values to be in configuration
  2554. * file, just skipping over them provided the
  2555. * JSON is still valid after that. */
  2556. if (fileconf) {
  2557. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2558. *fileconf_load_p = -1;
  2559. } else {
  2560. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2561. p, err);
  2562. return err_buf;
  2563. }
  2564. }
  2565. }
  2566. free(name);
  2567. }
  2568. val = json_object_get(config, JSON_INCLUDE_CONF);
  2569. if (val && json_is_string(val))
  2570. return load_config(json_string_value(val), NULL);
  2571. return NULL;
  2572. }
  2573. struct bfg_loaded_configfile *bfg_loaded_configfiles;
  2574. static char *load_config(const char *arg, void __maybe_unused *unused)
  2575. {
  2576. json_error_t err;
  2577. json_t *config;
  2578. char *json_error;
  2579. size_t siz;
  2580. struct bfg_loaded_configfile *cfginfo;
  2581. cfginfo = malloc(sizeof(*cfginfo));
  2582. *cfginfo = (struct bfg_loaded_configfile){
  2583. .filename = strdup(arg),
  2584. };
  2585. LL_APPEND(bfg_loaded_configfiles, cfginfo);
  2586. if (++include_count > JSON_MAX_DEPTH)
  2587. return JSON_MAX_DEPTH_ERR;
  2588. #if JANSSON_MAJOR_VERSION > 1
  2589. config = json_load_file(arg, 0, &err);
  2590. #else
  2591. config = json_load_file(arg, &err);
  2592. #endif
  2593. if (!json_is_object(config)) {
  2594. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2595. json_error = malloc(siz);
  2596. if (!json_error)
  2597. quit(1, "Malloc failure in json error");
  2598. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2599. return json_error;
  2600. }
  2601. config_loaded = true;
  2602. /* Parse the config now, so we can override it. That can keep pointers
  2603. * so don't free config object. */
  2604. return parse_config(config, true, &cfginfo->fileconf_load);
  2605. }
  2606. static
  2607. bool _load_default_configs(const char * const filepath, void * __maybe_unused userp)
  2608. {
  2609. bool * const found_defcfg_p = userp;
  2610. *found_defcfg_p = true;
  2611. load_config(filepath, NULL);
  2612. // Regardless of status of loading the config file, we should continue loading other defaults
  2613. return false;
  2614. }
  2615. static void load_default_config(void)
  2616. {
  2617. bool found_defcfg = false;
  2618. appdata_file_call("BFGMiner", def_conf, _load_default_configs, &found_defcfg);
  2619. if (!found_defcfg)
  2620. {
  2621. // No BFGMiner config, try Cgminer's...
  2622. appdata_file_call("cgminer", "cgminer.conf", _load_default_configs, &found_defcfg);
  2623. }
  2624. }
  2625. extern const char *opt_argv0;
  2626. static char *opt_verusage_and_exit(const char *extra)
  2627. {
  2628. puts(packagename);
  2629. printf(" Lowlevel:%s\n", BFG_LOWLLIST);
  2630. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2631. printf(" Algorithms:%s\n", BFG_ALGOLIST);
  2632. printf(" Options:%s\n", BFG_OPTLIST);
  2633. printf("%s", opt_usage(opt_argv0, extra));
  2634. fflush(stdout);
  2635. exit(0);
  2636. }
  2637. /* These options are parsed before anything else */
  2638. static struct opt_table opt_early_table[] = {
  2639. // Default config is loaded in command line order, like a regular config
  2640. OPT_EARLY_WITH_ARG("--config|-c|--default-config",
  2641. set_bool_ignore_arg, NULL, &config_loaded,
  2642. opt_hidden),
  2643. OPT_EARLY_WITHOUT_ARG("--no-config|--no-default-config",
  2644. opt_set_bool, &config_loaded,
  2645. "Inhibit loading default config file"),
  2646. OPT_ENDTABLE
  2647. };
  2648. /* These options are available from commandline only */
  2649. static struct opt_table opt_cmdline_table[] = {
  2650. OPT_WITH_ARG("--config|-c",
  2651. load_config, NULL, NULL,
  2652. "Load a JSON-format configuration file\n"
  2653. "See example.conf for an example configuration."),
  2654. OPT_EARLY_WITHOUT_ARG("--no-config",
  2655. opt_set_bool, &config_loaded,
  2656. opt_hidden),
  2657. OPT_EARLY_WITHOUT_ARG("--no-default-config",
  2658. opt_set_bool, &config_loaded,
  2659. "Inhibit loading default config file"),
  2660. OPT_WITHOUT_ARG("--default-config",
  2661. load_default_config, NULL,
  2662. "Always load the default config file"),
  2663. OPT_WITHOUT_ARG("--help|-h",
  2664. opt_verusage_and_exit, NULL,
  2665. "Print this message"),
  2666. #ifdef USE_OPENCL
  2667. OPT_WITHOUT_ARG("--ndevs|-n",
  2668. print_ndevs_and_exit, &nDevs,
  2669. opt_hidden),
  2670. #endif
  2671. OPT_WITHOUT_ARG("--version|-V",
  2672. opt_version_and_exit, packagename,
  2673. "Display version and exit"),
  2674. OPT_ENDTABLE
  2675. };
  2676. static bool jobj_binary(const json_t *obj, const char *key,
  2677. void *buf, size_t buflen, bool required)
  2678. {
  2679. const char *hexstr;
  2680. json_t *tmp;
  2681. tmp = json_object_get(obj, key);
  2682. if (unlikely(!tmp)) {
  2683. if (unlikely(required))
  2684. applog(LOG_ERR, "JSON key '%s' not found", key);
  2685. return false;
  2686. }
  2687. hexstr = json_string_value(tmp);
  2688. if (unlikely(!hexstr)) {
  2689. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2690. return false;
  2691. }
  2692. if (!hex2bin(buf, hexstr, buflen))
  2693. return false;
  2694. return true;
  2695. }
  2696. static void calc_midstate(struct work *work)
  2697. {
  2698. union {
  2699. unsigned char c[64];
  2700. uint32_t i[16];
  2701. } data;
  2702. swap32yes(&data.i[0], work->data, 16);
  2703. sha256_ctx ctx;
  2704. sha256_init(&ctx);
  2705. sha256_update(&ctx, data.c, 64);
  2706. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2707. swap32tole(work->midstate, work->midstate, 8);
  2708. }
  2709. static
  2710. struct bfg_tmpl_ref *tmpl_makeref(blktemplate_t * const tmpl)
  2711. {
  2712. struct bfg_tmpl_ref * const tr = malloc(sizeof(*tr));
  2713. *tr = (struct bfg_tmpl_ref){
  2714. .tmpl = tmpl,
  2715. .refcount = 1,
  2716. };
  2717. mutex_init(&tr->mutex);
  2718. return tr;
  2719. }
  2720. static
  2721. void tmpl_incref(struct bfg_tmpl_ref * const tr)
  2722. {
  2723. mutex_lock(&tr->mutex);
  2724. ++tr->refcount;
  2725. mutex_unlock(&tr->mutex);
  2726. }
  2727. void tmpl_decref(struct bfg_tmpl_ref * const tr)
  2728. {
  2729. mutex_lock(&tr->mutex);
  2730. bool free_tmpl = !--tr->refcount;
  2731. mutex_unlock(&tr->mutex);
  2732. if (free_tmpl)
  2733. {
  2734. blktmpl_free(tr->tmpl);
  2735. mutex_destroy(&tr->mutex);
  2736. free(tr);
  2737. }
  2738. }
  2739. static struct work *make_work(void)
  2740. {
  2741. struct work *work = calloc(1, sizeof(struct work));
  2742. if (unlikely(!work))
  2743. quit(1, "Failed to calloc work in make_work");
  2744. cg_wlock(&control_lock);
  2745. work->id = total_work++;
  2746. cg_wunlock(&control_lock);
  2747. return work;
  2748. }
  2749. /* This is the central place all work that is about to be retired should be
  2750. * cleaned to remove any dynamically allocated arrays within the struct */
  2751. void clean_work(struct work *work)
  2752. {
  2753. free(work->job_id);
  2754. bytes_free(&work->nonce2);
  2755. free(work->nonce1);
  2756. if (work->device_data_free_func)
  2757. work->device_data_free_func(work);
  2758. if (work->tr)
  2759. tmpl_decref(work->tr);
  2760. memset(work, 0, sizeof(struct work));
  2761. }
  2762. /* All dynamically allocated work structs should be freed here to not leak any
  2763. * ram from arrays allocated within the work struct */
  2764. void free_work(struct work *work)
  2765. {
  2766. clean_work(work);
  2767. free(work);
  2768. }
  2769. 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";
  2770. #define workpadding_bin bfg_workpadding_bin
  2771. static const size_t block_info_str_sz = 3 /* ... */ + 16 /* block hash segment */ + 1;
  2772. static
  2773. void block_info_str(char * const out, const struct block_info * const blkinfo)
  2774. {
  2775. unsigned char hash_swap[32];
  2776. swap256(hash_swap, blkinfo->prevblkhash);
  2777. swap32tole(hash_swap, hash_swap, 32 / 4);
  2778. memset(out, '.', 3);
  2779. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2780. if (blkinfo->height > 0 && blkinfo->height < 1000000)
  2781. {
  2782. bin2hex(&out[3], &hash_swap[0x1c], 4);
  2783. snprintf(&out[11], block_info_str_sz-11, " #%6u", blkinfo->height);
  2784. }
  2785. else
  2786. bin2hex(&out[3], &hash_swap[0x18], 8);
  2787. }
  2788. #ifdef HAVE_CURSES
  2789. static void update_block_display(void);
  2790. #endif
  2791. // Must only be called with ch_lock held!
  2792. static
  2793. void __update_block_title(struct mining_goal_info * const goal)
  2794. {
  2795. struct blockchain_info * const blkchain = goal->blkchain;
  2796. if (!goal->current_goal_detail)
  2797. goal->current_goal_detail = malloc(block_info_str_sz);
  2798. block_info_str(goal->current_goal_detail, blkchain->currentblk);
  2799. #ifdef HAVE_CURSES
  2800. update_block_display();
  2801. #endif
  2802. }
  2803. static struct block_info *block_exists(const struct blockchain_info *, const void *);
  2804. static
  2805. void have_block_height(struct mining_goal_info * const goal, const void * const prevblkhash, uint32_t blkheight)
  2806. {
  2807. struct blockchain_info * const blkchain = goal->blkchain;
  2808. struct block_info * const blkinfo = block_exists(blkchain, prevblkhash);
  2809. if ((!blkinfo) || blkinfo->height)
  2810. return;
  2811. uint32_t block_id = ((uint32_t*)prevblkhash)[0];
  2812. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2813. cg_wlock(&ch_lock);
  2814. blkinfo->height = blkheight;
  2815. if (blkinfo == blkchain->currentblk)
  2816. {
  2817. blkchain->currentblk_subsidy = 5000000000LL >> (blkheight / 210000);
  2818. __update_block_title(goal);
  2819. }
  2820. cg_wunlock(&ch_lock);
  2821. }
  2822. static
  2823. void pool_set_opaque(struct pool *pool, bool opaque)
  2824. {
  2825. if (pool->swork.opaque == opaque)
  2826. return;
  2827. pool->swork.opaque = opaque;
  2828. if (opaque)
  2829. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2830. pool->pool_no);
  2831. else
  2832. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2833. pool->pool_no);
  2834. }
  2835. bool pool_may_redirect_to(struct pool * const pool, const char * const uri)
  2836. {
  2837. if (uri_get_param_bool(pool->rpc_url, "redirect", false))
  2838. return true;
  2839. return match_domains(pool->rpc_url, strlen(pool->rpc_url), uri, strlen(uri));
  2840. }
  2841. void pool_check_coinbase(struct pool * const pool, const uint8_t * const cbtxn, const size_t cbtxnsz)
  2842. {
  2843. if (uri_get_param_bool(pool->rpc_url, "skipcbcheck", false))
  2844. {}
  2845. else
  2846. if (!check_coinbase(cbtxn, cbtxnsz, &pool->cb_param))
  2847. {
  2848. if (pool->enabled == POOL_ENABLED)
  2849. {
  2850. applog(LOG_ERR, "Pool %d misbehaving (%s), disabling!", pool->pool_no, "coinbase check");
  2851. disable_pool(pool, POOL_MISBEHAVING);
  2852. }
  2853. }
  2854. else
  2855. if (pool->enabled == POOL_MISBEHAVING)
  2856. {
  2857. applog(LOG_NOTICE, "Pool %d no longer misbehaving, re-enabling!", pool->pool_no);
  2858. enable_pool(pool);
  2859. }
  2860. }
  2861. 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)
  2862. {
  2863. const int offsets = max(ntime_roll, 60);
  2864. *nrl = (struct ntime_roll_limits){
  2865. .min = ntime_base,
  2866. .max = ntime_base + ntime_roll,
  2867. .tv_ref = *tvp_ref,
  2868. .minoff = -offsets,
  2869. .maxoff = offsets,
  2870. };
  2871. }
  2872. void work_set_simple_ntime_roll_limit(struct work * const work, const int ntime_roll, const struct timeval * const tvp_ref)
  2873. {
  2874. set_simple_ntime_roll_limit(&work->ntime_roll_limits, upk_u32be(work->data, 0x44), ntime_roll, tvp_ref);
  2875. }
  2876. int work_ntime_range(struct work * const work, const struct timeval * const tvp_earliest, const struct timeval * const tvp_latest, const int desired_roll)
  2877. {
  2878. const struct ntime_roll_limits * const nrl = &work->ntime_roll_limits;
  2879. const uint32_t ref_ntime = work_get_ntime(work);
  2880. const int earliest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_earliest);
  2881. const int latest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_latest);
  2882. // minimum ntime is the latest possible result (add a second to spare) adjusted for minimum offset (or fixed minimum ntime)
  2883. uint32_t min_ntime = max(nrl->min, ref_ntime + latest_elapsed+1 + nrl->minoff);
  2884. // maximum ntime is the earliest possible result adjusted for maximum offset (or fixed maximum ntime)
  2885. uint32_t max_ntime = min(nrl->max, ref_ntime + earliest_elapsed + nrl->maxoff);
  2886. if (max_ntime < min_ntime)
  2887. return -1;
  2888. if (max_ntime - min_ntime > desired_roll)
  2889. {
  2890. // Adjust min_ntime upward for accuracy, when possible
  2891. const int mid_elapsed = ((latest_elapsed - earliest_elapsed) / 2) + earliest_elapsed;
  2892. uint32_t ideal_ntime = ref_ntime + mid_elapsed;
  2893. if (ideal_ntime > min_ntime)
  2894. min_ntime = min(ideal_ntime, max_ntime - desired_roll);
  2895. }
  2896. work_set_ntime(work, min_ntime);
  2897. return max_ntime - min_ntime;
  2898. }
  2899. #if BLKMAKER_VERSION > 1
  2900. static
  2901. bool goal_has_at_least_one_getcbaddr(const struct mining_goal_info * const goal)
  2902. {
  2903. for (int i = 0; i < total_pools; ++i)
  2904. {
  2905. struct pool * const pool = pools[i];
  2906. if (uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2907. return true;
  2908. }
  2909. return false;
  2910. }
  2911. static
  2912. void refresh_bitcoind_address(struct mining_goal_info * const goal, const bool fresh)
  2913. {
  2914. struct blockchain_info * const blkchain = goal->blkchain;
  2915. if (!goal_has_at_least_one_getcbaddr(goal))
  2916. return;
  2917. char getcbaddr_req[60];
  2918. CURL *curl = NULL;
  2919. json_t *json, *j2;
  2920. const char *s, *s2;
  2921. bytes_t newscript = BYTES_INIT;
  2922. snprintf(getcbaddr_req, sizeof(getcbaddr_req), "{\"method\":\"get%saddress\",\"id\":0,\"params\":[\"BFGMiner\"]}", fresh ? "new" : "account");
  2923. for (int i = 0; i < total_pools; ++i)
  2924. {
  2925. struct pool * const pool = pools[i];
  2926. if (!uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2927. continue;
  2928. if (pool->goal != goal)
  2929. continue;
  2930. applog(LOG_DEBUG, "Refreshing coinbase address from pool %d", pool->pool_no);
  2931. if (!curl)
  2932. {
  2933. curl = curl_easy_init();
  2934. if (unlikely(!curl))
  2935. {
  2936. applogfail(LOG_ERR, "curl_easy_init");
  2937. break;
  2938. }
  2939. }
  2940. json = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, getcbaddr_req, false, false, NULL, pool, true);
  2941. if (unlikely((!json) || !json_is_null( (j2 = json_object_get(json, "error")) )))
  2942. {
  2943. const char *estrc;
  2944. char *estr = NULL;
  2945. if (!(json && j2))
  2946. estrc = NULL;
  2947. else
  2948. {
  2949. estrc = json_string_value(j2);
  2950. if (!estrc)
  2951. estrc = estr = json_dumps_ANY(j2, JSON_ENSURE_ASCII | JSON_SORT_KEYS);
  2952. }
  2953. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, estrc);
  2954. free(estr);
  2955. continue;
  2956. }
  2957. s = bfg_json_obj_string(json, "result", NULL);
  2958. if (unlikely(!s))
  2959. {
  2960. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, "(return value was not a String)");
  2961. continue;
  2962. }
  2963. s2 = set_b58addr(s, &newscript);
  2964. if (unlikely(s2))
  2965. {
  2966. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 's', pool->pool_no, s2);
  2967. continue;
  2968. }
  2969. if (goal->generation_script)
  2970. {
  2971. if (bytes_eq(&newscript, goal->generation_script))
  2972. {
  2973. applog(LOG_DEBUG, "Pool %d returned coinbase address already in use (%s)", pool->pool_no, s2);
  2974. break;
  2975. }
  2976. }
  2977. else
  2978. {
  2979. goal->generation_script = malloc(sizeof(*goal->generation_script));
  2980. bytes_init(goal->generation_script);
  2981. }
  2982. bytes_assimilate(goal->generation_script, &newscript);
  2983. coinbase_script_block_id = blkchain->currentblk->block_id;
  2984. applog(LOG_NOTICE, "Now using coinbase address %s, provided by pool %d", s, pool->pool_no);
  2985. break;
  2986. }
  2987. bytes_free(&newscript);
  2988. if (curl)
  2989. curl_easy_cleanup(curl);
  2990. }
  2991. #endif
  2992. #define GBT_XNONCESZ (sizeof(uint32_t))
  2993. #if BLKMAKER_VERSION > 4
  2994. #define blkmk_append_coinbase_safe(tmpl, append, appendsz) \
  2995. blkmk_append_coinbase_safe2(tmpl, append, appendsz, GBT_XNONCESZ, false)
  2996. #endif
  2997. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  2998. {
  2999. json_t *res_val = json_object_get(val, "result");
  3000. json_t *tmp_val;
  3001. bool ret = false;
  3002. struct timeval tv_now;
  3003. if (unlikely(detect_algo == 1)) {
  3004. json_t *tmp = json_object_get(res_val, "algorithm");
  3005. const char *v = tmp ? json_string_value(tmp) : "";
  3006. if (strncasecmp(v, "scrypt", 6))
  3007. detect_algo = 2;
  3008. }
  3009. timer_set_now(&tv_now);
  3010. if (work->tr)
  3011. {
  3012. blktemplate_t * const tmpl = work->tr->tmpl;
  3013. const char *err = blktmpl_add_jansson(tmpl, res_val, tv_now.tv_sec);
  3014. if (err) {
  3015. applog(LOG_ERR, "blktmpl error: %s", err);
  3016. return false;
  3017. }
  3018. work->rolltime = blkmk_time_left(tmpl, tv_now.tv_sec);
  3019. #if BLKMAKER_VERSION > 1
  3020. struct mining_goal_info * const goal = pool->goal;
  3021. const uint32_t tmpl_block_id = ((uint32_t*)tmpl->prevblk)[0];
  3022. if ((!tmpl->cbtxn) && coinbase_script_block_id != tmpl_block_id)
  3023. refresh_bitcoind_address(goal, false);
  3024. if (goal->generation_script)
  3025. {
  3026. bool newcb;
  3027. #if BLKMAKER_VERSION > 2
  3028. blkmk_init_generation2(tmpl, bytes_buf(goal->generation_script), bytes_len(goal->generation_script), &newcb);
  3029. #else
  3030. newcb = !tmpl->cbtxn;
  3031. blkmk_init_generation(tmpl, bytes_buf(goal->generation_script), bytes_len(goal->generation_script));
  3032. #endif
  3033. if (newcb)
  3034. {
  3035. ssize_t ae = blkmk_append_coinbase_safe(tmpl, &template_nonce, sizeof(template_nonce));
  3036. if (ae < (ssize_t)sizeof(template_nonce))
  3037. 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);
  3038. ++template_nonce;
  3039. }
  3040. }
  3041. #endif
  3042. #if BLKMAKER_VERSION > 0
  3043. {
  3044. ssize_t ae = blkmk_append_coinbase_safe(tmpl, opt_coinbase_sig, 101);
  3045. static bool appenderr = false;
  3046. if (ae <= 0) {
  3047. if (opt_coinbase_sig) {
  3048. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  3049. appenderr = true;
  3050. }
  3051. } else if (ae >= 3 || opt_coinbase_sig) {
  3052. const char *cbappend = opt_coinbase_sig;
  3053. const char full[] = PACKAGE " " VERSION;
  3054. char *need_free = NULL;
  3055. if (!cbappend) {
  3056. if ((size_t)ae >= sizeof(full) - 1)
  3057. cbappend = full;
  3058. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  3059. {
  3060. const char *pos = strchr(full, '-');
  3061. size_t sz = (pos - full);
  3062. if (pos && ae > sz)
  3063. {
  3064. cbappend = need_free = malloc(sz + 1);
  3065. memcpy(need_free, full, sz);
  3066. need_free[sz] = '\0';
  3067. }
  3068. else
  3069. cbappend = PACKAGE;
  3070. }
  3071. else
  3072. cbappend = "BFG";
  3073. }
  3074. size_t cbappendsz = strlen(cbappend);
  3075. static bool truncatewarning = false;
  3076. if (cbappendsz <= (size_t)ae) {
  3077. if (cbappendsz < (size_t)ae)
  3078. // If we have space, include the trailing \0
  3079. ++cbappendsz;
  3080. ae = cbappendsz;
  3081. truncatewarning = false;
  3082. } else {
  3083. char *tmp = malloc(ae + 1);
  3084. memcpy(tmp, opt_coinbase_sig, ae);
  3085. tmp[ae] = '\0';
  3086. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  3087. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  3088. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  3089. free(tmp);
  3090. truncatewarning = true;
  3091. }
  3092. ae = blkmk_append_coinbase_safe(tmpl, cbappend, ae);
  3093. free(need_free);
  3094. if (ae <= 0) {
  3095. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  3096. appenderr = true;
  3097. } else
  3098. appenderr = false;
  3099. }
  3100. }
  3101. #endif
  3102. if (blkmk_get_data(tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  3103. return false;
  3104. swap32yes(work->data, work->data, 80 / 4);
  3105. memcpy(&work->data[80], workpadding_bin, 48);
  3106. work->ntime_roll_limits = (struct ntime_roll_limits){
  3107. .min = tmpl->mintime,
  3108. .max = tmpl->maxtime,
  3109. .tv_ref = tv_now,
  3110. .minoff = tmpl->mintimeoff,
  3111. .maxoff = tmpl->maxtimeoff,
  3112. };
  3113. const struct blktmpl_longpoll_req *lp;
  3114. if ((lp = blktmpl_get_longpoll(tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  3115. free(pool->lp_id);
  3116. pool->lp_id = strdup(lp->id);
  3117. #if 0 /* This just doesn't work :( */
  3118. curl_socket_t sock = pool->lp_socket;
  3119. if (sock != CURL_SOCKET_BAD) {
  3120. pool->lp_socket = CURL_SOCKET_BAD;
  3121. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  3122. shutdown(sock, SHUT_RDWR);
  3123. }
  3124. #endif
  3125. }
  3126. }
  3127. else
  3128. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  3129. applog(LOG_ERR, "JSON inval data");
  3130. return false;
  3131. }
  3132. else
  3133. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  3134. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  3135. // Calculate it ourselves
  3136. applog(LOG_DEBUG, "Calculating midstate locally");
  3137. calc_midstate(work);
  3138. }
  3139. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  3140. applog(LOG_ERR, "JSON inval target");
  3141. return false;
  3142. }
  3143. if (work->tr)
  3144. {
  3145. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  3146. {
  3147. int p = (sizeof(work->target) - 1) - i;
  3148. unsigned char c = work->target[i];
  3149. work->target[i] = work->target[p];
  3150. work->target[p] = c;
  3151. }
  3152. }
  3153. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  3154. struct mining_goal_info * const goal = pool->goal;
  3155. uint32_t blkheight = json_number_value(tmp_val);
  3156. const void * const prevblkhash = &work->data[4];
  3157. have_block_height(goal, prevblkhash, blkheight);
  3158. }
  3159. memset(work->hash, 0, sizeof(work->hash));
  3160. work->tv_staged = tv_now;
  3161. #if BLKMAKER_VERSION > 4
  3162. if (work->tr)
  3163. {
  3164. blktemplate_t * const tmpl = work->tr->tmpl;
  3165. uint8_t buf[80];
  3166. int16_t expire;
  3167. uint8_t *cbtxn;
  3168. size_t cbtxnsz;
  3169. size_t cbextranonceoffset;
  3170. int branchcount;
  3171. libblkmaker_hash_t *branches;
  3172. if (blkmk_get_mdata(tmpl, buf, sizeof(buf), tv_now.tv_sec, &expire, &cbtxn, &cbtxnsz, &cbextranonceoffset, &branchcount, &branches, GBT_XNONCESZ, false))
  3173. {
  3174. struct stratum_work * const swork = &pool->swork;
  3175. const size_t branchdatasz = branchcount * 0x20;
  3176. pool_check_coinbase(pool, cbtxn, cbtxnsz);
  3177. cg_wlock(&pool->data_lock);
  3178. swork->tr = work->tr;
  3179. bytes_assimilate_raw(&swork->coinbase, cbtxn, cbtxnsz, cbtxnsz);
  3180. swork->nonce2_offset = cbextranonceoffset;
  3181. bytes_assimilate_raw(&swork->merkle_bin, branches, branchdatasz, branchdatasz);
  3182. swork->merkles = branchcount;
  3183. memcpy(swork->header1, &buf[0], 36);
  3184. swork->ntime = le32toh(*(uint32_t *)(&buf[68]));
  3185. swork->tv_received = tv_now;
  3186. memcpy(swork->diffbits, &buf[72], 4);
  3187. memcpy(swork->target, work->target, sizeof(swork->target));
  3188. free(swork->job_id);
  3189. swork->job_id = NULL;
  3190. swork->clean = true;
  3191. swork->work_restart_id = pool->work_restart_id;
  3192. // FIXME: Do something with expire
  3193. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  3194. pool->nonce2 = 0;
  3195. cg_wunlock(&pool->data_lock);
  3196. }
  3197. else
  3198. applog(LOG_DEBUG, "blkmk_get_mdata failed for pool %u", pool->pool_no);
  3199. }
  3200. #endif // BLKMAKER_VERSION > 4
  3201. pool_set_opaque(pool, !work->tr);
  3202. ret = true;
  3203. return ret;
  3204. }
  3205. /* Returns whether the pool supports local work generation or not. */
  3206. static bool pool_localgen(struct pool *pool)
  3207. {
  3208. return (pool->last_work_copy || pool->has_stratum);
  3209. }
  3210. int dev_from_id(int thr_id)
  3211. {
  3212. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  3213. return cgpu->device_id;
  3214. }
  3215. /* Create an exponentially decaying average over the opt_log_interval */
  3216. void decay_time(double *f, double fadd, double fsecs)
  3217. {
  3218. double ftotal, fprop;
  3219. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  3220. ftotal = 1.0 + fprop;
  3221. *f += (fadd * fprop);
  3222. *f /= ftotal;
  3223. }
  3224. static
  3225. int __total_staged(const bool include_spares)
  3226. {
  3227. int tot = HASH_COUNT(staged_work);
  3228. if (!include_spares)
  3229. tot -= staged_spare;
  3230. return tot;
  3231. }
  3232. static int total_staged(const bool include_spares)
  3233. {
  3234. int ret;
  3235. mutex_lock(stgd_lock);
  3236. ret = __total_staged(include_spares);
  3237. mutex_unlock(stgd_lock);
  3238. return ret;
  3239. }
  3240. #ifdef HAVE_CURSES
  3241. WINDOW *mainwin, *statuswin, *logwin;
  3242. #endif
  3243. double total_secs = 1.0;
  3244. #ifdef HAVE_CURSES
  3245. static char statusline[256];
  3246. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  3247. static int statusy;
  3248. static int devsummaryYOffset;
  3249. static int total_lines;
  3250. #endif
  3251. #ifdef USE_OPENCL
  3252. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  3253. #endif
  3254. struct cgpu_info *cpus;
  3255. bool _bfg_console_cancel_disabled;
  3256. int _bfg_console_prev_cancelstate;
  3257. #ifdef HAVE_CURSES
  3258. #define lock_curses() bfg_console_lock()
  3259. #define unlock_curses() bfg_console_unlock()
  3260. static bool curses_active_locked(void)
  3261. {
  3262. bool ret;
  3263. lock_curses();
  3264. ret = curses_active;
  3265. if (!ret)
  3266. unlock_curses();
  3267. return ret;
  3268. }
  3269. // Cancellable getch
  3270. int my_cancellable_getch(void)
  3271. {
  3272. // This only works because the macro only hits direct getch() calls
  3273. typedef int (*real_getch_t)(void);
  3274. const real_getch_t real_getch = __real_getch;
  3275. int type, rv;
  3276. bool sct;
  3277. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  3278. rv = real_getch();
  3279. if (sct)
  3280. pthread_setcanceltype(type, &type);
  3281. return rv;
  3282. }
  3283. #ifdef PDCURSES
  3284. static
  3285. int bfg_wresize(WINDOW *win, int lines, int columns)
  3286. {
  3287. int rv = wresize(win, lines, columns);
  3288. int x, y;
  3289. getyx(win, y, x);
  3290. if (unlikely(y >= lines || x >= columns))
  3291. {
  3292. if (y >= lines)
  3293. y = lines - 1;
  3294. if (x >= columns)
  3295. x = columns - 1;
  3296. wmove(win, y, x);
  3297. }
  3298. return rv;
  3299. }
  3300. #else
  3301. # define bfg_wresize wresize
  3302. #endif
  3303. #endif
  3304. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  3305. {
  3306. va_list ap;
  3307. size_t presz = strlen(buf);
  3308. va_start(ap, fmt);
  3309. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  3310. va_end(ap);
  3311. }
  3312. double stats_elapsed(struct cgminer_stats *stats)
  3313. {
  3314. struct timeval now;
  3315. double elapsed;
  3316. if (stats->start_tv.tv_sec == 0)
  3317. elapsed = total_secs;
  3318. else {
  3319. cgtime(&now);
  3320. elapsed = tdiff(&now, &stats->start_tv);
  3321. }
  3322. if (elapsed < 1.0)
  3323. elapsed = 1.0;
  3324. return elapsed;
  3325. }
  3326. bool drv_ready(struct cgpu_info *cgpu)
  3327. {
  3328. switch (cgpu->status) {
  3329. case LIFE_INIT:
  3330. case LIFE_DEAD2:
  3331. return false;
  3332. default:
  3333. return true;
  3334. }
  3335. }
  3336. double cgpu_utility(struct cgpu_info *cgpu)
  3337. {
  3338. double dev_runtime = cgpu_runtime(cgpu);
  3339. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  3340. }
  3341. #define suffix_string(val, buf, bufsiz, sigdigits) do{ \
  3342. _Static_assert(sigdigits == 0, "suffix_string only supported with sigdigits==0"); \
  3343. format_unit3(buf, bufsiz, FUP_DIFF, "", H2B_SHORTV, val, -1); \
  3344. }while(0)
  3345. static float
  3346. utility_to_hashrate(double utility)
  3347. {
  3348. return utility * 0x4444444;
  3349. }
  3350. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  3351. static const int _unitbase = 4;
  3352. static
  3353. void pick_unit(float hashrate, unsigned char *unit)
  3354. {
  3355. unsigned char i;
  3356. if (hashrate == 0 || !isfinite(hashrate))
  3357. {
  3358. if (*unit < _unitbase)
  3359. *unit = _unitbase;
  3360. return;
  3361. }
  3362. hashrate *= 1e12;
  3363. for (i = 0; i < *unit; ++i)
  3364. hashrate /= 1e3;
  3365. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  3366. while (hashrate >= 999.95)
  3367. {
  3368. hashrate /= 1e3;
  3369. if (likely(_unitchar[*unit] != '?'))
  3370. ++*unit;
  3371. }
  3372. }
  3373. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  3374. enum h2bs_fmt {
  3375. H2B_NOUNIT, // "xxx.x"
  3376. H2B_SHORT, // "xxx.xMH/s"
  3377. H2B_SPACED, // "xxx.x MH/s"
  3378. H2B_SHORTV, // Like H2B_SHORT, but omit space for base unit
  3379. };
  3380. enum bfu_floatprec {
  3381. FUP_INTEGER,
  3382. FUP_HASHES,
  3383. FUP_BTC,
  3384. FUP_DIFF,
  3385. };
  3386. static
  3387. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  3388. {
  3389. char *s = buf;
  3390. unsigned char prec, i, unit;
  3391. int rv = 0;
  3392. if (unitin == -1)
  3393. {
  3394. unit = 0;
  3395. hashrate_pick_unit(hashrate, &unit);
  3396. }
  3397. else
  3398. unit = unitin;
  3399. hashrate *= 1e12;
  3400. for (i = 0; i < unit; ++i)
  3401. hashrate /= 1000;
  3402. switch (fprec)
  3403. {
  3404. case FUP_HASHES:
  3405. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  3406. if (hashrate >= 99.995 || unit < 6)
  3407. prec = 1;
  3408. else
  3409. prec = 2;
  3410. _SNP("%5.*f", prec, hashrate);
  3411. break;
  3412. case FUP_INTEGER:
  3413. _SNP("%3d", (int)hashrate);
  3414. break;
  3415. case FUP_BTC:
  3416. if (hashrate >= 99.995)
  3417. prec = 0;
  3418. else
  3419. prec = 2;
  3420. _SNP("%5.*f", prec, hashrate);
  3421. break;
  3422. case FUP_DIFF:
  3423. if (unit > _unitbase)
  3424. _SNP("%.3g", hashrate);
  3425. else
  3426. _SNP("%u", (unsigned int)hashrate);
  3427. }
  3428. if (fmt != H2B_NOUNIT)
  3429. {
  3430. char uc[3] = {_unitchar[unit], '\0'};
  3431. switch (fmt) {
  3432. case H2B_SPACED:
  3433. _SNP(" ");
  3434. default:
  3435. break;
  3436. case H2B_SHORTV:
  3437. if (isspace(uc[0]))
  3438. uc[0] = '\0';
  3439. }
  3440. if (uc[0] == '\xb5')
  3441. // Convert to UTF-8
  3442. snprintf(uc, sizeof(uc), "%s", U8_MICRO);
  3443. _SNP("%s%s", uc, measurement);
  3444. }
  3445. return rv;
  3446. }
  3447. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  3448. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  3449. static
  3450. 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)
  3451. {
  3452. unsigned char unit = 0;
  3453. bool allzero = true;
  3454. int i;
  3455. size_t delimsz = 0;
  3456. char *buf = buflist[0];
  3457. size_t bufsz = bufszlist[0];
  3458. size_t itemwidth = (floatprec ? 5 : 3);
  3459. if (!isarray)
  3460. delimsz = strlen(delim);
  3461. for (i = 0; i < count; ++i)
  3462. if (numbers[i] != 0)
  3463. {
  3464. pick_unit(numbers[i], &unit);
  3465. allzero = false;
  3466. }
  3467. if (allzero)
  3468. unit = _unitbase;
  3469. --count;
  3470. for (i = 0; i < count; ++i)
  3471. {
  3472. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  3473. if (isarray)
  3474. {
  3475. buf = buflist[i + 1];
  3476. bufsz = bufszlist[i + 1];
  3477. }
  3478. else
  3479. {
  3480. buf += itemwidth;
  3481. bufsz -= itemwidth;
  3482. if (delimsz > bufsz)
  3483. delimsz = bufsz;
  3484. memcpy(buf, delim, delimsz);
  3485. buf += delimsz;
  3486. bufsz -= delimsz;
  3487. }
  3488. }
  3489. // Last entry has the unit
  3490. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  3491. return buflist[0];
  3492. }
  3493. #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)
  3494. #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)
  3495. static
  3496. int percentf3(char * const buf, size_t sz, double p, const double t)
  3497. {
  3498. char *s = buf;
  3499. int rv = 0;
  3500. if (!p)
  3501. _SNP("none");
  3502. else
  3503. if (t <= p)
  3504. _SNP("100%%");
  3505. else
  3506. {
  3507. p /= t;
  3508. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  3509. _SNP(".%02.0f%%", p * 10000); // ".01%"
  3510. else
  3511. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  3512. _SNP("%.1f%%", p * 100); // "9.1%"
  3513. else
  3514. _SNP("%3.0f%%", p * 100); // " 99%"
  3515. }
  3516. return rv;
  3517. }
  3518. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  3519. static
  3520. void test_decimal_width()
  3521. {
  3522. // The pipe character at end of each line should perfectly line up
  3523. char printbuf[512];
  3524. char testbuf1[64];
  3525. char testbuf2[64];
  3526. char testbuf3[64];
  3527. char testbuf4[64];
  3528. double testn;
  3529. int width;
  3530. int saved;
  3531. // Hotspots around 0.1 and 0.01
  3532. saved = -1;
  3533. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  3534. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  3535. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  3536. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  3537. if (unlikely((saved != -1) && (width != saved))) {
  3538. ++unittest_failures;
  3539. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  3540. applog(LOG_ERR, "%s", printbuf);
  3541. }
  3542. saved = width;
  3543. }
  3544. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  3545. saved = -1;
  3546. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  3547. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3548. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3549. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3550. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  3551. width = utf8_strlen(printbuf);
  3552. if (unlikely((saved != -1) && (width != saved))) {
  3553. ++unittest_failures;
  3554. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  3555. applog(LOG_ERR, "%s", printbuf);
  3556. }
  3557. saved = width;
  3558. }
  3559. // Hotspot around unit transition boundary in pick_unit
  3560. saved = -1;
  3561. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  3562. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3563. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3564. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3565. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  3566. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  3567. width = utf8_strlen(printbuf);
  3568. if (unlikely((saved != -1) && (width != saved))) {
  3569. ++unittest_failures;
  3570. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  3571. applog(LOG_ERR, "%s", printbuf);
  3572. }
  3573. saved = width;
  3574. }
  3575. }
  3576. #ifdef HAVE_CURSES
  3577. static void adj_width(int var, int *length);
  3578. #endif
  3579. #ifdef HAVE_CURSES
  3580. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  3581. static
  3582. 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)
  3583. {
  3584. char rejpcbuf[6];
  3585. char bnbuf[6];
  3586. adj_width(accepted, &awidth);
  3587. adj_width(rejected, &rwidth);
  3588. adj_width(stale, &swidth);
  3589. adj_width(hwerrs, &hwwidth);
  3590. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3591. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  3592. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  3593. cHr, aHr, uHr,
  3594. awidth, accepted,
  3595. rwidth, rejected,
  3596. swidth, stale,
  3597. rejpcbuf,
  3598. hwwidth, hwerrs,
  3599. bnbuf
  3600. );
  3601. }
  3602. static
  3603. const char *pool_proto_str(const struct pool * const pool)
  3604. {
  3605. if (pool->idle)
  3606. return "Dead ";
  3607. if (pool->has_stratum)
  3608. return "Strtm";
  3609. if (pool->lp_url && pool->proto != pool->lp_proto)
  3610. return "Mixed";
  3611. switch (pool->proto)
  3612. {
  3613. case PLP_GETBLOCKTEMPLATE:
  3614. return " GBT ";
  3615. case PLP_GETWORK:
  3616. return "GWork";
  3617. default:
  3618. return "Alive";
  3619. }
  3620. }
  3621. #endif
  3622. static inline
  3623. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  3624. {
  3625. if (!(use_unicode && have_unicode_degrees))
  3626. maybe_unicode = false;
  3627. if (temp && *temp > 0.)
  3628. if (maybe_unicode)
  3629. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  3630. else
  3631. snprintf(buf, bufsz, "%4.1fC", *temp);
  3632. else
  3633. {
  3634. if (temp)
  3635. snprintf(buf, bufsz, " ");
  3636. if (maybe_unicode)
  3637. tailsprintf(buf, bufsz, " ");
  3638. }
  3639. tailsprintf(buf, bufsz, " | ");
  3640. }
  3641. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  3642. {
  3643. #ifndef HAVE_CURSES
  3644. assert(for_curses == false);
  3645. #endif
  3646. struct device_drv *drv = cgpu->drv;
  3647. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  3648. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[max(ALLOC_H2B_SHORT, ALLOC_H2B_SPACED)+3+1];
  3649. char rejpcbuf[6];
  3650. char bnbuf[6];
  3651. double dev_runtime;
  3652. if (!opt_show_procs)
  3653. cgpu = cgpu->device;
  3654. dev_runtime = cgpu_runtime(cgpu);
  3655. double rolling, mhashes;
  3656. int accepted, rejected, stale;
  3657. double waccepted;
  3658. double wnotaccepted;
  3659. int hwerrs;
  3660. double bad_diff1, good_diff1;
  3661. rolling = mhashes = waccepted = wnotaccepted = 0;
  3662. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  3663. {
  3664. struct cgpu_info *slave = cgpu;
  3665. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  3666. {
  3667. slave->utility = slave->accepted / dev_runtime * 60;
  3668. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  3669. rolling += slave->rolling;
  3670. mhashes += slave->total_mhashes;
  3671. if (opt_weighed_stats)
  3672. {
  3673. accepted += slave->diff_accepted;
  3674. rejected += slave->diff_rejected;
  3675. stale += slave->diff_stale;
  3676. }
  3677. else
  3678. {
  3679. accepted += slave->accepted;
  3680. rejected += slave->rejected;
  3681. stale += slave->stale;
  3682. }
  3683. waccepted += slave->diff_accepted;
  3684. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  3685. hwerrs += slave->hw_errors;
  3686. bad_diff1 += slave->bad_diff1;
  3687. good_diff1 += slave->diff1;
  3688. if (opt_show_procs)
  3689. break;
  3690. }
  3691. }
  3692. if ((cgpu->device == cgpu) && (drv->get_master_rolling_hashrate))
  3693. rolling = drv->get_master_rolling_hashrate(cgpu);
  3694. double wtotal = (waccepted + wnotaccepted);
  3695. multi_format_unit_array2(
  3696. ((char*[]){cHr, aHr, uHr}),
  3697. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  3698. true, "h/s", hashrate_style,
  3699. 3,
  3700. 1e6*rolling,
  3701. 1e6*mhashes / dev_runtime,
  3702. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  3703. // Processor representation
  3704. #ifdef HAVE_CURSES
  3705. if (for_curses)
  3706. {
  3707. if (opt_show_procs)
  3708. snprintf(buf, bufsz, " %*s: ", -(5 + max_lpdigits), cgpu->proc_repr);
  3709. else
  3710. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  3711. }
  3712. else
  3713. #endif
  3714. snprintf(buf, bufsz, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  3715. if (include_serial_in_statline && cgpu->dev_serial)
  3716. tailsprintf(buf, bufsz, "[serial=%s] ", cgpu->dev_serial);
  3717. if (unlikely(cgpu->status == LIFE_INIT))
  3718. {
  3719. tailsprintf(buf, bufsz, "Initializing...");
  3720. return;
  3721. }
  3722. {
  3723. const size_t bufln = strlen(buf);
  3724. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3725. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3726. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3727. else
  3728. {
  3729. float temp = cgpu->temp;
  3730. if (!opt_show_procs)
  3731. {
  3732. // Find the highest temperature of all processors
  3733. struct cgpu_info *proc = cgpu;
  3734. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3735. if (proc->temp > temp)
  3736. temp = proc->temp;
  3737. }
  3738. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3739. }
  3740. }
  3741. #ifdef HAVE_CURSES
  3742. if (for_curses)
  3743. {
  3744. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3745. const char *cHrStats;
  3746. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3747. bool all_dead = true, all_off = true, all_rdrv = true;
  3748. struct cgpu_info *proc = cgpu;
  3749. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3750. {
  3751. switch (cHrStatsI) {
  3752. default:
  3753. if (proc->status == LIFE_WAIT)
  3754. cHrStatsI = 5;
  3755. case 5:
  3756. if (proc->deven == DEV_RECOVER_ERR)
  3757. cHrStatsI = 4;
  3758. case 4:
  3759. if (proc->deven == DEV_RECOVER)
  3760. cHrStatsI = 3;
  3761. case 3:
  3762. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3763. {
  3764. cHrStatsI = 1;
  3765. all_off = false;
  3766. }
  3767. else
  3768. {
  3769. if (likely(proc->deven == DEV_ENABLED))
  3770. all_off = false;
  3771. if (proc->deven != DEV_RECOVER_DRV)
  3772. all_rdrv = false;
  3773. }
  3774. case 1:
  3775. break;
  3776. }
  3777. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3778. all_dead = false;
  3779. if (opt_show_procs)
  3780. break;
  3781. }
  3782. if (unlikely(all_dead))
  3783. cHrStatsI = 0;
  3784. else
  3785. if (unlikely(all_off))
  3786. cHrStatsI = 2;
  3787. cHrStats = cHrStatsOpt[cHrStatsI];
  3788. if (cHrStatsI == 2 && all_rdrv)
  3789. cHrStats = " RST ";
  3790. format_statline(buf, bufsz,
  3791. cHrStats,
  3792. aHr, uHr,
  3793. accepted, rejected, stale,
  3794. wnotaccepted, waccepted,
  3795. hwerrs,
  3796. bad_diff1, bad_diff1 + good_diff1);
  3797. }
  3798. else
  3799. #endif
  3800. {
  3801. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3802. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3803. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3804. opt_log_interval,
  3805. cHr, aHr, uHr,
  3806. accepted,
  3807. rejected,
  3808. stale,
  3809. rejpcbuf,
  3810. hwerrs,
  3811. bnbuf
  3812. );
  3813. }
  3814. }
  3815. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3816. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3817. static void text_print_status(int thr_id)
  3818. {
  3819. struct cgpu_info *cgpu;
  3820. char logline[256];
  3821. cgpu = get_thr_cgpu(thr_id);
  3822. if (cgpu) {
  3823. get_statline(logline, sizeof(logline), cgpu);
  3824. printf("\n%s\r", logline);
  3825. fflush(stdout);
  3826. }
  3827. }
  3828. #ifdef HAVE_CURSES
  3829. static int attr_bad = A_BOLD;
  3830. #ifdef WIN32
  3831. #define swprintf snwprintf
  3832. #endif
  3833. static
  3834. void bfg_waddstr(WINDOW *win, const char *s)
  3835. {
  3836. const char *p = s;
  3837. int32_t w;
  3838. int wlen;
  3839. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3840. while (true)
  3841. {
  3842. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3843. {
  3844. // Printable ASCII
  3845. ++p;
  3846. }
  3847. if (p != s)
  3848. waddnstr(win, s, p - s);
  3849. w = utf8_decode(p, &wlen);
  3850. s = p += wlen;
  3851. switch(w)
  3852. {
  3853. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3854. case '\0':
  3855. return;
  3856. case 0xb5: // micro symbol
  3857. w = unicode_micro;
  3858. goto default_addch;
  3859. case 0xf000: // "bad" off
  3860. wattroff(win, attr_bad);
  3861. break;
  3862. case 0xf001: // "bad" on
  3863. wattron(win, attr_bad);
  3864. break;
  3865. #ifdef USE_UNICODE
  3866. case '|':
  3867. wadd_wch(win, WACS_VLINE);
  3868. break;
  3869. #endif
  3870. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3871. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3872. if (!use_unicode)
  3873. {
  3874. waddch(win, '-');
  3875. break;
  3876. }
  3877. #ifdef USE_UNICODE
  3878. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3879. break;
  3880. #endif
  3881. case 0x2022:
  3882. if (w > WCHAR_MAX || !iswprint(w))
  3883. w = '*';
  3884. default:
  3885. default_addch:
  3886. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3887. {
  3888. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3889. if (iswprint(REPLACEMENT_CHAR))
  3890. w = REPLACEMENT_CHAR;
  3891. else
  3892. #endif
  3893. w = '?';
  3894. }
  3895. {
  3896. #ifdef USE_UNICODE
  3897. wchar_t wbuf[0x10];
  3898. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3899. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3900. waddnwstr(win, wbuf, wbuflen);
  3901. #else
  3902. wprintw(win, "%lc", (wint_t)w);
  3903. #endif
  3904. }
  3905. }
  3906. }
  3907. }
  3908. static inline
  3909. void bfg_hline(WINDOW *win, int y)
  3910. {
  3911. int maxx, __maybe_unused maxy;
  3912. getmaxyx(win, maxy, maxx);
  3913. #ifdef USE_UNICODE
  3914. if (use_unicode)
  3915. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3916. else
  3917. #endif
  3918. mvwhline(win, y, 0, '-', maxx);
  3919. }
  3920. static
  3921. int bfg_win_linelen(WINDOW * const win)
  3922. {
  3923. int maxx;
  3924. int __maybe_unused y;
  3925. getmaxyx(win, y, maxx);
  3926. return maxx;
  3927. }
  3928. // Spaces until end of line, using current attributes (ie, not completely clear)
  3929. static
  3930. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3931. {
  3932. int x, maxx;
  3933. int __maybe_unused y;
  3934. getmaxyx(win, y, maxx);
  3935. getyx(win, y, x);
  3936. const int space_count = (maxx - x) - offset;
  3937. // Check for negative - terminal too narrow
  3938. if (space_count <= 0)
  3939. return;
  3940. char buf[space_count];
  3941. memset(buf, ' ', space_count);
  3942. waddnstr(win, buf, space_count);
  3943. }
  3944. static int menu_attr = A_REVERSE;
  3945. #define CURBUFSIZ 256
  3946. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3947. char tmp42[CURBUFSIZ]; \
  3948. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3949. wmove(win, y, x); \
  3950. bfg_waddstr(win, tmp42); \
  3951. } while (0)
  3952. #define cg_wprintw(win, fmt, ...) do { \
  3953. char tmp42[CURBUFSIZ]; \
  3954. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3955. bfg_waddstr(win, tmp42); \
  3956. } while (0)
  3957. static
  3958. void update_block_display_line(const int blky, struct mining_goal_info *goal)
  3959. {
  3960. struct blockchain_info * const blkchain = goal->blkchain;
  3961. struct block_info * const blkinfo = blkchain->currentblk;
  3962. double income;
  3963. char incomestr[ALLOC_H2B_SHORT+6+1];
  3964. if (blkinfo->height)
  3965. {
  3966. income = goal->diff_accepted * 3600 * blkchain->currentblk_subsidy / total_secs / goal->current_diff;
  3967. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  3968. }
  3969. else
  3970. strcpy(incomestr, "?");
  3971. int linelen = bfg_win_linelen(statuswin);
  3972. wmove(statuswin, blky, 0);
  3973. bfg_waddstr(statuswin, " Block");
  3974. if (!goal->is_default)
  3975. linelen -= strlen(goal->name) + 1;
  3976. linelen -= 6; // " Block"
  3977. if (blkinfo->height && blkinfo->height < 1000000)
  3978. {
  3979. cg_wprintw(statuswin, " #%6u", blkinfo->height);
  3980. linelen -= 8;
  3981. }
  3982. bfg_waddstr(statuswin, ":");
  3983. if (linelen > 55)
  3984. bfg_waddstr(statuswin, " ");
  3985. if (linelen >= 65)
  3986. bfg_waddstr(statuswin, "...");
  3987. {
  3988. char hexpbh[0x11];
  3989. if (!(blkinfo->height && blkinfo->height < 1000000))
  3990. {
  3991. bin2hex(hexpbh, &blkinfo->prevblkhash[4], 4);
  3992. bfg_waddstr(statuswin, hexpbh);
  3993. }
  3994. bin2hex(hexpbh, &blkinfo->prevblkhash[0], 4);
  3995. bfg_waddstr(statuswin, hexpbh);
  3996. }
  3997. if (linelen >= 55)
  3998. bfg_waddstr(statuswin, " ");
  3999. cg_wprintw(statuswin, " Diff:%s", goal->current_diff_str);
  4000. if (linelen >= 69)
  4001. bfg_waddstr(statuswin, " ");
  4002. cg_wprintw(statuswin, "(%s) ", goal->net_hashrate);
  4003. if (linelen >= 62)
  4004. {
  4005. if (linelen >= 69)
  4006. bfg_waddstr(statuswin, " ");
  4007. bfg_waddstr(statuswin, "Started:");
  4008. }
  4009. else
  4010. bfg_waddstr(statuswin, "S:");
  4011. if (linelen >= 69)
  4012. bfg_waddstr(statuswin, " ");
  4013. bfg_waddstr(statuswin, blkchain->currentblk_first_seen_time_str);
  4014. if (linelen >= 69)
  4015. bfg_waddstr(statuswin, " ");
  4016. cg_wprintw(statuswin, " I:%s", incomestr);
  4017. if (!goal->is_default)
  4018. cg_wprintw(statuswin, " %s", goal->name);
  4019. wclrtoeol(statuswin);
  4020. }
  4021. static bool pool_actively_in_use(const struct pool *, const struct pool *);
  4022. static
  4023. void update_block_display(void)
  4024. {
  4025. struct mining_goal_info *goal, *tmpgoal;
  4026. int blky = 3, i, total_found_goals = 0;
  4027. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  4028. {
  4029. for (i = 0; i < total_pools; ++i)
  4030. {
  4031. struct pool * const pool = pools[i];
  4032. if (pool->goal == goal && pool_actively_in_use(pool, NULL))
  4033. break;
  4034. }
  4035. if (i >= total_pools)
  4036. // no pools using this goal, so it's probably stale anyway
  4037. continue;
  4038. update_block_display_line(blky++, goal);
  4039. ++total_found_goals;
  4040. }
  4041. if (total_found_goals != active_goals)
  4042. {
  4043. active_goals = total_found_goals;
  4044. devcursor = 7 + active_goals;
  4045. switch_logsize();
  4046. }
  4047. }
  4048. static bool pool_unworkable(const struct pool *);
  4049. /* Must be called with curses mutex lock held and curses_active */
  4050. static void curses_print_status(const int ts)
  4051. {
  4052. struct pool *pool = currentpool;
  4053. struct timeval now, tv;
  4054. float efficiency;
  4055. int logdiv;
  4056. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  4057. wattron(statuswin, attr_title);
  4058. const int linelen = bfg_win_linelen(statuswin);
  4059. int titlelen = 1 + strlen(PACKAGE) + 1 + strlen(VERSION) + 3 + 21 + 3 + 19;
  4060. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " ");
  4061. if (titlelen + 17 < linelen)
  4062. cg_wprintw(statuswin, "version ");
  4063. cg_wprintw(statuswin, VERSION " - ");
  4064. if (titlelen + 9 < linelen)
  4065. cg_wprintw(statuswin, "Started: ");
  4066. else
  4067. if (titlelen + 7 <= linelen)
  4068. cg_wprintw(statuswin, "Start: ");
  4069. cg_wprintw(statuswin, "%s", datestamp);
  4070. timer_set_now(&now);
  4071. {
  4072. unsigned int days, hours;
  4073. div_t d;
  4074. timersub(&now, &miner_started, &tv);
  4075. d = div(tv.tv_sec, 86400);
  4076. days = d.quot;
  4077. d = div(d.rem, 3600);
  4078. hours = d.quot;
  4079. d = div(d.rem, 60);
  4080. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  4081. , days
  4082. , (days == 1) ? ' ' : 's'
  4083. , hours
  4084. , d.quot
  4085. , d.rem
  4086. );
  4087. }
  4088. bfg_wspctoeol(statuswin, 0);
  4089. wattroff(statuswin, attr_title);
  4090. wattron(statuswin, menu_attr);
  4091. wmove(statuswin, 1, 0);
  4092. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  4093. bfg_wspctoeol(statuswin, 14);
  4094. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  4095. wattroff(statuswin, menu_attr);
  4096. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && enabled_pools > 1) {
  4097. char poolinfo[20], poolinfo2[20];
  4098. int poolinfooff = 0, poolinfo2off, workable_pools = 0;
  4099. double lowdiff = DBL_MAX, highdiff = -1;
  4100. struct pool *lowdiff_pool = pools[0], *highdiff_pool = pools[0];
  4101. time_t oldest_work_restart = time(NULL) + 1;
  4102. struct pool *oldest_work_restart_pool = pools[0];
  4103. for (int i = 0; i < total_pools; ++i)
  4104. {
  4105. if (pool_unworkable(pools[i]))
  4106. continue;
  4107. // NOTE: Only set pool var when it's workable; if only one is, it gets used by single-pool code
  4108. pool = pools[i];
  4109. ++workable_pools;
  4110. if (poolinfooff < sizeof(poolinfo))
  4111. poolinfooff += snprintf(&poolinfo[poolinfooff], sizeof(poolinfo) - poolinfooff, "%u,", pool->pool_no);
  4112. struct cgminer_pool_stats * const pool_stats = &pool->cgminer_pool_stats;
  4113. if (pool_stats->last_diff < lowdiff)
  4114. {
  4115. lowdiff = pool_stats->last_diff;
  4116. lowdiff_pool = pool;
  4117. }
  4118. if (pool_stats->last_diff > highdiff)
  4119. {
  4120. highdiff = pool_stats->last_diff;
  4121. highdiff_pool = pool;
  4122. }
  4123. if (oldest_work_restart >= pool->work_restart_time)
  4124. {
  4125. oldest_work_restart = pool->work_restart_time;
  4126. oldest_work_restart_pool = pool;
  4127. }
  4128. }
  4129. if (unlikely(!workable_pools))
  4130. goto no_workable_pools;
  4131. if (workable_pools == 1)
  4132. goto one_workable_pool;
  4133. poolinfo2off = snprintf(poolinfo2, sizeof(poolinfo2), "%u (", workable_pools);
  4134. if (poolinfooff > sizeof(poolinfo2) - poolinfo2off - 1)
  4135. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s...)", (int)(sizeof(poolinfo2) - poolinfo2off - 5), poolinfo);
  4136. else
  4137. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s)%*s", (int)(poolinfooff - 1), poolinfo, (int)(sizeof(poolinfo2)), "");
  4138. cg_mvwprintw(statuswin, 2, 0, " Pools: %s Diff:%s%s%s %c LU:%s",
  4139. poolinfo2,
  4140. lowdiff_pool->diff,
  4141. (lowdiff == highdiff) ? "" : "-",
  4142. (lowdiff == highdiff) ? "" : highdiff_pool->diff,
  4143. pool->goal->have_longpoll ? '+' : '-',
  4144. oldest_work_restart_pool->work_restart_timestamp);
  4145. }
  4146. else
  4147. if (pool_unworkable(pool))
  4148. {
  4149. no_workable_pools: ;
  4150. wattron(statuswin, attr_bad);
  4151. cg_mvwprintw(statuswin, 2, 0, " (all pools are dead) ");
  4152. wattroff(statuswin, attr_bad);
  4153. }
  4154. else
  4155. {
  4156. one_workable_pool: ;
  4157. char pooladdr[19];
  4158. {
  4159. const char *rawaddr = pool->sockaddr_url;
  4160. BFGINIT(rawaddr, pool->rpc_url);
  4161. size_t pooladdrlen = strlen(rawaddr);
  4162. if (pooladdrlen > 20)
  4163. snprintf(pooladdr, sizeof(pooladdr), "...%s", &rawaddr[pooladdrlen - (sizeof(pooladdr) - 4)]);
  4164. else
  4165. snprintf(pooladdr, sizeof(pooladdr), "%*s", -(int)(sizeof(pooladdr) - 1), rawaddr);
  4166. }
  4167. cg_mvwprintw(statuswin, 2, 0, " Pool%2u: %s Diff:%s %c%s LU:%s User:%s",
  4168. pool->pool_no, pooladdr, pool->diff,
  4169. pool->goal->have_longpoll ? '+' : '-', pool_proto_str(pool),
  4170. pool->work_restart_timestamp,
  4171. pool->rpc_user);
  4172. }
  4173. wclrtoeol(statuswin);
  4174. char bwstr[(ALLOC_H2B_SHORT*2)+3+1];
  4175. cg_mvwprintw(statuswin, devcursor - 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f BS:%s",
  4176. ts,
  4177. total_go + total_ro,
  4178. new_blocks,
  4179. total_submitting,
  4180. multi_format_unit2(bwstr, sizeof(bwstr),
  4181. false, "B/s", H2B_SHORT, "/", 2,
  4182. (float)(total_bytes_rcvd / total_secs),
  4183. (float)(total_bytes_sent / total_secs)),
  4184. efficiency,
  4185. best_share);
  4186. wclrtoeol(statuswin);
  4187. mvwaddstr(statuswin, devcursor - 3, 0, " ");
  4188. bfg_waddstr(statuswin, statusline);
  4189. wclrtoeol(statuswin);
  4190. int devdiv = devcursor - 2;
  4191. logdiv = statusy - 1;
  4192. bfg_hline(statuswin, devdiv);
  4193. bfg_hline(statuswin, logdiv);
  4194. #ifdef USE_UNICODE
  4195. if (use_unicode)
  4196. {
  4197. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  4198. if (opt_show_procs && !opt_compact)
  4199. offset += max_lpdigits; // proc letter(s)
  4200. if (have_unicode_degrees)
  4201. ++offset; // degrees symbol
  4202. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4203. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4204. offset += 24; // hashrates etc
  4205. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4206. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4207. }
  4208. #endif
  4209. }
  4210. static void adj_width(int var, int *length)
  4211. {
  4212. if ((int)(log10(var) + 1) > *length)
  4213. (*length)++;
  4214. }
  4215. static int dev_width;
  4216. static void curses_print_devstatus(struct cgpu_info *cgpu)
  4217. {
  4218. char logline[256];
  4219. int ypos;
  4220. if (opt_compact)
  4221. return;
  4222. /* Check this isn't out of the window size */
  4223. if (opt_show_procs)
  4224. ypos = cgpu->cgminer_id;
  4225. else
  4226. {
  4227. if (cgpu->proc_id)
  4228. return;
  4229. ypos = cgpu->device_line_id;
  4230. }
  4231. ypos += devsummaryYOffset;
  4232. if (ypos < 0)
  4233. return;
  4234. ypos += devcursor - 1;
  4235. if (ypos >= statusy - 1)
  4236. return;
  4237. if (wmove(statuswin, ypos, 0) == ERR)
  4238. return;
  4239. get_statline2(logline, sizeof(logline), cgpu, true);
  4240. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  4241. wattron(statuswin, A_REVERSE);
  4242. bfg_waddstr(statuswin, logline);
  4243. wattroff(statuswin, A_REVERSE);
  4244. wclrtoeol(statuswin);
  4245. }
  4246. static
  4247. void _refresh_devstatus(const bool already_have_lock) {
  4248. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  4249. int i;
  4250. if (unlikely(!total_devices))
  4251. {
  4252. const int ypos = devcursor - 1;
  4253. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  4254. {
  4255. wattron(statuswin, attr_bad);
  4256. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  4257. wclrtoeol(statuswin);
  4258. wattroff(statuswin, attr_bad);
  4259. }
  4260. }
  4261. for (i = 0; i < total_devices; i++)
  4262. curses_print_devstatus(get_devices(i));
  4263. touchwin(statuswin);
  4264. wrefresh(statuswin);
  4265. if (!already_have_lock)
  4266. unlock_curses();
  4267. }
  4268. }
  4269. #define refresh_devstatus() _refresh_devstatus(false)
  4270. #endif
  4271. static void print_status(int thr_id)
  4272. {
  4273. if (!curses_active)
  4274. text_print_status(thr_id);
  4275. }
  4276. #ifdef HAVE_CURSES
  4277. static
  4278. bool set_statusy(int maxy)
  4279. {
  4280. if (loginput_size)
  4281. {
  4282. maxy -= loginput_size;
  4283. if (maxy < 0)
  4284. maxy = 0;
  4285. }
  4286. if (logstart < maxy)
  4287. maxy = logstart;
  4288. if (statusy == maxy)
  4289. return false;
  4290. statusy = maxy;
  4291. logcursor = statusy;
  4292. return true;
  4293. }
  4294. /* Check for window resize. Called with curses mutex locked */
  4295. static inline void change_logwinsize(void)
  4296. {
  4297. int x, y, logx, logy;
  4298. getmaxyx(mainwin, y, x);
  4299. if (x < 80 || y < 25)
  4300. return;
  4301. if (y > statusy + 2 && statusy < logstart) {
  4302. set_statusy(y - 2);
  4303. mvwin(logwin, logcursor, 0);
  4304. bfg_wresize(statuswin, statusy, x);
  4305. }
  4306. y -= logcursor;
  4307. getmaxyx(logwin, logy, logx);
  4308. /* Detect screen size change */
  4309. if (x != logx || y != logy)
  4310. bfg_wresize(logwin, y, x);
  4311. }
  4312. static void check_winsizes(void)
  4313. {
  4314. if (!use_curses)
  4315. return;
  4316. if (curses_active_locked()) {
  4317. int y, x;
  4318. x = getmaxx(statuswin);
  4319. if (set_statusy(LINES - 2))
  4320. {
  4321. erase();
  4322. bfg_wresize(statuswin, statusy, x);
  4323. getmaxyx(mainwin, y, x);
  4324. y -= logcursor;
  4325. bfg_wresize(logwin, y, x);
  4326. mvwin(logwin, logcursor, 0);
  4327. }
  4328. unlock_curses();
  4329. }
  4330. }
  4331. static int device_line_id_count;
  4332. static void switch_logsize(void)
  4333. {
  4334. if (curses_active_locked()) {
  4335. if (opt_compact) {
  4336. logstart = devcursor - 1;
  4337. logcursor = logstart + 1;
  4338. } else {
  4339. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  4340. logstart = devcursor + total_lines;
  4341. logcursor = logstart;
  4342. }
  4343. unlock_curses();
  4344. }
  4345. check_winsizes();
  4346. update_block_display();
  4347. }
  4348. /* For mandatory printing when mutex is already locked */
  4349. void _wlog(const char *str)
  4350. {
  4351. static bool newline;
  4352. size_t end = strlen(str) - 1;
  4353. if (newline)
  4354. bfg_waddstr(logwin, "\n");
  4355. if (str[end] == '\n')
  4356. {
  4357. char *s;
  4358. newline = true;
  4359. s = alloca(end + 1);
  4360. memcpy(s, str, end);
  4361. s[end] = '\0';
  4362. str = s;
  4363. }
  4364. else
  4365. newline = false;
  4366. bfg_waddstr(logwin, str);
  4367. }
  4368. /* Mandatory printing */
  4369. void _wlogprint(const char *str)
  4370. {
  4371. if (curses_active_locked()) {
  4372. _wlog(str);
  4373. unlock_curses();
  4374. }
  4375. }
  4376. #endif
  4377. #ifdef HAVE_CURSES
  4378. bool _log_curses_only(int prio, const char *datetime, const char *str)
  4379. {
  4380. bool high_prio;
  4381. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  4382. if (curses_active)
  4383. {
  4384. if (!loginput_size || high_prio) {
  4385. wlog(" %s %s\n", datetime, str);
  4386. if (high_prio) {
  4387. touchwin(logwin);
  4388. wrefresh(logwin);
  4389. }
  4390. }
  4391. return true;
  4392. }
  4393. return false;
  4394. }
  4395. void clear_logwin(void)
  4396. {
  4397. if (curses_active_locked()) {
  4398. wclear(logwin);
  4399. unlock_curses();
  4400. }
  4401. }
  4402. void logwin_update(void)
  4403. {
  4404. if (curses_active_locked()) {
  4405. touchwin(logwin);
  4406. wrefresh(logwin);
  4407. unlock_curses();
  4408. }
  4409. }
  4410. #endif
  4411. void enable_pool(struct pool * const pool)
  4412. {
  4413. if (pool->enabled != POOL_ENABLED) {
  4414. mutex_lock(&lp_lock);
  4415. enabled_pools++;
  4416. pool->enabled = POOL_ENABLED;
  4417. pthread_cond_broadcast(&lp_cond);
  4418. mutex_unlock(&lp_lock);
  4419. if (pool->prio < current_pool()->prio)
  4420. switch_pools(pool);
  4421. }
  4422. }
  4423. void manual_enable_pool(struct pool * const pool)
  4424. {
  4425. pool->failover_only = false;
  4426. BFGINIT(pool->quota, 1);
  4427. enable_pool(pool);
  4428. }
  4429. void disable_pool(struct pool * const pool, const enum pool_enable enable_status)
  4430. {
  4431. if (pool->enabled == POOL_DISABLED)
  4432. /* had been manually disabled before */
  4433. return;
  4434. if (pool->enabled != POOL_ENABLED)
  4435. {
  4436. /* has been programmatically disabled already, just change to the new status directly */
  4437. pool->enabled = enable_status;
  4438. return;
  4439. }
  4440. /* Fall into the lock area */
  4441. mutex_lock(&lp_lock);
  4442. --enabled_pools;
  4443. pool->enabled = enable_status;
  4444. mutex_unlock(&lp_lock);
  4445. if (pool == current_pool())
  4446. switch_pools(NULL);
  4447. }
  4448. static
  4449. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  4450. struct cgpu_info *cgpu;
  4451. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  4452. const unsigned char *hashpart = &work->hash[0x1c - malgo->ui_skip_hash_bytes];
  4453. char shrdiffdisp[ALLOC_H2B_SHORTV];
  4454. const double tgtdiff = work->work_difficulty;
  4455. char tgtdiffdisp[ALLOC_H2B_SHORTV];
  4456. char where[20];
  4457. cgpu = get_thr_cgpu(work->thr_id);
  4458. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  4459. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  4460. if (total_pools > 1)
  4461. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  4462. else
  4463. where[0] = '\0';
  4464. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  4465. disp,
  4466. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  4467. cgpu->proc_repr,
  4468. where,
  4469. shrdiffdisp, tgtdiffdisp,
  4470. reason,
  4471. resubmit ? "(resubmit)" : "",
  4472. worktime
  4473. );
  4474. }
  4475. static bool test_work_current(struct work *);
  4476. static void _submit_work_async(struct work *);
  4477. static
  4478. void maybe_local_submit(const struct work *work)
  4479. {
  4480. #if BLKMAKER_VERSION > 3
  4481. if (unlikely(work->block && work->tr))
  4482. {
  4483. // This is a block with a full template (GBT)
  4484. // Regardless of the result, submit to local bitcoind(s) as well
  4485. struct work *work_cp;
  4486. for (int i = 0; i < total_pools; ++i)
  4487. {
  4488. if (!uri_get_param_bool(pools[i]->rpc_url, "allblocks", false))
  4489. continue;
  4490. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  4491. work_cp = copy_work(work);
  4492. work_cp->pool = pools[i];
  4493. work_cp->do_foreign_submit = true;
  4494. _submit_work_async(work_cp);
  4495. }
  4496. }
  4497. #endif
  4498. }
  4499. static
  4500. json_t *extract_reject_reason_j(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4501. {
  4502. if (json_is_string(res))
  4503. return res;
  4504. if ( (res = json_object_get(val, "reject-reason")) )
  4505. return res;
  4506. if (work->stratum && err && json_is_array(err) && json_array_size(err) >= 2 && (res = json_array_get(err, 1)) && json_is_string(res))
  4507. return res;
  4508. return NULL;
  4509. }
  4510. static
  4511. const char *extract_reject_reason(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4512. {
  4513. json_t * const j = extract_reject_reason_j(val, res, err, work);
  4514. return j ? json_string_value(j) : NULL;
  4515. }
  4516. static
  4517. int put_in_parens(char * const buf, const size_t bufsz, const char * const s)
  4518. {
  4519. if (!s)
  4520. {
  4521. if (bufsz)
  4522. buf[0] = '\0';
  4523. return 0;
  4524. }
  4525. int p = snprintf(buf, bufsz, " (%s", s);
  4526. if (p >= bufsz - 1)
  4527. p = bufsz - 2;
  4528. strcpy(&buf[p], ")");
  4529. return p + 1;
  4530. }
  4531. /* Theoretically threads could race when modifying accepted and
  4532. * rejected values but the chance of two submits completing at the
  4533. * same time is zero so there is no point adding extra locking */
  4534. static void
  4535. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  4536. /*char *hashshow,*/ bool resubmit, char *worktime)
  4537. {
  4538. struct pool *pool = work->pool;
  4539. struct cgpu_info *cgpu;
  4540. cgpu = get_thr_cgpu(work->thr_id);
  4541. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  4542. struct mining_goal_info * const goal = pool->goal;
  4543. mutex_lock(&stats_lock);
  4544. cgpu->accepted++;
  4545. total_accepted++;
  4546. pool->accepted++;
  4547. cgpu->diff_accepted += work->work_difficulty;
  4548. total_diff_accepted += work->work_difficulty;
  4549. pool->diff_accepted += work->work_difficulty;
  4550. goal->diff_accepted += work->work_difficulty;
  4551. mutex_unlock(&stats_lock);
  4552. pool->seq_rejects = 0;
  4553. cgpu->last_share_pool = pool->pool_no;
  4554. cgpu->last_share_pool_time = time(NULL);
  4555. cgpu->last_share_diff = work->work_difficulty;
  4556. pool->last_share_time = cgpu->last_share_pool_time;
  4557. pool->last_share_diff = work->work_difficulty;
  4558. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  4559. if (!QUIET) {
  4560. share_result_msg(work, "Accepted", "", resubmit, worktime);
  4561. }
  4562. sharelog("accept", work);
  4563. if (opt_shares && total_diff_accepted >= opt_shares) {
  4564. applog(LOG_WARNING, "Successfully mined %g accepted shares as requested and exiting.", opt_shares);
  4565. kill_work();
  4566. return;
  4567. }
  4568. /* Detect if a pool that has been temporarily disabled for
  4569. * continually rejecting shares has started accepting shares.
  4570. * This will only happen with the work returned from a
  4571. * longpoll */
  4572. if (unlikely(pool->enabled == POOL_REJECTING)) {
  4573. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  4574. enable_pool(pool);
  4575. }
  4576. if (unlikely(work->block)) {
  4577. // Force moving on to this new block :)
  4578. struct work fakework;
  4579. memset(&fakework, 0, sizeof(fakework));
  4580. fakework.pool = work->pool;
  4581. // Copy block version, bits, and time from share
  4582. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  4583. memcpy(&fakework.data[68], &work->data[68], 8);
  4584. // Set prevblock to winning hash (swap32'd)
  4585. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  4586. test_work_current(&fakework);
  4587. }
  4588. }
  4589. else
  4590. if (!hash_target_check(work->hash, work->target))
  4591. {
  4592. // This was submitted despite failing the proper target
  4593. // Quietly ignore the reject
  4594. char reason[32];
  4595. put_in_parens(reason, sizeof(reason), extract_reject_reason(val, res, err, work));
  4596. applog(LOG_DEBUG, "Share above target rejected%s by pool %u as expected, ignoring", reason, pool->pool_no);
  4597. } else {
  4598. mutex_lock(&stats_lock);
  4599. cgpu->rejected++;
  4600. total_rejected++;
  4601. pool->rejected++;
  4602. cgpu->diff_rejected += work->work_difficulty;
  4603. total_diff_rejected += work->work_difficulty;
  4604. pool->diff_rejected += work->work_difficulty;
  4605. pool->seq_rejects++;
  4606. mutex_unlock(&stats_lock);
  4607. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  4608. if (!QUIET) {
  4609. char disposition[36] = "reject";
  4610. char reason[32];
  4611. const char *reasontmp = extract_reject_reason(val, res, err, work);
  4612. int n = put_in_parens(reason, sizeof(reason), reasontmp);
  4613. if (reason[0])
  4614. snprintf(&disposition[6], sizeof(disposition) - 6, ":%.*s", n - 3, &reason[2]);
  4615. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  4616. sharelog(disposition, work);
  4617. }
  4618. /* Once we have more than a nominal amount of sequential rejects,
  4619. * at least 10 and more than 3 mins at the current utility,
  4620. * disable the pool because some pool error is likely to have
  4621. * ensued. Do not do this if we know the share just happened to
  4622. * be stale due to networking delays.
  4623. */
  4624. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  4625. double utility = total_accepted / total_secs * 60;
  4626. if (pool->seq_rejects > utility * 3) {
  4627. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  4628. pool->pool_no, pool->seq_rejects);
  4629. disable_pool(pool, POOL_REJECTING);
  4630. pool->seq_rejects = 0;
  4631. }
  4632. }
  4633. }
  4634. maybe_local_submit(work);
  4635. }
  4636. static char *submit_upstream_work_request(struct work *work)
  4637. {
  4638. char *hexstr = NULL;
  4639. char *s, *sd;
  4640. struct pool *pool = work->pool;
  4641. if (work->tr)
  4642. {
  4643. blktemplate_t * const tmpl = work->tr->tmpl;
  4644. json_t *req;
  4645. unsigned char data[80];
  4646. swap32yes(data, work->data, 80 / 4);
  4647. #if BLKMAKER_VERSION > 3
  4648. if (work->do_foreign_submit)
  4649. req = blkmk_submit_foreign_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4650. else
  4651. #endif
  4652. req = blkmk_submit_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4653. s = json_dumps(req, 0);
  4654. json_decref(req);
  4655. sd = malloc(161);
  4656. bin2hex(sd, data, 80);
  4657. } else {
  4658. /* build hex string */
  4659. hexstr = malloc((sizeof(work->data) * 2) + 1);
  4660. bin2hex(hexstr, work->data, sizeof(work->data));
  4661. /* build JSON-RPC request */
  4662. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  4663. s = realloc_strcat(s, hexstr);
  4664. s = realloc_strcat(s, "\" ], \"id\":1}");
  4665. free(hexstr);
  4666. sd = s;
  4667. }
  4668. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  4669. if (work->tr)
  4670. free(sd);
  4671. else
  4672. s = realloc_strcat(s, "\n");
  4673. return s;
  4674. }
  4675. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  4676. json_t *res, *err;
  4677. bool rc = false;
  4678. int thr_id = work->thr_id;
  4679. struct pool *pool = work->pool;
  4680. struct timeval tv_submit_reply;
  4681. time_t ts_submit_reply;
  4682. char worktime[200] = "";
  4683. cgtime(&tv_submit_reply);
  4684. ts_submit_reply = time(NULL);
  4685. if (unlikely(!val)) {
  4686. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  4687. if (!pool_tset(pool, &pool->submit_fail)) {
  4688. total_ro++;
  4689. pool->remotefail_occasions++;
  4690. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  4691. }
  4692. goto out;
  4693. } else if (pool_tclear(pool, &pool->submit_fail))
  4694. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4695. res = json_object_get(val, "result");
  4696. err = json_object_get(val, "error");
  4697. if (!QUIET) {
  4698. if (opt_worktime) {
  4699. char workclone[20];
  4700. struct tm _tm;
  4701. struct tm *tm, tm_getwork, tm_submit_reply;
  4702. tm = &_tm;
  4703. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  4704. (struct timeval *)&(work->tv_getwork));
  4705. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  4706. (struct timeval *)&(work->tv_getwork_reply));
  4707. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  4708. (struct timeval *)&(work->tv_work_start));
  4709. double work_to_submit = tdiff(ptv_submit,
  4710. (struct timeval *)&(work->tv_work_found));
  4711. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  4712. int diffplaces = 3;
  4713. localtime_r(&work->ts_getwork, tm);
  4714. memcpy(&tm_getwork, tm, sizeof(struct tm));
  4715. localtime_r(&ts_submit_reply, tm);
  4716. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  4717. if (work->clone) {
  4718. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  4719. tdiff((struct timeval *)&(work->tv_cloned),
  4720. (struct timeval *)&(work->tv_getwork_reply)));
  4721. }
  4722. else
  4723. strcpy(workclone, "O");
  4724. if (work->work_difficulty < 1)
  4725. diffplaces = 6;
  4726. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  4727. const uint8_t * const prevblkhash = &work->data[4];
  4728. snprintf(worktime, sizeof(worktime),
  4729. " <-%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",
  4730. (unsigned long)be32toh(((uint32_t *)prevblkhash)[7 - malgo->worktime_skip_prevblk_u32]),
  4731. (unsigned long)be32toh(((uint32_t *)prevblkhash)[6 - malgo->worktime_skip_prevblk_u32]),
  4732. work->getwork_mode, diffplaces, work->work_difficulty,
  4733. tm_getwork.tm_hour, tm_getwork.tm_min,
  4734. tm_getwork.tm_sec, getwork_time, workclone,
  4735. getwork_to_work, work_time, work_to_submit, submit_time,
  4736. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  4737. tm_submit_reply.tm_sec);
  4738. }
  4739. }
  4740. share_result(val, res, err, work, resubmit, worktime);
  4741. if (!opt_realquiet)
  4742. print_status(thr_id);
  4743. if (!want_per_device_stats) {
  4744. char logline[256];
  4745. struct cgpu_info *cgpu;
  4746. cgpu = get_thr_cgpu(thr_id);
  4747. get_statline(logline, sizeof(logline), cgpu);
  4748. applog(LOG_INFO, "%s", logline);
  4749. }
  4750. json_decref(val);
  4751. rc = true;
  4752. out:
  4753. return rc;
  4754. }
  4755. /* Specifies whether we can use this pool for work or not. */
  4756. static bool pool_unworkable(const struct pool * const pool)
  4757. {
  4758. if (pool->idle)
  4759. return true;
  4760. if (pool->enabled != POOL_ENABLED)
  4761. return true;
  4762. if (pool->has_stratum && !pool->stratum_active)
  4763. return true;
  4764. return false;
  4765. }
  4766. static struct pool *priority_pool(int);
  4767. static bool pool_unusable(struct pool *);
  4768. static
  4769. bool pool_actively_desired(const struct pool * const pool, const struct pool *cp)
  4770. {
  4771. if (pool->enabled != POOL_ENABLED)
  4772. return false;
  4773. if (pool_strategy == POOL_LOADBALANCE && pool->quota)
  4774. return true;
  4775. if (pool_strategy == POOL_BALANCE && !pool->failover_only)
  4776. return true;
  4777. if (!cp)
  4778. cp = current_pool();
  4779. if (pool == cp)
  4780. return true;
  4781. // If we are the highest priority, workable pool for a given algorithm, we are needed
  4782. struct mining_algorithm * const malgo = pool->goal->malgo;
  4783. for (int i = 0; i < total_pools; ++i)
  4784. {
  4785. struct pool * const other_pool = priority_pool(i);
  4786. if (other_pool == pool)
  4787. return true;
  4788. if (pool_unusable(other_pool))
  4789. continue;
  4790. if (other_pool->goal->malgo == malgo)
  4791. break;
  4792. }
  4793. return false;
  4794. }
  4795. static
  4796. bool pool_actively_in_use(const struct pool * const pool, const struct pool *cp)
  4797. {
  4798. return (!pool_unworkable(pool)) && pool_actively_desired(pool, cp);
  4799. }
  4800. static
  4801. bool pool_supports_block_change_notification(struct pool * const pool)
  4802. {
  4803. return pool->has_stratum || pool->lp_url;
  4804. }
  4805. static
  4806. bool pool_has_active_block_change_notification(struct pool * const pool)
  4807. {
  4808. return pool->stratum_active || pool->lp_active;
  4809. }
  4810. static struct pool *_select_longpoll_pool(struct pool *, bool(*)(struct pool *));
  4811. #define select_longpoll_pool(pool) _select_longpoll_pool(pool, pool_supports_block_change_notification)
  4812. #define pool_active_lp_pool(pool) _select_longpoll_pool(pool, pool_has_active_block_change_notification)
  4813. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  4814. * rolling average per 10 minutes and if pools start getting more, it biases
  4815. * away from them to distribute work evenly. The share count is reset to the
  4816. * rolling average every 10 minutes to not send all work to one pool after it
  4817. * has been disabled/out for an extended period. */
  4818. static
  4819. struct pool *select_balanced(struct pool *cp, struct mining_algorithm * const malgo)
  4820. {
  4821. int i, lowest = cp->shares;
  4822. struct pool *ret = cp, *failover_pool = NULL;
  4823. for (i = 0; i < total_pools; i++) {
  4824. struct pool *pool = pools[i];
  4825. if (malgo && pool->goal->malgo != malgo)
  4826. continue;
  4827. if (pool_unworkable(pool))
  4828. continue;
  4829. if (pool->failover_only)
  4830. {
  4831. BFGINIT(failover_pool, pool);
  4832. continue;
  4833. }
  4834. if (pool->shares < lowest) {
  4835. lowest = pool->shares;
  4836. ret = pool;
  4837. }
  4838. }
  4839. if (malgo && ret->goal->malgo != malgo)
  4840. // Yes, we want failover_pool even if it's NULL
  4841. ret = failover_pool;
  4842. else
  4843. if (pool_unworkable(ret) && failover_pool)
  4844. ret = failover_pool;
  4845. if (ret)
  4846. ++ret->shares;
  4847. return ret;
  4848. }
  4849. static
  4850. struct pool *select_loadbalance(struct mining_algorithm * const malgo)
  4851. {
  4852. static int rotating_pool = 0;
  4853. struct pool *pool;
  4854. bool avail = false;
  4855. int tested, i, rpsave;
  4856. for (i = 0; i < total_pools; i++) {
  4857. struct pool *tp = pools[i];
  4858. if (tp->quota_used < tp->quota_gcd) {
  4859. avail = true;
  4860. break;
  4861. }
  4862. }
  4863. /* There are no pools with quota, so reset them. */
  4864. if (!avail) {
  4865. for (i = 0; i < total_pools; i++)
  4866. {
  4867. struct pool * const tp = pools[i];
  4868. tp->quota_used -= tp->quota_gcd;
  4869. }
  4870. if (++rotating_pool >= total_pools)
  4871. rotating_pool = 0;
  4872. }
  4873. /* Try to find the first pool in the rotation that is usable */
  4874. // Look for the lowest integer quota_used / quota_gcd in case we are imbalanced by algorithm demands
  4875. struct pool *pool_lowest = NULL;
  4876. int lowest = INT_MAX;
  4877. rpsave = rotating_pool;
  4878. for (tested = 0; tested < total_pools; ++tested)
  4879. {
  4880. pool = pools[rotating_pool];
  4881. if (malgo && pool->goal->malgo != malgo)
  4882. goto continue_tested;
  4883. if (pool->quota_used < pool->quota_gcd)
  4884. {
  4885. ++pool->quota_used;
  4886. if (!pool_unworkable(pool))
  4887. goto out;
  4888. /* Failover-only flag for load-balance means distribute
  4889. * unused quota to priority pool 0. */
  4890. if (opt_fail_only)
  4891. priority_pool(0)->quota_used--;
  4892. }
  4893. if (malgo)
  4894. {
  4895. const int count = pool->quota_used / pool->quota_gcd;
  4896. if (count < lowest)
  4897. {
  4898. pool_lowest = pool;
  4899. lowest = count;
  4900. }
  4901. }
  4902. continue_tested: ;
  4903. if (++rotating_pool >= total_pools)
  4904. rotating_pool = 0;
  4905. }
  4906. // Even if pool_lowest is NULL, we want to return that to indicate failure
  4907. // Note it isn't possible to get here if !malgo
  4908. pool = pool_lowest;
  4909. out: ;
  4910. // Restore rotating_pool static, so malgo searches don't affect the usual load balancing
  4911. if (malgo)
  4912. rotating_pool = rpsave;
  4913. return pool;
  4914. }
  4915. static
  4916. struct pool *select_failover(struct mining_algorithm * const malgo)
  4917. {
  4918. int i;
  4919. for (i = 0; i < total_pools; i++) {
  4920. struct pool *tp = priority_pool(i);
  4921. if (malgo && tp->goal->malgo != malgo)
  4922. continue;
  4923. if (!pool_unusable(tp)) {
  4924. return tp;
  4925. }
  4926. }
  4927. return NULL;
  4928. }
  4929. static bool pool_active(struct pool *, bool pinging);
  4930. static void pool_died(struct pool *);
  4931. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  4932. * it has any quota left. */
  4933. static inline struct pool *select_pool(bool lagging, struct mining_algorithm * const malgo)
  4934. {
  4935. struct pool *pool = NULL, *cp;
  4936. retry:
  4937. cp = current_pool();
  4938. if (pool_strategy == POOL_BALANCE) {
  4939. pool = select_balanced(cp, malgo);
  4940. if ((!pool) || pool_unworkable(pool))
  4941. goto simple_failover;
  4942. goto out;
  4943. }
  4944. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  4945. if (malgo && cp->goal->malgo != malgo)
  4946. goto simple_failover;
  4947. pool = cp;
  4948. goto out;
  4949. } else
  4950. pool = select_loadbalance(malgo);
  4951. simple_failover:
  4952. /* If there are no alive pools with quota, choose according to
  4953. * priority. */
  4954. if (!pool) {
  4955. pool = select_failover(malgo);
  4956. }
  4957. /* If still nothing is usable, use the current pool */
  4958. if (!pool)
  4959. {
  4960. if (malgo && cp->goal->malgo != malgo)
  4961. {
  4962. applog(LOG_DEBUG, "Failed to select pool for specific mining algorithm '%s'", malgo->name);
  4963. return NULL;
  4964. }
  4965. pool = cp;
  4966. }
  4967. out:
  4968. if (!pool_actively_in_use(pool, cp))
  4969. {
  4970. if (!pool_active(pool, false))
  4971. {
  4972. pool_died(pool);
  4973. goto retry;
  4974. }
  4975. pool_tclear(pool, &pool->idle);
  4976. }
  4977. applog(LOG_DEBUG, "Selecting pool %d for %s%swork", pool->pool_no, malgo ? malgo->name : "", malgo ? " " : "");
  4978. return pool;
  4979. }
  4980. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  4981. double target_diff(const unsigned char *target)
  4982. {
  4983. double targ = 0;
  4984. signed int i;
  4985. for (i = 31; i >= 0; --i)
  4986. targ = (targ * 0x100) + target[i];
  4987. return DIFFEXACTONE / (targ ?: 1);
  4988. }
  4989. /*
  4990. * Calculate the work share difficulty
  4991. */
  4992. static void calc_diff(struct work *work, int known)
  4993. {
  4994. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  4995. double difficulty;
  4996. if (!known) {
  4997. work->work_difficulty = target_diff(work->target);
  4998. } else
  4999. work->work_difficulty = known;
  5000. difficulty = work->work_difficulty;
  5001. pool_stats->last_diff = difficulty;
  5002. suffix_string(difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  5003. if (difficulty == pool_stats->min_diff)
  5004. pool_stats->min_diff_count++;
  5005. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  5006. pool_stats->min_diff = difficulty;
  5007. pool_stats->min_diff_count = 1;
  5008. }
  5009. if (difficulty == pool_stats->max_diff)
  5010. pool_stats->max_diff_count++;
  5011. else if (difficulty > pool_stats->max_diff) {
  5012. pool_stats->max_diff = difficulty;
  5013. pool_stats->max_diff_count = 1;
  5014. }
  5015. }
  5016. static void gen_stratum_work(struct pool *, struct work *);
  5017. static void pool_update_work_restart_time(struct pool *);
  5018. static void restart_threads(void);
  5019. static uint32_t benchmark_blkhdr[20];
  5020. static const int benchmark_update_interval = 1;
  5021. static
  5022. void *benchmark_intense_work_update_thread(void *userp)
  5023. {
  5024. pthread_detach(pthread_self());
  5025. RenameThread("benchmark-intense");
  5026. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5027. struct pool * const pool = userp;
  5028. struct stratum_work * const swork = &pool->swork;
  5029. uint8_t * const blkhdr = swork->header1;
  5030. while (true)
  5031. {
  5032. sleep(benchmark_update_interval);
  5033. cg_wlock(&pool->data_lock);
  5034. for (int i = 36; --i >= 0; )
  5035. if (++blkhdr[i])
  5036. break;
  5037. cg_wunlock(&pool->data_lock);
  5038. struct work *work = make_work();
  5039. gen_stratum_work(pool, work);
  5040. pool->swork.work_restart_id = ++pool->work_restart_id;
  5041. pool_update_work_restart_time(pool);
  5042. test_work_current(work);
  5043. free_work(work);
  5044. restart_threads();
  5045. }
  5046. return NULL;
  5047. }
  5048. static
  5049. void setup_benchmark_pool()
  5050. {
  5051. struct pool *pool;
  5052. want_longpoll = false;
  5053. // Temporarily disable opt_benchmark to avoid auto-removal
  5054. opt_benchmark = false;
  5055. pool = add_pool();
  5056. opt_benchmark = true;
  5057. pool->rpc_url = malloc(255);
  5058. strcpy(pool->rpc_url, "Benchmark");
  5059. pool_set_uri(pool, pool->rpc_url);
  5060. pool->rpc_user = pool->rpc_url;
  5061. pool->rpc_pass = pool->rpc_url;
  5062. enable_pool(pool);
  5063. pool->idle = false;
  5064. successful_connect = true;
  5065. {
  5066. uint32_t * const blkhdr = benchmark_blkhdr;
  5067. blkhdr[2] = htobe32(1);
  5068. blkhdr[17] = htobe32(0x7fffffff); // timestamp
  5069. blkhdr[18] = htobe32(0x1700ffff); // "bits"
  5070. }
  5071. {
  5072. struct stratum_work * const swork = &pool->swork;
  5073. const int branchcount = 15; // 1 MB block
  5074. const size_t branchdatasz = branchcount * 0x20;
  5075. const size_t coinbase_sz = (opt_benchmark_intense ? 250 : 6) * 1024;
  5076. bytes_resize(&swork->coinbase, coinbase_sz);
  5077. memset(bytes_buf(&swork->coinbase), '\xff', coinbase_sz);
  5078. swork->nonce2_offset = 0;
  5079. bytes_resize(&swork->merkle_bin, branchdatasz);
  5080. memset(bytes_buf(&swork->merkle_bin), '\xff', branchdatasz);
  5081. swork->merkles = branchcount;
  5082. swork->header1[0] = '\xff';
  5083. memset(&swork->header1[1], '\0', 34);
  5084. swork->header1[35] = '\x01';
  5085. swork->ntime = 0x7fffffff;
  5086. timer_unset(&swork->tv_received);
  5087. memcpy(swork->diffbits, "\x17\0\xff\xff", 4);
  5088. const struct mining_goal_info * const goal = get_mining_goal("default");
  5089. const struct mining_algorithm * const malgo = goal->malgo;
  5090. set_target_to_pdiff(swork->target, malgo->reasonable_low_nonce_diff);
  5091. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  5092. pool->nonce2 = 0;
  5093. }
  5094. if (opt_benchmark_intense)
  5095. {
  5096. pthread_t pth;
  5097. if (unlikely(pthread_create(&pth, NULL, benchmark_intense_work_update_thread, pool)))
  5098. applog(LOG_WARNING, "Failed to start benchmark intense work update thread");
  5099. }
  5100. }
  5101. void get_benchmark_work(struct work *work, bool use_swork)
  5102. {
  5103. if (use_swork)
  5104. {
  5105. struct timeval tv_now;
  5106. timer_set_now(&tv_now);
  5107. gen_stratum_work(pools[0], work);
  5108. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  5109. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  5110. return;
  5111. }
  5112. struct pool * const pool = pools[0];
  5113. uint32_t * const blkhdr = benchmark_blkhdr;
  5114. for (int i = 16; i >= 0; --i)
  5115. if (++blkhdr[i])
  5116. break;
  5117. memcpy(&work->data[ 0], blkhdr, 80);
  5118. memcpy(&work->data[80], workpadding_bin, 48);
  5119. char hex[161];
  5120. bin2hex(hex, work->data, 80);
  5121. applog(LOG_DEBUG, "Generated benchmark header %s", hex);
  5122. calc_midstate(work);
  5123. memcpy(work->target, pool->swork.target, sizeof(work->target));
  5124. work->mandatory = true;
  5125. work->pool = pools[0];
  5126. cgtime(&work->tv_getwork);
  5127. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  5128. copy_time(&work->tv_staged, &work->tv_getwork);
  5129. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  5130. calc_diff(work, 0);
  5131. work_set_simple_ntime_roll_limit(work, 60, &work->tv_getwork);
  5132. }
  5133. static void wake_gws(void);
  5134. static void update_last_work(struct work *work)
  5135. {
  5136. if (!work->tr)
  5137. // Only save GBT jobs, since rollntime isn't coordinated well yet
  5138. return;
  5139. struct pool *pool = work->pool;
  5140. mutex_lock(&pool->last_work_lock);
  5141. if (pool->last_work_copy)
  5142. free_work(pool->last_work_copy);
  5143. pool->last_work_copy = copy_work(work);
  5144. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  5145. mutex_unlock(&pool->last_work_lock);
  5146. }
  5147. static
  5148. void gbt_req_target(json_t *req)
  5149. {
  5150. json_t *j;
  5151. json_t *n;
  5152. if (!request_target_str)
  5153. return;
  5154. j = json_object_get(req, "params");
  5155. if (!j)
  5156. {
  5157. n = json_array();
  5158. if (!n)
  5159. return;
  5160. if (json_object_set_new(req, "params", n))
  5161. goto erradd;
  5162. j = n;
  5163. }
  5164. n = json_array_get(j, 0);
  5165. if (!n)
  5166. {
  5167. n = json_object();
  5168. if (!n)
  5169. return;
  5170. if (json_array_append_new(j, n))
  5171. goto erradd;
  5172. }
  5173. j = n;
  5174. n = json_string(request_target_str);
  5175. if (!n)
  5176. return;
  5177. if (json_object_set_new(j, "target", n))
  5178. goto erradd;
  5179. return;
  5180. erradd:
  5181. json_decref(n);
  5182. }
  5183. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe, struct pool * const pool)
  5184. {
  5185. char *rpc_req;
  5186. clean_work(work);
  5187. switch (proto) {
  5188. case PLP_GETWORK:
  5189. work->getwork_mode = GETWORK_MODE_POOL;
  5190. return strdup(getwork_req);
  5191. case PLP_GETBLOCKTEMPLATE:
  5192. work->getwork_mode = GETWORK_MODE_GBT;
  5193. blktemplate_t * const tmpl = blktmpl_create();
  5194. if (!tmpl)
  5195. goto gbtfail2;
  5196. work->tr = tmpl_makeref(tmpl);
  5197. gbt_capabilities_t caps = blktmpl_addcaps(tmpl);
  5198. if (!caps)
  5199. goto gbtfail;
  5200. caps |= GBT_LONGPOLL;
  5201. #if BLKMAKER_VERSION > 1
  5202. const struct mining_goal_info * const goal = pool->goal;
  5203. if (goal->generation_script || goal_has_at_least_one_getcbaddr(goal))
  5204. caps |= GBT_CBVALUE;
  5205. #endif
  5206. json_t *req = blktmpl_request_jansson(caps, lpid);
  5207. if (!req)
  5208. goto gbtfail;
  5209. if (probe)
  5210. gbt_req_target(req);
  5211. rpc_req = json_dumps(req, 0);
  5212. if (!rpc_req)
  5213. goto gbtfail;
  5214. json_decref(req);
  5215. return rpc_req;
  5216. default:
  5217. return NULL;
  5218. }
  5219. return NULL;
  5220. gbtfail:
  5221. tmpl_decref(work->tr);
  5222. work->tr = NULL;
  5223. gbtfail2:
  5224. return NULL;
  5225. }
  5226. #define prepare_rpc_req(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, false, pool)
  5227. #define prepare_rpc_req_probe(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, true, pool)
  5228. static const char *pool_protocol_name(enum pool_protocol proto)
  5229. {
  5230. switch (proto) {
  5231. case PLP_GETBLOCKTEMPLATE:
  5232. return "getblocktemplate";
  5233. case PLP_GETWORK:
  5234. return "getwork";
  5235. default:
  5236. return "UNKNOWN";
  5237. }
  5238. }
  5239. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  5240. {
  5241. switch (proto) {
  5242. case PLP_GETBLOCKTEMPLATE:
  5243. if (want_getwork)
  5244. return PLP_GETWORK;
  5245. default:
  5246. return PLP_NONE;
  5247. }
  5248. }
  5249. static bool get_upstream_work(struct work *work, CURL *curl)
  5250. {
  5251. struct pool *pool = work->pool;
  5252. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  5253. struct timeval tv_elapsed;
  5254. json_t *val = NULL;
  5255. bool rc = false;
  5256. char *url;
  5257. enum pool_protocol proto;
  5258. char *rpc_req;
  5259. if (pool->proto == PLP_NONE)
  5260. pool->proto = PLP_GETBLOCKTEMPLATE;
  5261. tryagain:
  5262. rpc_req = prepare_rpc_req(work, pool->proto, NULL, pool);
  5263. work->pool = pool;
  5264. if (!rpc_req)
  5265. return false;
  5266. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  5267. url = pool->rpc_url;
  5268. cgtime(&work->tv_getwork);
  5269. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  5270. false, &work->rolltime, pool, false);
  5271. pool_stats->getwork_attempts++;
  5272. free(rpc_req);
  5273. if (likely(val)) {
  5274. rc = work_decode(pool, work, val);
  5275. if (unlikely(!rc))
  5276. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  5277. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  5278. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  5279. pool->proto = proto;
  5280. goto tryagain;
  5281. } else
  5282. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  5283. cgtime(&work->tv_getwork_reply);
  5284. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  5285. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  5286. pool_stats->getwork_wait_rolling /= 1.63;
  5287. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  5288. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  5289. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  5290. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  5291. }
  5292. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  5293. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  5294. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  5295. }
  5296. pool_stats->getwork_calls++;
  5297. work->pool = pool;
  5298. work->longpoll = false;
  5299. calc_diff(work, 0);
  5300. total_getworks++;
  5301. pool->getwork_requested++;
  5302. if (rc)
  5303. update_last_work(work);
  5304. if (likely(val))
  5305. json_decref(val);
  5306. return rc;
  5307. }
  5308. #ifdef HAVE_CURSES
  5309. static void disable_curses(void)
  5310. {
  5311. if (curses_active_locked()) {
  5312. use_curses = false;
  5313. curses_active = false;
  5314. leaveok(logwin, false);
  5315. leaveok(statuswin, false);
  5316. leaveok(mainwin, false);
  5317. nocbreak();
  5318. echo();
  5319. delwin(logwin);
  5320. delwin(statuswin);
  5321. delwin(mainwin);
  5322. endwin();
  5323. #ifdef WIN32
  5324. // Move the cursor to after curses output.
  5325. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  5326. CONSOLE_SCREEN_BUFFER_INFO csbi;
  5327. COORD coord;
  5328. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  5329. coord.X = 0;
  5330. coord.Y = csbi.dwSize.Y - 1;
  5331. SetConsoleCursorPosition(hout, coord);
  5332. }
  5333. #endif
  5334. unlock_curses();
  5335. }
  5336. }
  5337. #endif
  5338. static void __kill_work(void)
  5339. {
  5340. struct cgpu_info *cgpu;
  5341. struct thr_info *thr;
  5342. int i;
  5343. if (!successful_connect)
  5344. return;
  5345. applog(LOG_INFO, "Received kill message");
  5346. shutting_down = true;
  5347. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  5348. notifier_wake(submit_waiting_notifier);
  5349. #ifdef USE_LIBMICROHTTPD
  5350. httpsrv_stop();
  5351. #endif
  5352. applog(LOG_DEBUG, "Killing off watchpool thread");
  5353. /* Kill the watchpool thread */
  5354. thr = &control_thr[watchpool_thr_id];
  5355. thr_info_cancel(thr);
  5356. applog(LOG_DEBUG, "Killing off watchdog thread");
  5357. /* Kill the watchdog thread */
  5358. thr = &control_thr[watchdog_thr_id];
  5359. thr_info_cancel(thr);
  5360. applog(LOG_DEBUG, "Shutting down mining threads");
  5361. for (i = 0; i < mining_threads; i++) {
  5362. thr = get_thread(i);
  5363. if (!thr)
  5364. continue;
  5365. cgpu = thr->cgpu;
  5366. if (!cgpu)
  5367. continue;
  5368. if (!cgpu->threads)
  5369. continue;
  5370. cgpu->shutdown = true;
  5371. thr->work_restart = true;
  5372. notifier_wake(thr->notifier);
  5373. notifier_wake(thr->work_restart_notifier);
  5374. }
  5375. sleep(1);
  5376. applog(LOG_DEBUG, "Killing off mining threads");
  5377. /* Kill the mining threads*/
  5378. for (i = 0; i < mining_threads; i++) {
  5379. thr = get_thread(i);
  5380. if (!thr)
  5381. continue;
  5382. cgpu = thr->cgpu;
  5383. if (cgpu->threads)
  5384. {
  5385. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  5386. thr_info_cancel(thr);
  5387. }
  5388. cgpu->status = LIFE_DEAD2;
  5389. }
  5390. /* Stop the others */
  5391. applog(LOG_DEBUG, "Killing off API thread");
  5392. thr = &control_thr[api_thr_id];
  5393. thr_info_cancel(thr);
  5394. }
  5395. /* This should be the common exit path */
  5396. void kill_work(void)
  5397. {
  5398. __kill_work();
  5399. quit(0, "Shutdown signal received.");
  5400. }
  5401. static
  5402. #ifdef WIN32
  5403. #ifndef _WIN64
  5404. const
  5405. #endif
  5406. #endif
  5407. char **initial_args;
  5408. void _bfg_clean_up(bool);
  5409. void app_restart(void)
  5410. {
  5411. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  5412. __kill_work();
  5413. _bfg_clean_up(true);
  5414. #if defined(unix) || defined(__APPLE__)
  5415. if (forkpid > 0) {
  5416. kill(forkpid, SIGTERM);
  5417. forkpid = 0;
  5418. }
  5419. #endif
  5420. execv(initial_args[0], initial_args);
  5421. applog(LOG_WARNING, "Failed to restart application");
  5422. }
  5423. static void sighandler(int __maybe_unused sig)
  5424. {
  5425. /* Restore signal handlers so we can still quit if kill_work fails */
  5426. sigaction(SIGTERM, &termhandler, NULL);
  5427. sigaction(SIGINT, &inthandler, NULL);
  5428. kill_work();
  5429. }
  5430. static void start_longpoll(void);
  5431. static void stop_longpoll(void);
  5432. /* Called with pool_lock held. Recruit an extra curl if none are available for
  5433. * this pool. */
  5434. static void recruit_curl(struct pool *pool)
  5435. {
  5436. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  5437. if (unlikely(!ce))
  5438. quit(1, "Failed to calloc in recruit_curl");
  5439. ce->curl = curl_easy_init();
  5440. if (unlikely(!ce->curl))
  5441. quit(1, "Failed to init in recruit_curl");
  5442. LL_PREPEND(pool->curllist, ce);
  5443. pool->curls++;
  5444. }
  5445. /* Grab an available curl if there is one. If not, then recruit extra curls
  5446. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  5447. * and there are already 5 curls in circulation. Limit total number to the
  5448. * number of mining threads per pool as well to prevent blasting a pool during
  5449. * network delays/outages. */
  5450. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  5451. {
  5452. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  5453. bool recruited = false;
  5454. struct curl_ent *ce;
  5455. mutex_lock(&pool->pool_lock);
  5456. retry:
  5457. if (!pool->curls) {
  5458. recruit_curl(pool);
  5459. recruited = true;
  5460. } else if (!pool->curllist) {
  5461. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  5462. if (!blocking) {
  5463. mutex_unlock(&pool->pool_lock);
  5464. return NULL;
  5465. }
  5466. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  5467. goto retry;
  5468. } else {
  5469. recruit_curl(pool);
  5470. recruited = true;
  5471. }
  5472. }
  5473. ce = pool->curllist;
  5474. LL_DELETE(pool->curllist, ce);
  5475. mutex_unlock(&pool->pool_lock);
  5476. if (recruited)
  5477. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  5478. return ce;
  5479. }
  5480. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  5481. {
  5482. return pop_curl_entry3(pool, blocking ? 1 : 0);
  5483. }
  5484. __maybe_unused
  5485. static struct curl_ent *pop_curl_entry(struct pool *pool)
  5486. {
  5487. return pop_curl_entry3(pool, 1);
  5488. }
  5489. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  5490. {
  5491. mutex_lock(&pool->pool_lock);
  5492. if (!ce || !ce->curl)
  5493. quithere(1, "Attempted to add NULL");
  5494. LL_PREPEND(pool->curllist, ce);
  5495. cgtime(&ce->tv);
  5496. pthread_cond_broadcast(&pool->cr_cond);
  5497. mutex_unlock(&pool->pool_lock);
  5498. }
  5499. bool stale_work(struct work *work, bool share);
  5500. static inline bool should_roll(struct work *work)
  5501. {
  5502. struct timeval now;
  5503. time_t expiry;
  5504. if (!pool_actively_in_use(work->pool, NULL))
  5505. return false;
  5506. if (stale_work(work, false))
  5507. return false;
  5508. if (work->rolltime > opt_scantime)
  5509. expiry = work->rolltime;
  5510. else
  5511. expiry = opt_scantime;
  5512. expiry = expiry * 2 / 3;
  5513. /* We shouldn't roll if we're unlikely to get one shares' duration
  5514. * work out of doing so */
  5515. cgtime(&now);
  5516. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  5517. return false;
  5518. return true;
  5519. }
  5520. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  5521. * reject blocks as invalid. */
  5522. static inline bool can_roll(struct work *work)
  5523. {
  5524. if (work->stratum)
  5525. return false;
  5526. if (!(work->pool && !work->clone))
  5527. return false;
  5528. if (work->tr)
  5529. {
  5530. if (stale_work(work, false))
  5531. return false;
  5532. return blkmk_work_left(work->tr->tmpl);
  5533. }
  5534. return (work->rolltime &&
  5535. work->rolls < 7000 && !stale_work(work, false));
  5536. }
  5537. static void roll_work(struct work *work)
  5538. {
  5539. if (work->tr)
  5540. {
  5541. struct timeval tv_now;
  5542. cgtime(&tv_now);
  5543. if (blkmk_get_data(work->tr->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  5544. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  5545. swap32yes(work->data, work->data, 80 / 4);
  5546. calc_midstate(work);
  5547. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  5548. } else {
  5549. uint32_t *work_ntime;
  5550. uint32_t ntime;
  5551. work_ntime = (uint32_t *)(work->data + 68);
  5552. ntime = be32toh(*work_ntime);
  5553. ntime++;
  5554. *work_ntime = htobe32(ntime);
  5555. work_set_simple_ntime_roll_limit(work, 0, &work->ntime_roll_limits.tv_ref);
  5556. applog(LOG_DEBUG, "Successfully rolled time header in work");
  5557. }
  5558. local_work++;
  5559. work->rolls++;
  5560. work->blk.nonce = 0;
  5561. /* This is now a different work item so it needs a different ID for the
  5562. * hashtable */
  5563. work->id = total_work++;
  5564. }
  5565. /* Duplicates any dynamically allocated arrays within the work struct to
  5566. * prevent a copied work struct from freeing ram belonging to another struct */
  5567. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  5568. {
  5569. int id = work->id;
  5570. clean_work(work);
  5571. memcpy(work, base_work, sizeof(struct work));
  5572. /* Keep the unique new id assigned during make_work to prevent copied
  5573. * work from having the same id. */
  5574. work->id = id;
  5575. if (base_work->job_id)
  5576. work->job_id = strdup(base_work->job_id);
  5577. if (base_work->nonce1)
  5578. work->nonce1 = strdup(base_work->nonce1);
  5579. bytes_cpy(&work->nonce2, &base_work->nonce2);
  5580. if (base_work->tr)
  5581. tmpl_incref(base_work->tr);
  5582. if (noffset)
  5583. {
  5584. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  5585. uint32_t ntime = be32toh(*work_ntime);
  5586. ntime += noffset;
  5587. *work_ntime = htobe32(ntime);
  5588. }
  5589. if (work->device_data_dup_func)
  5590. work->device_data = work->device_data_dup_func(work);
  5591. }
  5592. /* Generates a copy of an existing work struct, creating fresh heap allocations
  5593. * for all dynamically allocated arrays within the struct. noffset is used for
  5594. * when a driver has internally rolled the ntime, noffset is a relative value.
  5595. * The macro copy_work() calls this function with an noffset of 0. */
  5596. struct work *copy_work_noffset(const struct work *base_work, int noffset)
  5597. {
  5598. struct work *work = make_work();
  5599. _copy_work(work, base_work, noffset);
  5600. return work;
  5601. }
  5602. void __copy_work(struct work *work, const struct work *base_work)
  5603. {
  5604. _copy_work(work, base_work, 0);
  5605. }
  5606. static struct work *make_clone(struct work *work)
  5607. {
  5608. struct work *work_clone = copy_work(work);
  5609. work_clone->clone = true;
  5610. cgtime((struct timeval *)&(work_clone->tv_cloned));
  5611. work_clone->longpoll = false;
  5612. work_clone->mandatory = false;
  5613. /* Make cloned work appear slightly older to bias towards keeping the
  5614. * master work item which can be further rolled */
  5615. work_clone->tv_staged.tv_sec -= 1;
  5616. return work_clone;
  5617. }
  5618. static void stage_work(struct work *work);
  5619. static bool clone_available(void)
  5620. {
  5621. struct work *work_clone = NULL, *work, *tmp;
  5622. bool cloned = false;
  5623. mutex_lock(stgd_lock);
  5624. if (!staged_rollable)
  5625. goto out_unlock;
  5626. HASH_ITER(hh, staged_work, work, tmp) {
  5627. if (can_roll(work) && should_roll(work)) {
  5628. roll_work(work);
  5629. work_clone = make_clone(work);
  5630. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  5631. roll_work(work);
  5632. cloned = true;
  5633. break;
  5634. }
  5635. }
  5636. out_unlock:
  5637. mutex_unlock(stgd_lock);
  5638. if (cloned) {
  5639. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  5640. stage_work(work_clone);
  5641. }
  5642. return cloned;
  5643. }
  5644. static void pool_died(struct pool *pool)
  5645. {
  5646. mutex_lock(&lp_lock);
  5647. if (!pool_tset(pool, &pool->idle)) {
  5648. cgtime(&pool->tv_idle);
  5649. pthread_cond_broadcast(&lp_cond);
  5650. mutex_unlock(&lp_lock);
  5651. if (pool == current_pool()) {
  5652. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  5653. switch_pools(NULL);
  5654. } else
  5655. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  5656. }
  5657. else
  5658. mutex_unlock(&lp_lock);
  5659. }
  5660. bool stale_work(struct work *work, bool share)
  5661. {
  5662. unsigned work_expiry;
  5663. struct pool *pool;
  5664. uint32_t block_id;
  5665. unsigned getwork_delay;
  5666. block_id = ((uint32_t*)work->data)[1];
  5667. pool = work->pool;
  5668. struct mining_goal_info * const goal = pool->goal;
  5669. struct blockchain_info * const blkchain = goal->blkchain;
  5670. /* Technically the rolltime should be correct but some pools
  5671. * advertise a broken expire= that is lower than a meaningful
  5672. * scantime */
  5673. if (work->rolltime >= opt_scantime || work->tr)
  5674. work_expiry = work->rolltime;
  5675. else
  5676. work_expiry = opt_expiry;
  5677. unsigned max_expiry = (goal->have_longpoll ? opt_expiry_lp : opt_expiry);
  5678. if (work_expiry > max_expiry)
  5679. work_expiry = max_expiry;
  5680. if (share) {
  5681. /* If the share isn't on this pool's latest block, it's stale */
  5682. if (pool->block_id && pool->block_id != block_id)
  5683. {
  5684. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  5685. return true;
  5686. }
  5687. /* If the pool doesn't want old shares, then any found in work before
  5688. * the most recent longpoll is stale */
  5689. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  5690. {
  5691. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5692. return true;
  5693. }
  5694. } else {
  5695. /* If this work isn't for the latest Bitcoin block, it's stale */
  5696. /* But only care about the current pool if failover-only */
  5697. if (enabled_pools <= 1 || opt_fail_only) {
  5698. if (pool->block_id && block_id != pool->block_id)
  5699. {
  5700. 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);
  5701. return true;
  5702. }
  5703. } else {
  5704. if (block_id != blkchain->currentblk->block_id)
  5705. {
  5706. 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);
  5707. return true;
  5708. }
  5709. }
  5710. /* If the pool has asked us to restart since this work, it's stale */
  5711. if (work->work_restart_id != pool->work_restart_id)
  5712. {
  5713. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5714. return true;
  5715. }
  5716. if (pool->has_stratum && work->job_id) {
  5717. bool same_job;
  5718. if (!pool->stratum_active || !pool->stratum_notify) {
  5719. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  5720. return true;
  5721. }
  5722. same_job = true;
  5723. cg_rlock(&pool->data_lock);
  5724. if (strcmp(work->job_id, pool->swork.job_id))
  5725. same_job = false;
  5726. cg_runlock(&pool->data_lock);
  5727. if (!same_job) {
  5728. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  5729. return true;
  5730. }
  5731. }
  5732. /* Factor in the average getwork delay of this pool, rounding it up to
  5733. * the nearest second */
  5734. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  5735. if (unlikely(work_expiry <= getwork_delay + 5))
  5736. work_expiry = 5;
  5737. else
  5738. work_expiry -= getwork_delay;
  5739. }
  5740. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  5741. if (elapsed_since_staged > work_expiry) {
  5742. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  5743. return true;
  5744. }
  5745. /* If the user only wants strict failover, any work from a pool other than
  5746. * the current one is always considered stale */
  5747. if (opt_fail_only && !share && !work->mandatory && !pool_actively_in_use(pool, NULL))
  5748. {
  5749. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  5750. return true;
  5751. }
  5752. return false;
  5753. }
  5754. double share_diff(const struct work *work)
  5755. {
  5756. double ret;
  5757. bool new_best = false;
  5758. ret = target_diff(work->hash);
  5759. cg_wlock(&control_lock);
  5760. if (unlikely(ret > best_diff)) {
  5761. new_best = true;
  5762. best_diff = ret;
  5763. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5764. }
  5765. if (unlikely(ret > work->pool->best_diff))
  5766. work->pool->best_diff = ret;
  5767. cg_wunlock(&control_lock);
  5768. if (unlikely(new_best))
  5769. applog(LOG_INFO, "New best share: %s", best_share);
  5770. return ret;
  5771. }
  5772. static
  5773. void work_check_for_block(struct work * const work)
  5774. {
  5775. struct pool * const pool = work->pool;
  5776. struct mining_goal_info * const goal = pool->goal;
  5777. work->share_diff = share_diff(work);
  5778. if (unlikely(work->share_diff >= goal->current_diff)) {
  5779. work->block = true;
  5780. work->pool->solved++;
  5781. found_blocks++;
  5782. work->mandatory = true;
  5783. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  5784. }
  5785. }
  5786. static void submit_discard_share2(const char *reason, struct work *work)
  5787. {
  5788. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  5789. sharelog(reason, work);
  5790. mutex_lock(&stats_lock);
  5791. ++total_stale;
  5792. ++cgpu->stale;
  5793. ++(work->pool->stale_shares);
  5794. total_diff_stale += work->work_difficulty;
  5795. cgpu->diff_stale += work->work_difficulty;
  5796. work->pool->diff_stale += work->work_difficulty;
  5797. mutex_unlock(&stats_lock);
  5798. }
  5799. static void submit_discard_share(struct work *work)
  5800. {
  5801. submit_discard_share2("discard", work);
  5802. }
  5803. struct submit_work_state {
  5804. struct work *work;
  5805. bool resubmit;
  5806. struct curl_ent *ce;
  5807. int failures;
  5808. struct timeval tv_staleexpire;
  5809. char *s;
  5810. struct timeval tv_submit;
  5811. struct submit_work_state *next;
  5812. };
  5813. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  5814. {
  5815. long *p_timeout_us = userp;
  5816. const long max_ms = LONG_MAX / 1000;
  5817. if (max_ms < timeout_ms)
  5818. timeout_ms = max_ms;
  5819. *p_timeout_us = timeout_ms * 1000;
  5820. return 0;
  5821. }
  5822. static void sws_has_ce(struct submit_work_state *sws)
  5823. {
  5824. struct pool *pool = sws->work->pool;
  5825. sws->s = submit_upstream_work_request(sws->work);
  5826. cgtime(&sws->tv_submit);
  5827. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5828. }
  5829. static struct submit_work_state *begin_submission(struct work *work)
  5830. {
  5831. struct pool *pool;
  5832. struct submit_work_state *sws = NULL;
  5833. pool = work->pool;
  5834. sws = malloc(sizeof(*sws));
  5835. *sws = (struct submit_work_state){
  5836. .work = work,
  5837. };
  5838. work_check_for_block(work);
  5839. if (stale_work(work, true)) {
  5840. work->stale = true;
  5841. if (opt_submit_stale)
  5842. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  5843. else if (pool->submit_old)
  5844. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  5845. else {
  5846. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  5847. submit_discard_share(work);
  5848. goto out;
  5849. }
  5850. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5851. }
  5852. if (work->stratum) {
  5853. char *s;
  5854. s = malloc(1024);
  5855. sws->s = s;
  5856. } else {
  5857. /* submit solution to bitcoin via JSON-RPC */
  5858. sws->ce = pop_curl_entry2(pool, false);
  5859. if (sws->ce) {
  5860. sws_has_ce(sws);
  5861. } else {
  5862. sws->next = pool->sws_waiting_on_curl;
  5863. pool->sws_waiting_on_curl = sws;
  5864. if (sws->next)
  5865. applog(LOG_DEBUG, "submit_thread queuing submission");
  5866. else
  5867. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  5868. }
  5869. }
  5870. return sws;
  5871. out:
  5872. free(sws);
  5873. return NULL;
  5874. }
  5875. static bool retry_submission(struct submit_work_state *sws)
  5876. {
  5877. struct work *work = sws->work;
  5878. struct pool *pool = work->pool;
  5879. sws->resubmit = true;
  5880. if ((!work->stale) && stale_work(work, true)) {
  5881. work->stale = true;
  5882. if (opt_submit_stale)
  5883. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  5884. else if (pool->submit_old)
  5885. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  5886. else {
  5887. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  5888. submit_discard_share(work);
  5889. return false;
  5890. }
  5891. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5892. }
  5893. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  5894. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  5895. submit_discard_share(work);
  5896. return false;
  5897. }
  5898. else if (work->stale) {
  5899. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  5900. {
  5901. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  5902. submit_discard_share(work);
  5903. return false;
  5904. }
  5905. }
  5906. /* pause, then restart work-request loop */
  5907. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  5908. cgtime(&sws->tv_submit);
  5909. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5910. return true;
  5911. }
  5912. static void free_sws(struct submit_work_state *sws)
  5913. {
  5914. free(sws->s);
  5915. free_work(sws->work);
  5916. free(sws);
  5917. }
  5918. static void *submit_work_thread(__maybe_unused void *userdata)
  5919. {
  5920. int wip = 0;
  5921. CURLM *curlm;
  5922. long curlm_timeout_us = -1;
  5923. struct timeval curlm_timer;
  5924. struct submit_work_state *sws, **swsp;
  5925. struct submit_work_state *write_sws = NULL;
  5926. unsigned tsreduce = 0;
  5927. pthread_detach(pthread_self());
  5928. RenameThread("submit_work");
  5929. applog(LOG_DEBUG, "Creating extra submit work thread");
  5930. curlm = curl_multi_init();
  5931. curlm_timeout_us = -1;
  5932. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  5933. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  5934. fd_set rfds, wfds, efds;
  5935. int maxfd;
  5936. struct timeval tv_timeout, tv_now;
  5937. int n;
  5938. CURLMsg *cm;
  5939. FD_ZERO(&rfds);
  5940. while (1) {
  5941. mutex_lock(&submitting_lock);
  5942. total_submitting -= tsreduce;
  5943. tsreduce = 0;
  5944. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  5945. notifier_read(submit_waiting_notifier);
  5946. }
  5947. // Receive any new submissions
  5948. while (submit_waiting) {
  5949. struct work *work = submit_waiting;
  5950. DL_DELETE(submit_waiting, work);
  5951. if ( (sws = begin_submission(work)) ) {
  5952. if (sws->ce)
  5953. curl_multi_add_handle(curlm, sws->ce->curl);
  5954. else if (sws->s) {
  5955. sws->next = write_sws;
  5956. write_sws = sws;
  5957. }
  5958. ++wip;
  5959. }
  5960. else {
  5961. --total_submitting;
  5962. free_work(work);
  5963. }
  5964. }
  5965. if (unlikely(shutting_down && !wip))
  5966. break;
  5967. mutex_unlock(&submitting_lock);
  5968. FD_ZERO(&rfds);
  5969. FD_ZERO(&wfds);
  5970. FD_ZERO(&efds);
  5971. tv_timeout.tv_sec = -1;
  5972. // Setup cURL with select
  5973. // Need to call perform to ensure the timeout gets updated
  5974. curl_multi_perform(curlm, &n);
  5975. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  5976. if (curlm_timeout_us >= 0)
  5977. {
  5978. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  5979. reduce_timeout_to(&tv_timeout, &curlm_timer);
  5980. }
  5981. // Setup waiting stratum submissions with select
  5982. for (sws = write_sws; sws; sws = sws->next)
  5983. {
  5984. struct pool *pool = sws->work->pool;
  5985. int fd = pool->sock;
  5986. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  5987. continue;
  5988. FD_SET(fd, &wfds);
  5989. set_maxfd(&maxfd, fd);
  5990. }
  5991. // Setup "submit waiting" notifier with select
  5992. FD_SET(submit_waiting_notifier[0], &rfds);
  5993. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  5994. // Wait for something interesting to happen :)
  5995. cgtime(&tv_now);
  5996. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  5997. FD_ZERO(&rfds);
  5998. continue;
  5999. }
  6000. // Handle any stratum ready-to-write results
  6001. for (swsp = &write_sws; (sws = *swsp); ) {
  6002. struct work *work = sws->work;
  6003. struct pool *pool = work->pool;
  6004. int fd = pool->sock;
  6005. bool sessionid_match;
  6006. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  6007. next_write_sws:
  6008. // TODO: Check if stale, possibly discard etc
  6009. swsp = &sws->next;
  6010. continue;
  6011. }
  6012. cg_rlock(&pool->data_lock);
  6013. // 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
  6014. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  6015. sessionid_match = (!pool->swork.nonce1) || !strcmp(work->nonce1, pool->swork.nonce1);
  6016. cg_runlock(&pool->data_lock);
  6017. if (!sessionid_match)
  6018. {
  6019. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  6020. submit_discard_share2("disconnect", work);
  6021. ++tsreduce;
  6022. next_write_sws_del:
  6023. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  6024. FD_CLR(fd, &wfds);
  6025. // Delete sws for this submission, since we're done with it
  6026. *swsp = sws->next;
  6027. free_sws(sws);
  6028. --wip;
  6029. continue;
  6030. }
  6031. char *s = sws->s;
  6032. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  6033. int sshare_id;
  6034. uint32_t nonce;
  6035. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  6036. char noncehex[9];
  6037. char ntimehex[9];
  6038. sshare->work = copy_work(work);
  6039. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  6040. nonce = *((uint32_t *)(work->data + 76));
  6041. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  6042. bin2hex(ntimehex, (void *)&work->data[68], 4);
  6043. mutex_lock(&sshare_lock);
  6044. /* Give the stratum share a unique id */
  6045. sshare_id =
  6046. sshare->id = swork_id++;
  6047. HASH_ADD_INT(stratum_shares, id, sshare);
  6048. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  6049. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  6050. mutex_unlock(&sshare_lock);
  6051. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  6052. if (likely(stratum_send(pool, s, strlen(s)))) {
  6053. if (pool_tclear(pool, &pool->submit_fail))
  6054. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  6055. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  6056. goto next_write_sws_del;
  6057. } else if (!pool_tset(pool, &pool->submit_fail)) {
  6058. // Undo stuff
  6059. mutex_lock(&sshare_lock);
  6060. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  6061. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  6062. if (sshare)
  6063. HASH_DEL(stratum_shares, sshare);
  6064. mutex_unlock(&sshare_lock);
  6065. if (sshare)
  6066. {
  6067. free_work(sshare->work);
  6068. free(sshare);
  6069. }
  6070. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  6071. total_ro++;
  6072. pool->remotefail_occasions++;
  6073. if (!sshare)
  6074. goto next_write_sws_del;
  6075. goto next_write_sws;
  6076. }
  6077. }
  6078. // Handle any cURL activities
  6079. curl_multi_perform(curlm, &n);
  6080. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  6081. if (cm->msg == CURLMSG_DONE)
  6082. {
  6083. bool finished;
  6084. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  6085. curl_multi_remove_handle(curlm, cm->easy_handle);
  6086. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  6087. if (!finished) {
  6088. if (retry_submission(sws))
  6089. curl_multi_add_handle(curlm, sws->ce->curl);
  6090. else
  6091. finished = true;
  6092. }
  6093. if (finished) {
  6094. --wip;
  6095. ++tsreduce;
  6096. struct pool *pool = sws->work->pool;
  6097. if (pool->sws_waiting_on_curl) {
  6098. pool->sws_waiting_on_curl->ce = sws->ce;
  6099. sws_has_ce(pool->sws_waiting_on_curl);
  6100. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  6101. curl_multi_add_handle(curlm, sws->ce->curl);
  6102. } else {
  6103. push_curl_entry(sws->ce, sws->work->pool);
  6104. }
  6105. free_sws(sws);
  6106. }
  6107. }
  6108. }
  6109. }
  6110. assert(!write_sws);
  6111. mutex_unlock(&submitting_lock);
  6112. curl_multi_cleanup(curlm);
  6113. applog(LOG_DEBUG, "submit_work thread exiting");
  6114. return NULL;
  6115. }
  6116. /* Find the pool that currently has the highest priority */
  6117. static struct pool *priority_pool(int choice)
  6118. {
  6119. struct pool *ret = NULL;
  6120. int i;
  6121. for (i = 0; i < total_pools; i++) {
  6122. struct pool *pool = pools[i];
  6123. if (pool->prio == choice) {
  6124. ret = pool;
  6125. break;
  6126. }
  6127. }
  6128. if (unlikely(!ret)) {
  6129. applog(LOG_ERR, "WTF No pool %d found!", choice);
  6130. return pools[choice];
  6131. }
  6132. return ret;
  6133. }
  6134. int prioritize_pools(char *param, int *pid)
  6135. {
  6136. char *ptr, *next;
  6137. int i, pr, prio = 0;
  6138. if (total_pools == 0) {
  6139. return MSG_NOPOOL;
  6140. }
  6141. if (param == NULL || *param == '\0') {
  6142. return MSG_MISPID;
  6143. }
  6144. bool pools_changed[total_pools];
  6145. int new_prio[total_pools];
  6146. for (i = 0; i < total_pools; ++i)
  6147. pools_changed[i] = false;
  6148. next = param;
  6149. while (next && *next) {
  6150. ptr = next;
  6151. next = strchr(ptr, ',');
  6152. if (next)
  6153. *(next++) = '\0';
  6154. i = atoi(ptr);
  6155. if (i < 0 || i >= total_pools) {
  6156. *pid = i;
  6157. return MSG_INVPID;
  6158. }
  6159. if (pools_changed[i]) {
  6160. *pid = i;
  6161. return MSG_DUPPID;
  6162. }
  6163. pools_changed[i] = true;
  6164. new_prio[i] = prio++;
  6165. }
  6166. // Only change them if no errors
  6167. for (i = 0; i < total_pools; i++) {
  6168. if (pools_changed[i])
  6169. pools[i]->prio = new_prio[i];
  6170. }
  6171. // In priority order, cycle through the unchanged pools and append them
  6172. for (pr = 0; pr < total_pools; pr++)
  6173. for (i = 0; i < total_pools; i++) {
  6174. if (!pools_changed[i] && pools[i]->prio == pr) {
  6175. pools[i]->prio = prio++;
  6176. pools_changed[i] = true;
  6177. break;
  6178. }
  6179. }
  6180. if (current_pool()->prio)
  6181. switch_pools(NULL);
  6182. return MSG_POOLPRIO;
  6183. }
  6184. void validate_pool_priorities(void)
  6185. {
  6186. // TODO: this should probably do some sort of logging
  6187. int i, j;
  6188. bool used[total_pools];
  6189. bool valid[total_pools];
  6190. for (i = 0; i < total_pools; i++)
  6191. used[i] = valid[i] = false;
  6192. for (i = 0; i < total_pools; i++) {
  6193. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  6194. if (!used[pools[i]->prio]) {
  6195. valid[i] = true;
  6196. used[pools[i]->prio] = true;
  6197. }
  6198. }
  6199. }
  6200. for (i = 0; i < total_pools; i++) {
  6201. if (!valid[i]) {
  6202. for (j = 0; j < total_pools; j++) {
  6203. if (!used[j]) {
  6204. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  6205. pools[i]->prio = j;
  6206. used[j] = true;
  6207. break;
  6208. }
  6209. }
  6210. }
  6211. }
  6212. }
  6213. static void clear_pool_work(struct pool *pool);
  6214. /* Specifies whether we can switch to this pool or not. */
  6215. static bool pool_unusable(struct pool *pool)
  6216. {
  6217. if (pool->idle)
  6218. return true;
  6219. if (pool->enabled != POOL_ENABLED)
  6220. return true;
  6221. return false;
  6222. }
  6223. void switch_pools(struct pool *selected)
  6224. {
  6225. struct pool *pool, *last_pool, *failover_pool = NULL;
  6226. int i, pool_no, next_pool;
  6227. if (selected)
  6228. enable_pool(selected);
  6229. cg_wlock(&control_lock);
  6230. last_pool = currentpool;
  6231. pool_no = currentpool->pool_no;
  6232. /* Switch selected to pool number 0 and move the rest down */
  6233. if (selected) {
  6234. if (selected->prio != 0) {
  6235. for (i = 0; i < total_pools; i++) {
  6236. pool = pools[i];
  6237. if (pool->prio < selected->prio)
  6238. pool->prio++;
  6239. }
  6240. selected->prio = 0;
  6241. }
  6242. }
  6243. switch (pool_strategy) {
  6244. /* All of these set to the master pool */
  6245. case POOL_BALANCE:
  6246. case POOL_FAILOVER:
  6247. case POOL_LOADBALANCE:
  6248. for (i = 0; i < total_pools; i++) {
  6249. pool = priority_pool(i);
  6250. if (pool_unusable(pool))
  6251. continue;
  6252. pool_no = pool->pool_no;
  6253. break;
  6254. }
  6255. break;
  6256. /* Both of these simply increment and cycle */
  6257. case POOL_ROUNDROBIN:
  6258. case POOL_ROTATE:
  6259. if (selected && !selected->idle) {
  6260. pool_no = selected->pool_no;
  6261. break;
  6262. }
  6263. next_pool = pool_no;
  6264. /* Select the next alive pool */
  6265. for (i = 1; i < total_pools; i++) {
  6266. next_pool++;
  6267. if (next_pool >= total_pools)
  6268. next_pool = 0;
  6269. pool = pools[next_pool];
  6270. if (pool_unusable(pool))
  6271. continue;
  6272. if (pool->failover_only)
  6273. {
  6274. BFGINIT(failover_pool, pool);
  6275. continue;
  6276. }
  6277. pool_no = next_pool;
  6278. break;
  6279. }
  6280. break;
  6281. default:
  6282. break;
  6283. }
  6284. pool = pools[pool_no];
  6285. if (pool_unusable(pool) && failover_pool)
  6286. pool = failover_pool;
  6287. currentpool = pool;
  6288. cg_wunlock(&control_lock);
  6289. mutex_lock(&lp_lock);
  6290. pthread_cond_broadcast(&lp_cond);
  6291. mutex_unlock(&lp_lock);
  6292. /* Set the lagging flag to avoid pool not providing work fast enough
  6293. * messages in failover only mode since we have to get all fresh work
  6294. * as in restart_threads */
  6295. if (opt_fail_only)
  6296. pool_tset(pool, &pool->lagging);
  6297. if (pool != last_pool)
  6298. {
  6299. pool->block_id = 0;
  6300. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  6301. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  6302. if (pool_localgen(pool) || opt_fail_only)
  6303. clear_pool_work(last_pool);
  6304. }
  6305. }
  6306. mutex_lock(&lp_lock);
  6307. pthread_cond_broadcast(&lp_cond);
  6308. mutex_unlock(&lp_lock);
  6309. #ifdef HAVE_CURSES
  6310. update_block_display();
  6311. #endif
  6312. }
  6313. static void discard_work(struct work *work)
  6314. {
  6315. if (!work->clone && !work->rolls && !work->mined) {
  6316. if (work->pool) {
  6317. work->pool->discarded_work++;
  6318. work->pool->quota_used--;
  6319. work->pool->works--;
  6320. }
  6321. total_discarded++;
  6322. applog(LOG_DEBUG, "Discarded work");
  6323. } else
  6324. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  6325. free_work(work);
  6326. }
  6327. static bool work_rollable(struct work *);
  6328. static
  6329. void unstage_work(struct work * const work)
  6330. {
  6331. HASH_DEL(staged_work, work);
  6332. --work_mining_algorithm(work)->staged;
  6333. if (work_rollable(work))
  6334. --staged_rollable;
  6335. if (work->spare)
  6336. --staged_spare;
  6337. staged_full = false;
  6338. }
  6339. static void wake_gws(void)
  6340. {
  6341. mutex_lock(stgd_lock);
  6342. pthread_cond_signal(&gws_cond);
  6343. mutex_unlock(stgd_lock);
  6344. }
  6345. static void discard_stale(void)
  6346. {
  6347. struct work *work, *tmp;
  6348. int stale = 0;
  6349. mutex_lock(stgd_lock);
  6350. HASH_ITER(hh, staged_work, work, tmp) {
  6351. if (stale_work(work, false)) {
  6352. unstage_work(work);
  6353. discard_work(work);
  6354. stale++;
  6355. }
  6356. }
  6357. pthread_cond_signal(&gws_cond);
  6358. mutex_unlock(stgd_lock);
  6359. if (stale)
  6360. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  6361. }
  6362. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  6363. {
  6364. bool rv;
  6365. struct timeval tv, orig;
  6366. ldiv_t d;
  6367. d = ldiv(ustime, 1000000);
  6368. tv = (struct timeval){
  6369. .tv_sec = d.quot,
  6370. .tv_usec = d.rem,
  6371. };
  6372. orig = work->tv_staged;
  6373. timersub(&orig, &tv, &work->tv_staged);
  6374. rv = stale_work(work, share);
  6375. work->tv_staged = orig;
  6376. return rv;
  6377. }
  6378. static
  6379. void pool_update_work_restart_time(struct pool * const pool)
  6380. {
  6381. pool->work_restart_time = time(NULL);
  6382. get_timestamp(pool->work_restart_timestamp, sizeof(pool->work_restart_timestamp), pool->work_restart_time);
  6383. }
  6384. static void restart_threads(void)
  6385. {
  6386. struct pool *cp = current_pool();
  6387. int i;
  6388. struct thr_info *thr;
  6389. /* Artificially set the lagging flag to avoid pool not providing work
  6390. * fast enough messages after every long poll */
  6391. pool_tset(cp, &cp->lagging);
  6392. /* Discard staged work that is now stale */
  6393. discard_stale();
  6394. rd_lock(&mining_thr_lock);
  6395. for (i = 0; i < mining_threads; i++)
  6396. {
  6397. thr = mining_thr[i];
  6398. thr->work_restart = true;
  6399. }
  6400. for (i = 0; i < mining_threads; i++)
  6401. {
  6402. thr = mining_thr[i];
  6403. notifier_wake(thr->work_restart_notifier);
  6404. }
  6405. rd_unlock(&mining_thr_lock);
  6406. }
  6407. void blkhashstr(char *rv, const unsigned char *hash)
  6408. {
  6409. unsigned char hash_swap[32];
  6410. swap256(hash_swap, hash);
  6411. swap32tole(hash_swap, hash_swap, 32 / 4);
  6412. bin2hex(rv, hash_swap, 32);
  6413. }
  6414. static
  6415. void set_curblock(struct mining_goal_info * const goal, struct block_info * const blkinfo)
  6416. {
  6417. struct blockchain_info * const blkchain = goal->blkchain;
  6418. blkchain->currentblk = blkinfo;
  6419. blkchain->currentblk_subsidy = 5000000000LL >> (blkinfo->height / 210000);
  6420. cg_wlock(&ch_lock);
  6421. __update_block_title(goal);
  6422. get_timestamp(blkchain->currentblk_first_seen_time_str, sizeof(blkchain->currentblk_first_seen_time_str), blkinfo->first_seen_time);
  6423. cg_wunlock(&ch_lock);
  6424. applog(LOG_INFO, "New block: %s diff %s (%s)", goal->current_goal_detail, goal->current_diff_str, goal->net_hashrate);
  6425. }
  6426. /* Search to see if this prevblkhash has been seen before */
  6427. static
  6428. struct block_info *block_exists(const struct blockchain_info * const blkchain, const void * const prevblkhash)
  6429. {
  6430. struct block_info *s;
  6431. rd_lock(&blk_lock);
  6432. HASH_FIND(hh, blkchain->blocks, prevblkhash, 0x20, s);
  6433. rd_unlock(&blk_lock);
  6434. return s;
  6435. }
  6436. static int block_sort(struct block_info * const blocka, struct block_info * const blockb)
  6437. {
  6438. return blocka->block_seen_order - blockb->block_seen_order;
  6439. }
  6440. static
  6441. void set_blockdiff(struct mining_goal_info * const goal, const struct work * const work)
  6442. {
  6443. unsigned char target[32];
  6444. double diff;
  6445. uint64_t diff64;
  6446. real_block_target(target, work->data);
  6447. diff = target_diff(target);
  6448. diff64 = diff;
  6449. suffix_string(diff64, goal->current_diff_str, sizeof(goal->current_diff_str), 0);
  6450. format_unit2(goal->net_hashrate, sizeof(goal->net_hashrate),
  6451. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  6452. if (unlikely(goal->current_diff != diff))
  6453. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", goal->current_diff_str, goal->net_hashrate);
  6454. goal->current_diff = diff;
  6455. }
  6456. static bool test_work_current(struct work *work)
  6457. {
  6458. bool ret = true;
  6459. if (work->mandatory)
  6460. return ret;
  6461. uint32_t block_id = ((uint32_t*)(work->data))[1];
  6462. const uint8_t * const prevblkhash = &work->data[4];
  6463. {
  6464. /* Hack to work around dud work sneaking into test */
  6465. bool dudwork = true;
  6466. for (int i = 8; i < 26; ++i)
  6467. if (work->data[i])
  6468. {
  6469. dudwork = false;
  6470. break;
  6471. }
  6472. if (dudwork)
  6473. goto out_free;
  6474. }
  6475. struct pool * const pool = work->pool;
  6476. struct mining_goal_info * const goal = pool->goal;
  6477. struct blockchain_info * const blkchain = goal->blkchain;
  6478. /* Search to see if this block exists yet and if not, consider it a
  6479. * new block and set the current block details to this one */
  6480. if (!block_exists(blkchain, prevblkhash))
  6481. {
  6482. struct block_info * const s = calloc(sizeof(struct block_info), 1);
  6483. int deleted_block = 0;
  6484. ret = false;
  6485. if (unlikely(!s))
  6486. quit (1, "test_work_current OOM");
  6487. memcpy(s->prevblkhash, prevblkhash, sizeof(s->prevblkhash));
  6488. s->block_id = block_id;
  6489. s->block_seen_order = new_blocks++;
  6490. s->first_seen_time = time(NULL);
  6491. wr_lock(&blk_lock);
  6492. /* Only keep the last hour's worth of blocks in memory since
  6493. * work from blocks before this is virtually impossible and we
  6494. * want to prevent memory usage from continually rising */
  6495. if (HASH_COUNT(blkchain->blocks) > 6)
  6496. {
  6497. struct block_info *oldblock;
  6498. HASH_SORT(blkchain->blocks, block_sort);
  6499. oldblock = blkchain->blocks;
  6500. deleted_block = oldblock->block_seen_order;
  6501. HASH_DEL(blkchain->blocks, oldblock);
  6502. free(oldblock);
  6503. }
  6504. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(s->prevblkhash), s);
  6505. set_blockdiff(goal, work);
  6506. wr_unlock(&blk_lock);
  6507. pool->block_id = block_id;
  6508. pool_update_work_restart_time(pool);
  6509. if (deleted_block)
  6510. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  6511. #if BLKMAKER_VERSION > 1
  6512. template_nonce = 0;
  6513. #endif
  6514. set_curblock(goal, s);
  6515. if (unlikely(new_blocks == 1))
  6516. goto out_free;
  6517. if (!work->stratum)
  6518. {
  6519. if (work->longpoll)
  6520. {
  6521. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  6522. pool->pool_no);
  6523. }
  6524. else
  6525. if (goal->have_longpoll)
  6526. applog(LOG_NOTICE, "New block detected on network before longpoll");
  6527. else
  6528. applog(LOG_NOTICE, "New block detected on network");
  6529. }
  6530. restart_threads();
  6531. }
  6532. else
  6533. {
  6534. bool restart = false;
  6535. if (unlikely(pool->block_id != block_id))
  6536. {
  6537. bool was_active = pool->block_id != 0;
  6538. pool->block_id = block_id;
  6539. pool_update_work_restart_time(pool);
  6540. if (!work->longpoll)
  6541. update_last_work(work);
  6542. if (was_active)
  6543. {
  6544. // Pool actively changed block
  6545. if (pool == current_pool())
  6546. restart = true;
  6547. if (block_id == blkchain->currentblk->block_id)
  6548. {
  6549. // Caught up, only announce if this pool is the one in use
  6550. if (restart)
  6551. applog(LOG_NOTICE, "%s %d caught up to new block",
  6552. work->longpoll ? "Longpoll from pool" : "Pool",
  6553. pool->pool_no);
  6554. }
  6555. else
  6556. {
  6557. // Switched to a block we know, but not the latest... why?
  6558. // This might detect pools trying to double-spend or 51%,
  6559. // but let's not make any accusations until it's had time
  6560. // in the real world.
  6561. char hexstr[65];
  6562. blkhashstr(hexstr, prevblkhash);
  6563. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  6564. work->longpoll ? "Longpoll from pool" : "Pool",
  6565. pool->pool_no,
  6566. hexstr);
  6567. }
  6568. }
  6569. }
  6570. if (work->longpoll)
  6571. {
  6572. struct pool * const cp = current_pool();
  6573. ++pool->work_restart_id;
  6574. if (work->tr && work->tr == pool->swork.tr)
  6575. pool->swork.work_restart_id = pool->work_restart_id;
  6576. update_last_work(work);
  6577. pool_update_work_restart_time(pool);
  6578. applog(
  6579. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  6580. "Longpoll from pool %d requested work update",
  6581. pool->pool_no);
  6582. if ((!restart) && pool == cp)
  6583. restart = true;
  6584. }
  6585. if (restart)
  6586. restart_threads();
  6587. }
  6588. work->longpoll = false;
  6589. out_free:
  6590. return ret;
  6591. }
  6592. static int tv_sort(struct work *worka, struct work *workb)
  6593. {
  6594. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  6595. }
  6596. static bool work_rollable(struct work *work)
  6597. {
  6598. return (!work->clone && work->rolltime);
  6599. }
  6600. static bool hash_push(struct work *work)
  6601. {
  6602. bool rc = true;
  6603. mutex_lock(stgd_lock);
  6604. if (work_rollable(work))
  6605. staged_rollable++;
  6606. ++work_mining_algorithm(work)->staged;
  6607. if (work->spare)
  6608. ++staged_spare;
  6609. if (likely(!getq->frozen)) {
  6610. HASH_ADD_INT(staged_work, id, work);
  6611. HASH_SORT(staged_work, tv_sort);
  6612. } else
  6613. rc = false;
  6614. pthread_cond_broadcast(&getq->cond);
  6615. mutex_unlock(stgd_lock);
  6616. return rc;
  6617. }
  6618. static void stage_work(struct work *work)
  6619. {
  6620. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  6621. work->id, work->pool->pool_no);
  6622. work->work_restart_id = work->pool->work_restart_id;
  6623. work->pool->last_work_time = time(NULL);
  6624. cgtime(&work->pool->tv_last_work_time);
  6625. test_work_current(work);
  6626. work->pool->works++;
  6627. hash_push(work);
  6628. }
  6629. #ifdef HAVE_CURSES
  6630. int curses_int(const char *query)
  6631. {
  6632. int ret;
  6633. char *cvar;
  6634. cvar = curses_input(query);
  6635. if (unlikely(!cvar))
  6636. return -1;
  6637. ret = atoi(cvar);
  6638. free(cvar);
  6639. return ret;
  6640. }
  6641. #endif
  6642. #ifdef HAVE_CURSES
  6643. static bool input_pool(bool live);
  6644. #endif
  6645. #ifdef HAVE_CURSES
  6646. static void display_pool_summary(struct pool *pool)
  6647. {
  6648. double efficiency = 0.0;
  6649. char xfer[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+4+1], bw[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+6+1];
  6650. int pool_secs;
  6651. if (curses_active_locked()) {
  6652. wlog("Pool: %s Goal: %s\n", pool->rpc_url, pool->goal->name);
  6653. if (pool->solved)
  6654. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  6655. if (!pool->has_stratum)
  6656. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  6657. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  6658. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  6659. wlog(" Accepted shares: %d\n", pool->accepted);
  6660. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  6661. pool->rejected, pool->stale_shares,
  6662. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  6663. );
  6664. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  6665. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  6666. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  6667. wlog(" Network transfer: %s (%s)\n",
  6668. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  6669. (float)pool->cgminer_pool_stats.net_bytes_received,
  6670. (float)pool->cgminer_pool_stats.net_bytes_sent),
  6671. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  6672. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  6673. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  6674. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  6675. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  6676. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  6677. wlog(" Items worked on: %d\n", pool->works);
  6678. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  6679. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  6680. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  6681. unlock_curses();
  6682. }
  6683. }
  6684. #endif
  6685. /* We can't remove the memory used for this struct pool because there may
  6686. * still be work referencing it. We just remove it from the pools list */
  6687. void remove_pool(struct pool *pool)
  6688. {
  6689. int i, last_pool = total_pools - 1;
  6690. struct pool *other;
  6691. disable_pool(pool, POOL_DISABLED);
  6692. /* Boost priority of any lower prio than this one */
  6693. for (i = 0; i < total_pools; i++) {
  6694. other = pools[i];
  6695. if (other->prio > pool->prio)
  6696. other->prio--;
  6697. }
  6698. if (pool->pool_no < last_pool) {
  6699. /* Swap the last pool for this one */
  6700. (pools[last_pool])->pool_no = pool->pool_no;
  6701. pools[pool->pool_no] = pools[last_pool];
  6702. }
  6703. /* Give it an invalid number */
  6704. pool->pool_no = total_pools;
  6705. pool->removed = true;
  6706. pool->has_stratum = false;
  6707. total_pools--;
  6708. }
  6709. /* add a mutex if this needs to be thread safe in the future */
  6710. static struct JE {
  6711. char *buf;
  6712. struct JE *next;
  6713. } *jedata = NULL;
  6714. static void json_escape_free()
  6715. {
  6716. struct JE *jeptr = jedata;
  6717. struct JE *jenext;
  6718. jedata = NULL;
  6719. while (jeptr) {
  6720. jenext = jeptr->next;
  6721. free(jeptr->buf);
  6722. free(jeptr);
  6723. jeptr = jenext;
  6724. }
  6725. }
  6726. static
  6727. char *json_escape(const char *str)
  6728. {
  6729. struct JE *jeptr;
  6730. char *buf, *ptr;
  6731. /* 2x is the max, may as well just allocate that */
  6732. ptr = buf = malloc(strlen(str) * 2 + 1);
  6733. jeptr = malloc(sizeof(*jeptr));
  6734. jeptr->buf = buf;
  6735. jeptr->next = jedata;
  6736. jedata = jeptr;
  6737. while (*str) {
  6738. if (*str == '\\' || *str == '"')
  6739. *(ptr++) = '\\';
  6740. *(ptr++) = *(str++);
  6741. }
  6742. *ptr = '\0';
  6743. return buf;
  6744. }
  6745. static
  6746. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  6747. {
  6748. if (!elist)
  6749. return;
  6750. static struct string_elist *entry;
  6751. fprintf(fcfg, ",\n\"%s\" : [", configname);
  6752. bool first = true;
  6753. DL_FOREACH(elist, entry)
  6754. {
  6755. const char * const s = entry->string;
  6756. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  6757. first = false;
  6758. }
  6759. fprintf(fcfg, "\n]");
  6760. }
  6761. void write_config(FILE *fcfg)
  6762. {
  6763. int i;
  6764. /* Write pool values */
  6765. fputs("{\n\"pools\" : [", fcfg);
  6766. for(i = 0; i < total_pools; i++) {
  6767. struct pool *pool = pools[i];
  6768. if (pool->failover_only)
  6769. // Don't write failover-only (automatically added) pools to the config file for now
  6770. continue;
  6771. if (pool->quota != 1) {
  6772. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  6773. pool->quota,
  6774. json_escape(pool->rpc_url));
  6775. } else {
  6776. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  6777. json_escape(pool->rpc_url));
  6778. }
  6779. if (pool->rpc_proxy)
  6780. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  6781. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  6782. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  6783. if (strcmp(pool->goal->name, "default"))
  6784. fprintf(fcfg, "\n\t\t\"pool-goal\" : \"%s\",", pool->goal->name);
  6785. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  6786. if (pool->force_rollntime)
  6787. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  6788. fprintf(fcfg, "\n\t}");
  6789. }
  6790. fputs("\n]\n", fcfg);
  6791. #ifdef USE_OPENCL
  6792. write_config_opencl(fcfg);
  6793. #endif
  6794. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  6795. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  6796. #endif
  6797. /* Simple bool and int options */
  6798. struct opt_table *opt;
  6799. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  6800. char *p, *name = strdup(opt->names);
  6801. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  6802. if (p[1] != '-')
  6803. continue;
  6804. if (opt->type & OPT_NOARG &&
  6805. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  6806. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  6807. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  6808. if (opt->type & OPT_HASARG &&
  6809. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  6810. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  6811. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  6812. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  6813. opt->desc != opt_hidden &&
  6814. 0 <= *(int *)opt->u.arg)
  6815. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  6816. }
  6817. }
  6818. /* Special case options */
  6819. if (request_target_str)
  6820. {
  6821. if (request_pdiff == (long)request_pdiff)
  6822. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  6823. else
  6824. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  6825. }
  6826. fprintf(fcfg, ",\n\"shares\" : %g", opt_shares);
  6827. if (pool_strategy == POOL_BALANCE)
  6828. fputs(",\n\"balance\" : true", fcfg);
  6829. if (pool_strategy == POOL_LOADBALANCE)
  6830. fputs(",\n\"load-balance\" : true", fcfg);
  6831. if (pool_strategy == POOL_ROUNDROBIN)
  6832. fputs(",\n\"round-robin\" : true", fcfg);
  6833. if (pool_strategy == POOL_ROTATE)
  6834. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  6835. #if defined(unix) || defined(__APPLE__)
  6836. if (opt_stderr_cmd && *opt_stderr_cmd)
  6837. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  6838. #endif // defined(unix)
  6839. if (opt_kernel_path && *opt_kernel_path) {
  6840. char *kpath = strdup(opt_kernel_path);
  6841. if (kpath[strlen(kpath)-1] == '/')
  6842. kpath[strlen(kpath)-1] = 0;
  6843. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  6844. free(kpath);
  6845. }
  6846. if (schedstart.enable)
  6847. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  6848. if (schedstop.enable)
  6849. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  6850. if (opt_socks_proxy && *opt_socks_proxy)
  6851. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  6852. _write_config_string_elist(fcfg, "scan", scan_devices);
  6853. #ifdef USE_LIBMICROHTTPD
  6854. if (httpsrv_port != -1)
  6855. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  6856. #endif
  6857. #ifdef USE_LIBEVENT
  6858. if (stratumsrv_port != -1)
  6859. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  6860. #endif
  6861. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  6862. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  6863. if (opt_api_allow)
  6864. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  6865. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  6866. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  6867. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  6868. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  6869. if (*opt_api_mcast_des)
  6870. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  6871. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  6872. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  6873. if (opt_api_groups)
  6874. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  6875. fputs("\n}\n", fcfg);
  6876. json_escape_free();
  6877. }
  6878. void zero_bestshare(void)
  6879. {
  6880. int i;
  6881. best_diff = 0;
  6882. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  6883. for (i = 0; i < total_pools; i++) {
  6884. struct pool *pool = pools[i];
  6885. pool->best_diff = 0;
  6886. }
  6887. }
  6888. void zero_stats(void)
  6889. {
  6890. int i;
  6891. applog(LOG_DEBUG, "Zeroing stats");
  6892. cgtime(&total_tv_start);
  6893. miner_started = total_tv_start;
  6894. total_rolling = 0;
  6895. total_mhashes_done = 0;
  6896. total_getworks = 0;
  6897. total_accepted = 0;
  6898. total_rejected = 0;
  6899. hw_errors = 0;
  6900. total_stale = 0;
  6901. total_discarded = 0;
  6902. total_bytes_rcvd = total_bytes_sent = 0;
  6903. new_blocks = 0;
  6904. local_work = 0;
  6905. total_go = 0;
  6906. total_ro = 0;
  6907. total_secs = 1.0;
  6908. total_diff1 = 0;
  6909. total_bad_diff1 = 0;
  6910. found_blocks = 0;
  6911. total_diff_accepted = 0;
  6912. total_diff_rejected = 0;
  6913. total_diff_stale = 0;
  6914. #ifdef HAVE_CURSES
  6915. awidth = rwidth = swidth = hwwidth = 1;
  6916. #endif
  6917. struct mining_goal_info *goal, *tmpgoal;
  6918. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  6919. {
  6920. goal->diff_accepted = 0;
  6921. }
  6922. for (i = 0; i < total_pools; i++) {
  6923. struct pool *pool = pools[i];
  6924. pool->getwork_requested = 0;
  6925. pool->accepted = 0;
  6926. pool->rejected = 0;
  6927. pool->solved = 0;
  6928. pool->getwork_requested = 0;
  6929. pool->stale_shares = 0;
  6930. pool->discarded_work = 0;
  6931. pool->getfail_occasions = 0;
  6932. pool->remotefail_occasions = 0;
  6933. pool->last_share_time = 0;
  6934. pool->works = 0;
  6935. pool->diff1 = 0;
  6936. pool->diff_accepted = 0;
  6937. pool->diff_rejected = 0;
  6938. pool->diff_stale = 0;
  6939. pool->last_share_diff = 0;
  6940. pool->cgminer_stats.start_tv = total_tv_start;
  6941. pool->cgminer_stats.getwork_calls = 0;
  6942. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6943. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6944. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6945. pool->cgminer_pool_stats.getwork_calls = 0;
  6946. pool->cgminer_pool_stats.getwork_attempts = 0;
  6947. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6948. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  6949. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  6950. pool->cgminer_pool_stats.min_diff = 0;
  6951. pool->cgminer_pool_stats.max_diff = 0;
  6952. pool->cgminer_pool_stats.min_diff_count = 0;
  6953. pool->cgminer_pool_stats.max_diff_count = 0;
  6954. pool->cgminer_pool_stats.times_sent = 0;
  6955. pool->cgminer_pool_stats.bytes_sent = 0;
  6956. pool->cgminer_pool_stats.net_bytes_sent = 0;
  6957. pool->cgminer_pool_stats.times_received = 0;
  6958. pool->cgminer_pool_stats.bytes_received = 0;
  6959. pool->cgminer_pool_stats.net_bytes_received = 0;
  6960. }
  6961. zero_bestshare();
  6962. for (i = 0; i < total_devices; ++i) {
  6963. struct cgpu_info *cgpu = get_devices(i);
  6964. mutex_lock(&hash_lock);
  6965. cgpu->total_mhashes = 0;
  6966. cgpu->accepted = 0;
  6967. cgpu->rejected = 0;
  6968. cgpu->stale = 0;
  6969. cgpu->hw_errors = 0;
  6970. cgpu->utility = 0.0;
  6971. cgpu->utility_diff1 = 0;
  6972. cgpu->last_share_pool_time = 0;
  6973. cgpu->bad_diff1 = 0;
  6974. cgpu->diff1 = 0;
  6975. cgpu->diff_accepted = 0;
  6976. cgpu->diff_rejected = 0;
  6977. cgpu->diff_stale = 0;
  6978. cgpu->last_share_diff = 0;
  6979. cgpu->thread_fail_init_count = 0;
  6980. cgpu->thread_zero_hash_count = 0;
  6981. cgpu->thread_fail_queue_count = 0;
  6982. cgpu->dev_sick_idle_60_count = 0;
  6983. cgpu->dev_dead_idle_600_count = 0;
  6984. cgpu->dev_nostart_count = 0;
  6985. cgpu->dev_over_heat_count = 0;
  6986. cgpu->dev_thermal_cutoff_count = 0;
  6987. cgpu->dev_comms_error_count = 0;
  6988. cgpu->dev_throttle_count = 0;
  6989. cgpu->cgminer_stats.start_tv = total_tv_start;
  6990. cgpu->cgminer_stats.getwork_calls = 0;
  6991. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6992. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6993. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6994. mutex_unlock(&hash_lock);
  6995. if (cgpu->drv->zero_stats)
  6996. cgpu->drv->zero_stats(cgpu);
  6997. }
  6998. }
  6999. #ifdef HAVE_CURSES
  7000. static
  7001. void loginput_mode(const int size)
  7002. {
  7003. clear_logwin();
  7004. loginput_size = size;
  7005. check_winsizes();
  7006. }
  7007. static void display_pools(void)
  7008. {
  7009. struct pool *pool;
  7010. int selected, i, j;
  7011. char input;
  7012. loginput_mode(7 + total_pools);
  7013. immedok(logwin, true);
  7014. updated:
  7015. for (j = 0; j < total_pools; j++) {
  7016. for (i = 0; i < total_pools; i++) {
  7017. pool = pools[i];
  7018. if (pool->prio != j)
  7019. continue;
  7020. if (pool_actively_in_use(pool, NULL))
  7021. wattron(logwin, A_BOLD);
  7022. if (pool->enabled != POOL_ENABLED || pool->failover_only)
  7023. wattron(logwin, A_DIM);
  7024. wlogprint("%d: ", pool->prio);
  7025. switch (pool->enabled) {
  7026. case POOL_ENABLED:
  7027. if ((pool_strategy == POOL_LOADBALANCE) ? (!pool->quota)
  7028. : ((pool_strategy != POOL_FAILOVER) ? pool->failover_only : 0))
  7029. wlogprint("Failover ");
  7030. else
  7031. wlogprint("Enabled ");
  7032. break;
  7033. case POOL_DISABLED:
  7034. wlogprint("Disabled ");
  7035. break;
  7036. case POOL_REJECTING:
  7037. wlogprint("Rejectin ");
  7038. break;
  7039. case POOL_MISBEHAVING:
  7040. wlogprint("Misbehav ");
  7041. break;
  7042. }
  7043. _wlogprint(pool_proto_str(pool));
  7044. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  7045. pool->quota,
  7046. pool->pool_no,
  7047. pool->rpc_url, pool->rpc_user);
  7048. wattroff(logwin, A_BOLD | A_DIM);
  7049. break; //for (i = 0; i < total_pools; i++)
  7050. }
  7051. }
  7052. retry:
  7053. wlogprint("\nCurrent pool management strategy: %s\n",
  7054. strategies[pool_strategy].s);
  7055. if (pool_strategy == POOL_ROTATE)
  7056. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  7057. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  7058. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  7059. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  7060. wlogprint("Or press any other key to continue\n");
  7061. logwin_update();
  7062. input = getch();
  7063. if (!strncasecmp(&input, "a", 1)) {
  7064. if (opt_benchmark)
  7065. {
  7066. wlogprint("Cannot add pools in benchmark mode");
  7067. goto retry;
  7068. }
  7069. input_pool(true);
  7070. goto updated;
  7071. } else if (!strncasecmp(&input, "r", 1)) {
  7072. if (total_pools <= 1) {
  7073. wlogprint("Cannot remove last pool");
  7074. goto retry;
  7075. }
  7076. selected = curses_int("Select pool number");
  7077. if (selected < 0 || selected >= total_pools) {
  7078. wlogprint("Invalid selection\n");
  7079. goto retry;
  7080. }
  7081. pool = pools[selected];
  7082. if (pool == current_pool())
  7083. switch_pools(NULL);
  7084. if (pool == current_pool()) {
  7085. wlogprint("Unable to remove pool due to activity\n");
  7086. goto retry;
  7087. }
  7088. remove_pool(pool);
  7089. goto updated;
  7090. } else if (!strncasecmp(&input, "s", 1)) {
  7091. selected = curses_int("Select pool number");
  7092. if (selected < 0 || selected >= total_pools) {
  7093. wlogprint("Invalid selection\n");
  7094. goto retry;
  7095. }
  7096. pool = pools[selected];
  7097. manual_enable_pool(pool);
  7098. switch_pools(pool);
  7099. goto updated;
  7100. } else if (!strncasecmp(&input, "d", 1)) {
  7101. if (enabled_pools <= 1) {
  7102. wlogprint("Cannot disable last pool");
  7103. goto retry;
  7104. }
  7105. selected = curses_int("Select pool number");
  7106. if (selected < 0 || selected >= total_pools) {
  7107. wlogprint("Invalid selection\n");
  7108. goto retry;
  7109. }
  7110. pool = pools[selected];
  7111. disable_pool(pool, POOL_DISABLED);
  7112. goto updated;
  7113. } else if (!strncasecmp(&input, "e", 1)) {
  7114. selected = curses_int("Select pool number");
  7115. if (selected < 0 || selected >= total_pools) {
  7116. wlogprint("Invalid selection\n");
  7117. goto retry;
  7118. }
  7119. pool = pools[selected];
  7120. manual_enable_pool(pool);
  7121. goto updated;
  7122. } else if (!strncasecmp(&input, "c", 1)) {
  7123. for (i = 0; i <= TOP_STRATEGY; i++)
  7124. wlogprint("%d: %s\n", i, strategies[i].s);
  7125. selected = curses_int("Select strategy number type");
  7126. if (selected < 0 || selected > TOP_STRATEGY) {
  7127. wlogprint("Invalid selection\n");
  7128. goto retry;
  7129. }
  7130. if (selected == POOL_ROTATE) {
  7131. opt_rotate_period = curses_int("Select interval in minutes");
  7132. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  7133. opt_rotate_period = 0;
  7134. wlogprint("Invalid selection\n");
  7135. goto retry;
  7136. }
  7137. }
  7138. mutex_lock(&lp_lock);
  7139. pool_strategy = selected;
  7140. pthread_cond_broadcast(&lp_cond);
  7141. mutex_unlock(&lp_lock);
  7142. switch_pools(NULL);
  7143. goto updated;
  7144. } else if (!strncasecmp(&input, "i", 1)) {
  7145. selected = curses_int("Select pool number");
  7146. if (selected < 0 || selected >= total_pools) {
  7147. wlogprint("Invalid selection\n");
  7148. goto retry;
  7149. }
  7150. pool = pools[selected];
  7151. display_pool_summary(pool);
  7152. goto retry;
  7153. } else if (!strncasecmp(&input, "q", 1)) {
  7154. selected = curses_int("Select pool number");
  7155. if (selected < 0 || selected >= total_pools) {
  7156. wlogprint("Invalid selection\n");
  7157. goto retry;
  7158. }
  7159. pool = pools[selected];
  7160. selected = curses_int("Set quota");
  7161. if (selected < 0) {
  7162. wlogprint("Invalid negative quota\n");
  7163. goto retry;
  7164. }
  7165. if (selected > 0)
  7166. pool->failover_only = false;
  7167. pool->quota = selected;
  7168. adjust_quota_gcd();
  7169. goto updated;
  7170. } else if (!strncasecmp(&input, "f", 1)) {
  7171. opt_fail_only ^= true;
  7172. goto updated;
  7173. } else if (!strncasecmp(&input, "p", 1)) {
  7174. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  7175. if (!prilist)
  7176. {
  7177. wlogprint("Not changing priorities\n");
  7178. goto retry;
  7179. }
  7180. int res = prioritize_pools(prilist, &i);
  7181. free(prilist);
  7182. switch (res) {
  7183. case MSG_NOPOOL:
  7184. wlogprint("No pools\n");
  7185. goto retry;
  7186. case MSG_MISPID:
  7187. wlogprint("Missing pool id parameter\n");
  7188. goto retry;
  7189. case MSG_INVPID:
  7190. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  7191. goto retry;
  7192. case MSG_DUPPID:
  7193. wlogprint("Duplicate pool specified %d\n", i);
  7194. goto retry;
  7195. case MSG_POOLPRIO:
  7196. default:
  7197. goto updated;
  7198. }
  7199. }
  7200. immedok(logwin, false);
  7201. loginput_mode(0);
  7202. }
  7203. static const char *summary_detail_level_str(void)
  7204. {
  7205. if (opt_compact)
  7206. return "compact";
  7207. if (opt_show_procs)
  7208. return "processors";
  7209. return "devices";
  7210. }
  7211. static void display_options(void)
  7212. {
  7213. int selected;
  7214. char input;
  7215. immedok(logwin, true);
  7216. loginput_mode(12);
  7217. retry:
  7218. clear_logwin();
  7219. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  7220. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  7221. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  7222. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  7223. opt_debug_console ? "on" : "off",
  7224. want_per_device_stats? "on" : "off",
  7225. opt_quiet ? "on" : "off",
  7226. opt_log_output ? "on" : "off",
  7227. opt_protocol ? "on" : "off",
  7228. opt_worktime ? "on" : "off",
  7229. summary_detail_level_str(),
  7230. opt_log_interval,
  7231. opt_weighed_stats ? "weighed" : "absolute");
  7232. wlogprint("Select an option or any other key to return\n");
  7233. logwin_update();
  7234. input = getch();
  7235. if (!strncasecmp(&input, "q", 1)) {
  7236. opt_quiet ^= true;
  7237. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  7238. goto retry;
  7239. } else if (!strncasecmp(&input, "v", 1)) {
  7240. opt_log_output ^= true;
  7241. if (opt_log_output)
  7242. opt_quiet = false;
  7243. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  7244. goto retry;
  7245. } else if (!strncasecmp(&input, "n", 1)) {
  7246. opt_log_output = false;
  7247. opt_debug_console = false;
  7248. opt_quiet = false;
  7249. opt_protocol = false;
  7250. opt_compact = false;
  7251. opt_show_procs = false;
  7252. devsummaryYOffset = 0;
  7253. want_per_device_stats = false;
  7254. wlogprint("Output mode reset to normal\n");
  7255. switch_logsize();
  7256. goto retry;
  7257. } else if (!strncasecmp(&input, "d", 1)) {
  7258. opt_debug = true;
  7259. opt_debug_console ^= true;
  7260. opt_log_output = opt_debug_console;
  7261. if (opt_debug_console)
  7262. opt_quiet = false;
  7263. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  7264. goto retry;
  7265. } else if (!strncasecmp(&input, "m", 1)) {
  7266. if (opt_compact)
  7267. opt_compact = false;
  7268. else
  7269. if (!opt_show_procs)
  7270. opt_show_procs = true;
  7271. else
  7272. {
  7273. opt_compact = true;
  7274. opt_show_procs = false;
  7275. devsummaryYOffset = 0;
  7276. }
  7277. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  7278. switch_logsize();
  7279. goto retry;
  7280. } else if (!strncasecmp(&input, "p", 1)) {
  7281. want_per_device_stats ^= true;
  7282. opt_log_output = want_per_device_stats;
  7283. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  7284. goto retry;
  7285. } else if (!strncasecmp(&input, "r", 1)) {
  7286. opt_protocol ^= true;
  7287. if (opt_protocol)
  7288. opt_quiet = false;
  7289. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  7290. goto retry;
  7291. } else if (!strncasecmp(&input, "c", 1))
  7292. clear_logwin();
  7293. else if (!strncasecmp(&input, "l", 1)) {
  7294. selected = curses_int("Interval in seconds");
  7295. if (selected < 0 || selected > 9999) {
  7296. wlogprint("Invalid selection\n");
  7297. goto retry;
  7298. }
  7299. opt_log_interval = selected;
  7300. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  7301. goto retry;
  7302. } else if (!strncasecmp(&input, "s", 1)) {
  7303. opt_realquiet = true;
  7304. } else if (!strncasecmp(&input, "w", 1)) {
  7305. opt_worktime ^= true;
  7306. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  7307. goto retry;
  7308. } else if (!strncasecmp(&input, "t", 1)) {
  7309. opt_weighed_stats ^= true;
  7310. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  7311. goto retry;
  7312. } else if (!strncasecmp(&input, "z", 1)) {
  7313. zero_stats();
  7314. goto retry;
  7315. }
  7316. immedok(logwin, false);
  7317. loginput_mode(0);
  7318. }
  7319. #endif
  7320. void default_save_file(char *filename)
  7321. {
  7322. #if defined(unix) || defined(__APPLE__)
  7323. if (getenv("HOME") && *getenv("HOME")) {
  7324. strcpy(filename, getenv("HOME"));
  7325. strcat(filename, "/");
  7326. }
  7327. else
  7328. strcpy(filename, "");
  7329. strcat(filename, ".bfgminer/");
  7330. mkdir(filename, 0777);
  7331. #else
  7332. strcpy(filename, "");
  7333. #endif
  7334. strcat(filename, def_conf);
  7335. }
  7336. #ifdef HAVE_CURSES
  7337. static void set_options(void)
  7338. {
  7339. int selected;
  7340. char input;
  7341. immedok(logwin, true);
  7342. loginput_mode(8);
  7343. retry:
  7344. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  7345. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  7346. "[W]rite config file\n[B]FGMiner restart\n",
  7347. opt_queue, opt_scantime, opt_expiry, opt_retries);
  7348. wlogprint("Select an option or any other key to return\n");
  7349. logwin_update();
  7350. input = getch();
  7351. if (!strncasecmp(&input, "q", 1)) {
  7352. selected = curses_int("Extra work items to queue");
  7353. if (selected < 0 || selected > 9999) {
  7354. wlogprint("Invalid selection\n");
  7355. goto retry;
  7356. }
  7357. opt_queue = selected;
  7358. goto retry;
  7359. } else if (!strncasecmp(&input, "l", 1)) {
  7360. if (want_longpoll)
  7361. stop_longpoll();
  7362. else
  7363. start_longpoll();
  7364. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  7365. goto retry;
  7366. } else if (!strncasecmp(&input, "s", 1)) {
  7367. selected = curses_int("Set scantime in seconds");
  7368. if (selected < 0 || selected > 9999) {
  7369. wlogprint("Invalid selection\n");
  7370. goto retry;
  7371. }
  7372. opt_scantime = selected;
  7373. goto retry;
  7374. } else if (!strncasecmp(&input, "e", 1)) {
  7375. selected = curses_int("Set expiry time in seconds");
  7376. if (selected < 0 || selected > 9999) {
  7377. wlogprint("Invalid selection\n");
  7378. goto retry;
  7379. }
  7380. opt_expiry = selected;
  7381. goto retry;
  7382. } else if (!strncasecmp(&input, "r", 1)) {
  7383. selected = curses_int("Retries before failing (-1 infinite)");
  7384. if (selected < -1 || selected > 9999) {
  7385. wlogprint("Invalid selection\n");
  7386. goto retry;
  7387. }
  7388. opt_retries = selected;
  7389. goto retry;
  7390. } else if (!strncasecmp(&input, "w", 1)) {
  7391. FILE *fcfg;
  7392. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  7393. default_save_file(filename);
  7394. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  7395. str = curses_input(prompt);
  7396. if (str) {
  7397. struct stat statbuf;
  7398. strcpy(filename, str);
  7399. free(str);
  7400. if (!stat(filename, &statbuf)) {
  7401. wlogprint("File exists, overwrite?\n");
  7402. input = getch();
  7403. if (strncasecmp(&input, "y", 1))
  7404. goto retry;
  7405. }
  7406. }
  7407. fcfg = fopen(filename, "w");
  7408. if (!fcfg) {
  7409. wlogprint("Cannot open or create file\n");
  7410. goto retry;
  7411. }
  7412. write_config(fcfg);
  7413. fclose(fcfg);
  7414. goto retry;
  7415. } else if (!strncasecmp(&input, "b", 1)) {
  7416. wlogprint("Are you sure?\n");
  7417. input = getch();
  7418. if (!strncasecmp(&input, "y", 1))
  7419. app_restart();
  7420. else
  7421. clear_logwin();
  7422. } else
  7423. clear_logwin();
  7424. loginput_mode(0);
  7425. immedok(logwin, false);
  7426. }
  7427. int scan_serial(const char *);
  7428. static
  7429. void _managetui_msg(const char *repr, const char **msg)
  7430. {
  7431. if (*msg)
  7432. {
  7433. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  7434. wattron(logwin, A_BOLD);
  7435. wlogprint("%s", *msg);
  7436. wattroff(logwin, A_BOLD);
  7437. *msg = NULL;
  7438. }
  7439. logwin_update();
  7440. }
  7441. void manage_device(void)
  7442. {
  7443. char logline[256];
  7444. const char *msg = NULL;
  7445. struct cgpu_info *cgpu;
  7446. const struct device_drv *drv;
  7447. selecting_device = true;
  7448. immedok(logwin, true);
  7449. loginput_mode(12);
  7450. devchange:
  7451. if (unlikely(!total_devices))
  7452. {
  7453. clear_logwin();
  7454. wlogprint("(no devices)\n");
  7455. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  7456. _managetui_msg("(none)", &msg);
  7457. int input = getch();
  7458. switch (input)
  7459. {
  7460. case '+': case '=': // add new device
  7461. goto addnew;
  7462. default:
  7463. goto out;
  7464. }
  7465. }
  7466. cgpu = devices[selected_device];
  7467. drv = cgpu->drv;
  7468. refresh_devstatus();
  7469. refresh:
  7470. clear_logwin();
  7471. wlogprint("Select processor to manage using up/down arrow keys\n");
  7472. get_statline3(logline, sizeof(logline), cgpu, true, true);
  7473. wattron(logwin, A_BOLD);
  7474. wlogprint("%s", logline);
  7475. wattroff(logwin, A_BOLD);
  7476. wlogprint("\n");
  7477. if (cgpu->dev_manufacturer)
  7478. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  7479. else
  7480. if (cgpu->dev_product)
  7481. wlogprint(" %s\n", cgpu->dev_product);
  7482. if (cgpu->dev_serial)
  7483. wlogprint("Serial: %s\n", cgpu->dev_serial);
  7484. if (cgpu->kname)
  7485. wlogprint("Kernel: %s\n", cgpu->kname);
  7486. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  7487. drv->proc_wlogprint_status(cgpu);
  7488. wlogprint("\n");
  7489. // TODO: Last share at TIMESTAMP on pool N
  7490. // TODO: Custom device info/commands
  7491. if (cgpu->deven != DEV_ENABLED)
  7492. wlogprint("[E]nable ");
  7493. if (cgpu->deven != DEV_DISABLED)
  7494. wlogprint("[D]isable ");
  7495. if (drv->identify_device)
  7496. wlogprint("[I]dentify ");
  7497. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  7498. drv->proc_tui_wlogprint_choices(cgpu);
  7499. wlogprint("\n");
  7500. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  7501. _managetui_msg(cgpu->proc_repr, &msg);
  7502. while (true)
  7503. {
  7504. int input = getch();
  7505. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  7506. switch (input) {
  7507. case 'd': case 'D':
  7508. if (cgpu->deven == DEV_DISABLED)
  7509. msg = "Processor already disabled\n";
  7510. else
  7511. {
  7512. cgpu->deven = DEV_DISABLED;
  7513. msg = "Processor being disabled\n";
  7514. }
  7515. goto refresh;
  7516. case 'e': case 'E':
  7517. if (cgpu->deven == DEV_ENABLED)
  7518. msg = "Processor already enabled\n";
  7519. else
  7520. {
  7521. proc_enable(cgpu);
  7522. msg = "Processor being enabled\n";
  7523. }
  7524. goto refresh;
  7525. case 'i': case 'I':
  7526. if (drv->identify_device && drv->identify_device(cgpu))
  7527. msg = "Identify command sent\n";
  7528. else
  7529. goto key_default;
  7530. goto refresh;
  7531. case KEY_DOWN:
  7532. if (selected_device >= total_devices - 1)
  7533. break;
  7534. ++selected_device;
  7535. goto devchange;
  7536. case KEY_UP:
  7537. if (selected_device <= 0)
  7538. break;
  7539. --selected_device;
  7540. goto devchange;
  7541. case KEY_NPAGE:
  7542. {
  7543. if (selected_device >= total_devices - 1)
  7544. break;
  7545. struct cgpu_info *mdev = devices[selected_device]->device;
  7546. do {
  7547. ++selected_device;
  7548. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  7549. goto devchange;
  7550. }
  7551. case KEY_PPAGE:
  7552. {
  7553. if (selected_device <= 0)
  7554. break;
  7555. struct cgpu_info *mdev = devices[selected_device]->device;
  7556. do {
  7557. --selected_device;
  7558. } while (devices[selected_device]->device == mdev && selected_device > 0);
  7559. goto devchange;
  7560. }
  7561. case '/': case '?': // find device
  7562. {
  7563. static char *pattern = NULL;
  7564. char *newpattern = curses_input("Enter pattern");
  7565. if (newpattern)
  7566. {
  7567. free(pattern);
  7568. pattern = newpattern;
  7569. }
  7570. else
  7571. if (!pattern)
  7572. pattern = calloc(1, 1);
  7573. int match = cgpu_search(pattern, selected_device + 1);
  7574. if (match == -1)
  7575. {
  7576. msg = "Couldn't find device\n";
  7577. goto refresh;
  7578. }
  7579. selected_device = match;
  7580. goto devchange;
  7581. }
  7582. case '+': case '=': // add new device
  7583. {
  7584. addnew:
  7585. clear_logwin();
  7586. _wlogprint(
  7587. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  7588. "Prefix by a driver name and colon to only probe a specific driver.\n"
  7589. "For example: erupter:"
  7590. #ifdef WIN32
  7591. "\\\\.\\COM40"
  7592. #elif defined(__APPLE__)
  7593. "/dev/cu.SLAB_USBtoUART"
  7594. #else
  7595. "/dev/ttyUSB39"
  7596. #endif
  7597. "\n"
  7598. );
  7599. char *scanser = curses_input("Enter target");
  7600. if (scan_serial(scanser))
  7601. {
  7602. selected_device = total_devices - 1;
  7603. msg = "Device scan succeeded\n";
  7604. }
  7605. else
  7606. msg = "No new devices found\n";
  7607. goto devchange;
  7608. }
  7609. case 'Q': case 'q':
  7610. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  7611. case '\x1b': // ESC
  7612. case KEY_ENTER:
  7613. case '\r': // Ctrl-M on Windows, with nonl
  7614. #ifdef PADENTER
  7615. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  7616. #endif
  7617. case '\n':
  7618. goto out;
  7619. default:
  7620. ;
  7621. key_default:
  7622. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  7623. {
  7624. msg = drv->proc_tui_handle_choice(cgpu, input);
  7625. if (msg)
  7626. goto refresh;
  7627. }
  7628. }
  7629. }
  7630. out:
  7631. selecting_device = false;
  7632. loginput_mode(0);
  7633. immedok(logwin, false);
  7634. }
  7635. void show_help(void)
  7636. {
  7637. loginput_mode(11);
  7638. // NOTE: wlogprint is a macro with a buffer limit
  7639. _wlogprint(
  7640. "LU: oldest explicit work update currently being used for new work\n"
  7641. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  7642. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  7643. "E: # shares * diff per 2kB bw | I: expected income | BS: best share ever found\n"
  7644. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7645. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7646. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7647. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  7648. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7649. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7650. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE
  7651. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7652. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7653. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7654. "\n"
  7655. "devices/processors hashing (only for totals line), hottest temperature\n"
  7656. );
  7657. wlogprint(
  7658. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  7659. , opt_log_interval);
  7660. _wlogprint(
  7661. "A: accepted shares | R: rejected+discarded(% of total)\n"
  7662. "HW: hardware errors / % nonces invalid\n"
  7663. "\n"
  7664. "Press any key to clear"
  7665. );
  7666. logwin_update();
  7667. getch();
  7668. loginput_mode(0);
  7669. }
  7670. static void *input_thread(void __maybe_unused *userdata)
  7671. {
  7672. RenameThread("input");
  7673. if (!curses_active)
  7674. return NULL;
  7675. while (1) {
  7676. int input;
  7677. input = getch();
  7678. switch (input) {
  7679. case 'h': case 'H': case '?':
  7680. case KEY_F(1):
  7681. show_help();
  7682. break;
  7683. case 'q': case 'Q':
  7684. kill_work();
  7685. return NULL;
  7686. case 'd': case 'D':
  7687. display_options();
  7688. break;
  7689. case 'm': case 'M':
  7690. manage_device();
  7691. break;
  7692. case 'p': case 'P':
  7693. display_pools();
  7694. break;
  7695. case 's': case 'S':
  7696. set_options();
  7697. break;
  7698. #ifdef HAVE_CURSES
  7699. case KEY_DOWN:
  7700. {
  7701. const int visible_lines = logcursor - devcursor;
  7702. const int invisible_lines = total_lines - visible_lines;
  7703. if (devsummaryYOffset <= -invisible_lines)
  7704. break;
  7705. devsummaryYOffset -= 2;
  7706. }
  7707. case KEY_UP:
  7708. if (devsummaryYOffset == 0)
  7709. break;
  7710. ++devsummaryYOffset;
  7711. refresh_devstatus();
  7712. break;
  7713. case KEY_NPAGE:
  7714. {
  7715. const int visible_lines = logcursor - devcursor;
  7716. const int invisible_lines = total_lines - visible_lines;
  7717. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  7718. devsummaryYOffset = -invisible_lines;
  7719. else
  7720. devsummaryYOffset -= visible_lines;
  7721. refresh_devstatus();
  7722. break;
  7723. }
  7724. case KEY_PPAGE:
  7725. {
  7726. const int visible_lines = logcursor - devcursor;
  7727. if (devsummaryYOffset + visible_lines >= 0)
  7728. devsummaryYOffset = 0;
  7729. else
  7730. devsummaryYOffset += visible_lines;
  7731. refresh_devstatus();
  7732. break;
  7733. }
  7734. #endif
  7735. }
  7736. if (opt_realquiet) {
  7737. disable_curses();
  7738. break;
  7739. }
  7740. }
  7741. return NULL;
  7742. }
  7743. #endif
  7744. static void *api_thread(void *userdata)
  7745. {
  7746. struct thr_info *mythr = userdata;
  7747. pthread_detach(pthread_self());
  7748. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7749. RenameThread("rpc");
  7750. api(api_thr_id);
  7751. mythr->has_pth = false;
  7752. return NULL;
  7753. }
  7754. void thread_reportin(struct thr_info *thr)
  7755. {
  7756. cgtime(&thr->last);
  7757. thr->cgpu->status = LIFE_WELL;
  7758. thr->getwork = 0;
  7759. thr->cgpu->device_last_well = time(NULL);
  7760. }
  7761. void thread_reportout(struct thr_info *thr)
  7762. {
  7763. thr->getwork = time(NULL);
  7764. }
  7765. static void hashmeter(int thr_id, struct timeval *diff,
  7766. uint64_t hashes_done)
  7767. {
  7768. char logstatusline[256];
  7769. struct timeval temp_tv_end, total_diff;
  7770. double secs;
  7771. double local_secs;
  7772. static double local_mhashes_done = 0;
  7773. double local_mhashes = (double)hashes_done / 1000000.0;
  7774. bool showlog = false;
  7775. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[ALLOC_H2B_SPACED+3+1];
  7776. char rejpcbuf[6];
  7777. char bnbuf[6];
  7778. struct thr_info *thr;
  7779. /* Update the last time this thread reported in */
  7780. if (thr_id >= 0) {
  7781. thr = get_thread(thr_id);
  7782. cgtime(&(thr->last));
  7783. thr->cgpu->device_last_well = time(NULL);
  7784. }
  7785. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  7786. /* So we can call hashmeter from a non worker thread */
  7787. if (thr_id >= 0) {
  7788. struct cgpu_info *cgpu = thr->cgpu;
  7789. int threadobj = cgpu->threads ?: 1;
  7790. double thread_rolling = 0.0;
  7791. int i;
  7792. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  7793. thr_id, hashes_done, hashes_done / 1000 / secs);
  7794. /* Rolling average for each thread and each device */
  7795. decay_time(&thr->rolling, local_mhashes / secs, secs);
  7796. for (i = 0; i < threadobj; i++)
  7797. thread_rolling += cgpu->thr[i]->rolling;
  7798. mutex_lock(&hash_lock);
  7799. decay_time(&cgpu->rolling, thread_rolling, secs);
  7800. cgpu->total_mhashes += local_mhashes;
  7801. mutex_unlock(&hash_lock);
  7802. // If needed, output detailed, per-device stats
  7803. if (want_per_device_stats) {
  7804. struct timeval now;
  7805. struct timeval elapsed;
  7806. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  7807. cgtime(&now);
  7808. timersub(&now, last_msg_tv, &elapsed);
  7809. if (opt_log_interval <= elapsed.tv_sec) {
  7810. struct cgpu_info *cgpu = thr->cgpu;
  7811. char logline[255];
  7812. *last_msg_tv = now;
  7813. get_statline(logline, sizeof(logline), cgpu);
  7814. if (!curses_active) {
  7815. printf("\n%s\r", logline);
  7816. fflush(stdout);
  7817. } else
  7818. applog(LOG_INFO, "%s", logline);
  7819. }
  7820. }
  7821. }
  7822. /* Totals are updated by all threads so can race without locking */
  7823. mutex_lock(&hash_lock);
  7824. cgtime(&temp_tv_end);
  7825. timersub(&temp_tv_end, &total_tv_start, &total_diff);
  7826. total_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7827. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  7828. total_mhashes_done += local_mhashes;
  7829. local_mhashes_done += local_mhashes;
  7830. /* Only update with opt_log_interval */
  7831. if (total_diff.tv_sec < opt_log_interval)
  7832. goto out_unlock;
  7833. showlog = true;
  7834. cgtime(&total_tv_end);
  7835. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7836. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  7837. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  7838. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  7839. multi_format_unit_array2(
  7840. ((char*[]){cHr, aHr, uHr}),
  7841. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  7842. true, "h/s", H2B_SHORT,
  7843. 3,
  7844. 1e6*total_rolling,
  7845. 1e6*total_mhashes_done / total_secs,
  7846. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  7847. int ui_accepted, ui_rejected, ui_stale;
  7848. if (opt_weighed_stats)
  7849. {
  7850. ui_accepted = total_diff_accepted;
  7851. ui_rejected = total_diff_rejected;
  7852. ui_stale = total_diff_stale;
  7853. }
  7854. else
  7855. {
  7856. ui_accepted = total_accepted;
  7857. ui_rejected = total_rejected;
  7858. ui_stale = total_stale;
  7859. }
  7860. #ifdef HAVE_CURSES
  7861. if (curses_active_locked()) {
  7862. float temp = 0;
  7863. struct cgpu_info *proc, *last_working_dev = NULL;
  7864. int i, working_devs = 0, working_procs = 0;
  7865. int divx;
  7866. bool bad = false;
  7867. // Find the highest temperature of all processors
  7868. for (i = 0; i < total_devices; ++i)
  7869. {
  7870. proc = get_devices(i);
  7871. if (proc->temp > temp)
  7872. temp = proc->temp;
  7873. if (unlikely(proc->deven == DEV_DISABLED))
  7874. ; // Just need to block it off from both conditions
  7875. else
  7876. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  7877. {
  7878. if (proc->rolling > .1)
  7879. {
  7880. ++working_procs;
  7881. if (proc->device != last_working_dev)
  7882. {
  7883. ++working_devs;
  7884. last_working_dev = proc->device;
  7885. }
  7886. }
  7887. }
  7888. else
  7889. bad = true;
  7890. }
  7891. if (working_devs == working_procs)
  7892. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  7893. else
  7894. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  7895. divx = 7;
  7896. if (opt_show_procs && !opt_compact)
  7897. divx += max_lpdigits;
  7898. if (bad)
  7899. {
  7900. divx += sizeof(U8_BAD_START)-1;
  7901. strcpy(&statusline[divx], U8_BAD_END);
  7902. divx += sizeof(U8_BAD_END)-1;
  7903. }
  7904. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  7905. format_statline(statusline, sizeof(statusline),
  7906. cHr, aHr,
  7907. uHr,
  7908. ui_accepted,
  7909. ui_rejected,
  7910. ui_stale,
  7911. total_diff_rejected + total_diff_stale, total_diff_accepted,
  7912. hw_errors,
  7913. total_bad_diff1, total_bad_diff1 + total_diff1);
  7914. unlock_curses();
  7915. }
  7916. #endif
  7917. // Add a space
  7918. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  7919. uHr[5] = ' ';
  7920. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  7921. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  7922. snprintf(logstatusline, sizeof(logstatusline),
  7923. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  7924. want_per_device_stats ? "ALL " : "",
  7925. opt_log_interval,
  7926. cHr, aHr,
  7927. uHr,
  7928. ui_accepted,
  7929. ui_rejected,
  7930. ui_stale,
  7931. rejpcbuf,
  7932. hw_errors,
  7933. bnbuf
  7934. );
  7935. local_mhashes_done = 0;
  7936. out_unlock:
  7937. mutex_unlock(&hash_lock);
  7938. if (showlog) {
  7939. if (!curses_active) {
  7940. if (want_per_device_stats)
  7941. printf("\n%s\r", logstatusline);
  7942. else
  7943. {
  7944. const int logstatusline_len = strlen(logstatusline);
  7945. int padding;
  7946. if (last_logstatusline_len > logstatusline_len)
  7947. padding = (last_logstatusline_len - logstatusline_len);
  7948. else
  7949. {
  7950. padding = 0;
  7951. if (last_logstatusline_len == -1)
  7952. puts("");
  7953. }
  7954. printf("%s%*s\r", logstatusline, padding, "");
  7955. last_logstatusline_len = logstatusline_len;
  7956. }
  7957. fflush(stdout);
  7958. } else
  7959. applog(LOG_INFO, "%s", logstatusline);
  7960. }
  7961. }
  7962. void hashmeter2(struct thr_info *thr)
  7963. {
  7964. struct timeval tv_now, tv_elapsed;
  7965. timerclear(&thr->tv_hashes_done);
  7966. cgtime(&tv_now);
  7967. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  7968. /* Update the hashmeter at most 5 times per second */
  7969. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  7970. tv_elapsed.tv_sec >= opt_log_interval) {
  7971. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  7972. thr->hashes_done = 0;
  7973. thr->tv_lastupdate = tv_now;
  7974. }
  7975. }
  7976. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  7977. struct stratum_share *sshare)
  7978. {
  7979. struct work *work = sshare->work;
  7980. share_result(val, res_val, err_val, work, false, "");
  7981. }
  7982. /* Parses stratum json responses and tries to find the id that the request
  7983. * matched to and treat it accordingly. */
  7984. bool parse_stratum_response(struct pool *pool, char *s)
  7985. {
  7986. json_t *val = NULL, *err_val, *res_val, *id_val;
  7987. struct stratum_share *sshare;
  7988. json_error_t err;
  7989. bool ret = false;
  7990. int id;
  7991. val = JSON_LOADS(s, &err);
  7992. if (!val) {
  7993. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  7994. goto out;
  7995. }
  7996. res_val = json_object_get(val, "result");
  7997. err_val = json_object_get(val, "error");
  7998. id_val = json_object_get(val, "id");
  7999. if (json_is_null(id_val) || !id_val) {
  8000. char *ss;
  8001. if (err_val)
  8002. ss = json_dumps(err_val, JSON_INDENT(3));
  8003. else
  8004. ss = strdup("(unknown reason)");
  8005. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  8006. free(ss);
  8007. goto out;
  8008. }
  8009. if (!json_is_integer(id_val)) {
  8010. if (json_is_string(id_val)
  8011. && !strncmp(json_string_value(id_val), "txlist", 6))
  8012. {
  8013. const bool is_array = json_is_array(res_val);
  8014. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  8015. is_array ? "transaction list" : "no-transaction-list response",
  8016. pool->pool_no, &json_string_value(id_val)[6]);
  8017. if (!is_array)
  8018. {
  8019. // No need to wait for a timeout
  8020. timer_unset(&pool->swork.tv_transparency);
  8021. pool_set_opaque(pool, true);
  8022. goto fishy;
  8023. }
  8024. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id))
  8025. // We only care about a transaction list for the current job id
  8026. goto fishy;
  8027. // Check that the transactions actually hash to the merkle links
  8028. {
  8029. unsigned maxtx = 1 << pool->swork.merkles;
  8030. unsigned mintx = maxtx >> 1;
  8031. --maxtx;
  8032. unsigned acttx = (unsigned)json_array_size(res_val);
  8033. if (acttx < mintx || acttx > maxtx) {
  8034. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  8035. pool->pool_no, acttx, mintx, maxtx);
  8036. goto fishy;
  8037. }
  8038. // TODO: Check hashes match actual merkle links
  8039. }
  8040. pool_set_opaque(pool, false);
  8041. timer_unset(&pool->swork.tv_transparency);
  8042. fishy:
  8043. ret = true;
  8044. }
  8045. goto out;
  8046. }
  8047. id = json_integer_value(id_val);
  8048. mutex_lock(&sshare_lock);
  8049. HASH_FIND_INT(stratum_shares, &id, sshare);
  8050. if (sshare)
  8051. HASH_DEL(stratum_shares, sshare);
  8052. mutex_unlock(&sshare_lock);
  8053. if (!sshare) {
  8054. double pool_diff;
  8055. /* Since the share is untracked, we can only guess at what the
  8056. * work difficulty is based on the current pool diff. */
  8057. cg_rlock(&pool->data_lock);
  8058. pool_diff = target_diff(pool->swork.target);
  8059. cg_runlock(&pool->data_lock);
  8060. if (json_is_true(res_val)) {
  8061. struct mining_goal_info * const goal = pool->goal;
  8062. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  8063. /* We don't know what device this came from so we can't
  8064. * attribute the work to the relevant cgpu */
  8065. mutex_lock(&stats_lock);
  8066. total_accepted++;
  8067. pool->accepted++;
  8068. total_diff_accepted += pool_diff;
  8069. pool->diff_accepted += pool_diff;
  8070. goal->diff_accepted += pool_diff;
  8071. mutex_unlock(&stats_lock);
  8072. } else {
  8073. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  8074. mutex_lock(&stats_lock);
  8075. total_rejected++;
  8076. pool->rejected++;
  8077. total_diff_rejected += pool_diff;
  8078. pool->diff_rejected += pool_diff;
  8079. mutex_unlock(&stats_lock);
  8080. }
  8081. goto out;
  8082. }
  8083. else {
  8084. mutex_lock(&submitting_lock);
  8085. --total_submitting;
  8086. mutex_unlock(&submitting_lock);
  8087. }
  8088. stratum_share_result(val, res_val, err_val, sshare);
  8089. free_work(sshare->work);
  8090. free(sshare);
  8091. ret = true;
  8092. out:
  8093. if (val)
  8094. json_decref(val);
  8095. return ret;
  8096. }
  8097. static void shutdown_stratum(struct pool *pool)
  8098. {
  8099. // Shut down Stratum as if we never had it
  8100. pool->stratum_active = false;
  8101. pool->stratum_init = false;
  8102. pool->has_stratum = false;
  8103. shutdown(pool->sock, SHUT_RDWR);
  8104. free(pool->stratum_url);
  8105. if (pool->sockaddr_url == pool->stratum_url)
  8106. pool->sockaddr_url = NULL;
  8107. pool->stratum_url = NULL;
  8108. }
  8109. void clear_stratum_shares(struct pool *pool)
  8110. {
  8111. int my_mining_threads = mining_threads; // Cached outside of locking
  8112. struct stratum_share *sshare, *tmpshare;
  8113. struct work *work;
  8114. struct cgpu_info *cgpu;
  8115. double diff_cleared = 0;
  8116. double thr_diff_cleared[my_mining_threads];
  8117. int cleared = 0;
  8118. int thr_cleared[my_mining_threads];
  8119. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  8120. for (int i = 0; i < my_mining_threads; ++i)
  8121. {
  8122. thr_diff_cleared[i] = 0;
  8123. thr_cleared[i] = 0;
  8124. }
  8125. mutex_lock(&sshare_lock);
  8126. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  8127. work = sshare->work;
  8128. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  8129. HASH_DEL(stratum_shares, sshare);
  8130. sharelog("disconnect", work);
  8131. diff_cleared += sshare->work->work_difficulty;
  8132. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  8133. ++thr_cleared[work->thr_id];
  8134. free_work(sshare->work);
  8135. free(sshare);
  8136. cleared++;
  8137. }
  8138. }
  8139. mutex_unlock(&sshare_lock);
  8140. if (cleared) {
  8141. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  8142. mutex_lock(&stats_lock);
  8143. pool->stale_shares += cleared;
  8144. total_stale += cleared;
  8145. pool->diff_stale += diff_cleared;
  8146. total_diff_stale += diff_cleared;
  8147. for (int i = 0; i < my_mining_threads; ++i)
  8148. if (thr_cleared[i])
  8149. {
  8150. cgpu = get_thr_cgpu(i);
  8151. cgpu->diff_stale += thr_diff_cleared[i];
  8152. cgpu->stale += thr_cleared[i];
  8153. }
  8154. mutex_unlock(&stats_lock);
  8155. mutex_lock(&submitting_lock);
  8156. total_submitting -= cleared;
  8157. mutex_unlock(&submitting_lock);
  8158. }
  8159. }
  8160. static void resubmit_stratum_shares(struct pool *pool)
  8161. {
  8162. struct stratum_share *sshare, *tmpshare;
  8163. struct work *work;
  8164. unsigned resubmitted = 0;
  8165. mutex_lock(&sshare_lock);
  8166. mutex_lock(&submitting_lock);
  8167. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  8168. if (sshare->work->pool != pool)
  8169. continue;
  8170. HASH_DEL(stratum_shares, sshare);
  8171. work = sshare->work;
  8172. DL_APPEND(submit_waiting, work);
  8173. free(sshare);
  8174. ++resubmitted;
  8175. }
  8176. mutex_unlock(&submitting_lock);
  8177. mutex_unlock(&sshare_lock);
  8178. if (resubmitted) {
  8179. notifier_wake(submit_waiting_notifier);
  8180. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  8181. }
  8182. }
  8183. static void clear_pool_work(struct pool *pool)
  8184. {
  8185. struct work *work, *tmp;
  8186. int cleared = 0;
  8187. mutex_lock(stgd_lock);
  8188. HASH_ITER(hh, staged_work, work, tmp) {
  8189. if (work->pool == pool) {
  8190. unstage_work(work);
  8191. free_work(work);
  8192. cleared++;
  8193. }
  8194. }
  8195. mutex_unlock(stgd_lock);
  8196. }
  8197. static int cp_prio(void)
  8198. {
  8199. int prio;
  8200. cg_rlock(&control_lock);
  8201. prio = currentpool->prio;
  8202. cg_runlock(&control_lock);
  8203. return prio;
  8204. }
  8205. /* We only need to maintain a secondary pool connection when we need the
  8206. * capacity to get work from the backup pools while still on the primary */
  8207. static bool cnx_needed(struct pool *pool)
  8208. {
  8209. struct pool *cp;
  8210. // We want to keep a connection open for rejecting or misbehaving pools, to detect when/if they change their tune
  8211. if (pool->enabled == POOL_DISABLED)
  8212. return false;
  8213. /* Idle stratum pool needs something to kick it alive again */
  8214. if (pool->has_stratum && pool->idle)
  8215. return true;
  8216. /* Getwork pools without opt_fail_only need backup pools up to be able
  8217. * to leak shares */
  8218. cp = current_pool();
  8219. if (pool_actively_desired(pool, cp))
  8220. return true;
  8221. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  8222. return true;
  8223. /* Keep the connection open to allow any stray shares to be submitted
  8224. * on switching pools for 2 minutes. */
  8225. if (timer_elapsed(&pool->tv_last_work_time, NULL) < 120)
  8226. return true;
  8227. /* If the pool has only just come to life and is higher priority than
  8228. * the current pool keep the connection open so we can fail back to
  8229. * it. */
  8230. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8231. return true;
  8232. if (pool_unworkable(cp))
  8233. return true;
  8234. /* We've run out of work, bring anything back to life. */
  8235. if (no_work)
  8236. return true;
  8237. // If the current pool lacks its own block change detection, see if we are needed for that
  8238. if (pool_active_lp_pool(cp) == pool)
  8239. return true;
  8240. return false;
  8241. }
  8242. static void wait_lpcurrent(struct pool *pool);
  8243. static void pool_resus(struct pool *pool);
  8244. static void stratum_resumed(struct pool *pool)
  8245. {
  8246. if (!pool->stratum_notify)
  8247. return;
  8248. if (pool_tclear(pool, &pool->idle)) {
  8249. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  8250. pool_resus(pool);
  8251. }
  8252. }
  8253. static bool supports_resume(struct pool *pool)
  8254. {
  8255. bool ret;
  8256. cg_rlock(&pool->data_lock);
  8257. ret = (pool->sessionid != NULL);
  8258. cg_runlock(&pool->data_lock);
  8259. return ret;
  8260. }
  8261. static bool pools_active;
  8262. /* One stratum thread per pool that has stratum waits on the socket checking
  8263. * for new messages and for the integrity of the socket connection. We reset
  8264. * the connection based on the integrity of the receive side only as the send
  8265. * side will eventually expire data it fails to send. */
  8266. static void *stratum_thread(void *userdata)
  8267. {
  8268. struct pool *pool = (struct pool *)userdata;
  8269. pthread_detach(pthread_self());
  8270. char threadname[20];
  8271. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  8272. RenameThread(threadname);
  8273. srand(time(NULL) + (intptr_t)userdata);
  8274. while (42) {
  8275. struct timeval timeout;
  8276. int sel_ret;
  8277. fd_set rd;
  8278. char *s;
  8279. int sock;
  8280. if (unlikely(!pool->has_stratum))
  8281. break;
  8282. /* Check to see whether we need to maintain this connection
  8283. * indefinitely or just bring it up when we switch to this
  8284. * pool */
  8285. while (true)
  8286. {
  8287. sock = pool->sock;
  8288. if (sock == INVSOCK)
  8289. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  8290. pool->pool_no);
  8291. else
  8292. if (!sock_full(pool) && !cnx_needed(pool) && pools_active)
  8293. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  8294. pool->pool_no);
  8295. else
  8296. break;
  8297. suspend_stratum(pool);
  8298. clear_stratum_shares(pool);
  8299. clear_pool_work(pool);
  8300. wait_lpcurrent(pool);
  8301. if (!restart_stratum(pool)) {
  8302. pool_died(pool);
  8303. while (!restart_stratum(pool)) {
  8304. if (pool->removed)
  8305. goto out;
  8306. cgsleep_ms(30000);
  8307. }
  8308. }
  8309. }
  8310. FD_ZERO(&rd);
  8311. FD_SET(sock, &rd);
  8312. timeout.tv_sec = 120;
  8313. timeout.tv_usec = 0;
  8314. /* If we fail to receive any notify messages for 2 minutes we
  8315. * assume the connection has been dropped and treat this pool
  8316. * as dead */
  8317. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  8318. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  8319. s = NULL;
  8320. } else
  8321. s = recv_line(pool);
  8322. if (!s) {
  8323. if (!pool->has_stratum)
  8324. break;
  8325. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  8326. pool->getfail_occasions++;
  8327. total_go++;
  8328. mutex_lock(&pool->stratum_lock);
  8329. pool->stratum_active = pool->stratum_notify = false;
  8330. pool->sock = INVSOCK;
  8331. mutex_unlock(&pool->stratum_lock);
  8332. /* If the socket to our stratum pool disconnects, all
  8333. * submissions need to be discarded or resent. */
  8334. if (!supports_resume(pool))
  8335. clear_stratum_shares(pool);
  8336. else
  8337. resubmit_stratum_shares(pool);
  8338. clear_pool_work(pool);
  8339. if (pool == current_pool())
  8340. restart_threads();
  8341. if (restart_stratum(pool))
  8342. continue;
  8343. shutdown_stratum(pool);
  8344. pool_died(pool);
  8345. break;
  8346. }
  8347. /* Check this pool hasn't died while being a backup pool and
  8348. * has not had its idle flag cleared */
  8349. stratum_resumed(pool);
  8350. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  8351. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  8352. free(s);
  8353. if (pool->swork.clean) {
  8354. struct work *work = make_work();
  8355. /* Generate a single work item to update the current
  8356. * block database */
  8357. pool->swork.clean = false;
  8358. gen_stratum_work(pool, work);
  8359. /* Try to extract block height from coinbase scriptSig */
  8360. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  8361. unsigned char cb_height_sz;
  8362. cb_height_sz = bin_height[-1];
  8363. if (cb_height_sz == 3) {
  8364. // FIXME: The block number will overflow this by AD 2173
  8365. struct mining_goal_info * const goal = pool->goal;
  8366. const void * const prevblkhash = &work->data[4];
  8367. uint32_t height = 0;
  8368. memcpy(&height, bin_height, 3);
  8369. height = le32toh(height);
  8370. have_block_height(goal, prevblkhash, height);
  8371. }
  8372. pool->swork.work_restart_id =
  8373. ++pool->work_restart_id;
  8374. pool_update_work_restart_time(pool);
  8375. if (test_work_current(work)) {
  8376. /* Only accept a work update if this stratum
  8377. * connection is from the current pool */
  8378. struct pool * const cp = current_pool();
  8379. if (pool == cp)
  8380. restart_threads();
  8381. applog(
  8382. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  8383. "Stratum from pool %d requested work update", pool->pool_no);
  8384. } else
  8385. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  8386. free_work(work);
  8387. }
  8388. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  8389. // More than 4 timmills past since requested transactions
  8390. timer_unset(&pool->swork.tv_transparency);
  8391. pool_set_opaque(pool, true);
  8392. }
  8393. }
  8394. out:
  8395. return NULL;
  8396. }
  8397. static void init_stratum_thread(struct pool *pool)
  8398. {
  8399. struct mining_goal_info * const goal = pool->goal;
  8400. goal->have_longpoll = true;
  8401. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  8402. quit(1, "Failed to create stratum thread");
  8403. }
  8404. static void *longpoll_thread(void *userdata);
  8405. static bool stratum_works(struct pool *pool)
  8406. {
  8407. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  8408. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  8409. return false;
  8410. if (pool->stratum_active)
  8411. return true;
  8412. if (!initiate_stratum(pool))
  8413. return false;
  8414. return true;
  8415. }
  8416. static
  8417. bool pool_recently_got_work(struct pool * const pool, const struct timeval * const tvp_now)
  8418. {
  8419. return (timer_isset(&pool->tv_last_work_time) && timer_elapsed(&pool->tv_last_work_time, tvp_now) < 60);
  8420. }
  8421. static bool pool_active(struct pool *pool, bool pinging)
  8422. {
  8423. struct timeval tv_now, tv_getwork, tv_getwork_reply;
  8424. bool ret = false;
  8425. json_t *val;
  8426. CURL *curl = NULL;
  8427. int rolltime;
  8428. char *rpc_req;
  8429. struct work *work;
  8430. enum pool_protocol proto;
  8431. if (pool->stratum_init)
  8432. {
  8433. if (pool->stratum_active)
  8434. return true;
  8435. }
  8436. else
  8437. if (!pool->idle)
  8438. {
  8439. timer_set_now(&tv_now);
  8440. if (pool_recently_got_work(pool, &tv_now))
  8441. return true;
  8442. }
  8443. mutex_lock(&pool->pool_test_lock);
  8444. if (pool->stratum_init)
  8445. {
  8446. ret = pool->stratum_active;
  8447. goto out;
  8448. }
  8449. timer_set_now(&tv_now);
  8450. if (pool->idle)
  8451. {
  8452. if (timer_elapsed(&pool->tv_idle, &tv_now) < 30)
  8453. goto out;
  8454. }
  8455. else
  8456. if (pool_recently_got_work(pool, &tv_now))
  8457. {
  8458. ret = true;
  8459. goto out;
  8460. }
  8461. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  8462. /* This is the central point we activate stratum when we can */
  8463. curl = curl_easy_init();
  8464. if (unlikely(!curl)) {
  8465. applog(LOG_ERR, "CURL initialisation failed");
  8466. goto out;
  8467. }
  8468. if (!(want_gbt || want_getwork))
  8469. goto nohttp;
  8470. work = make_work();
  8471. /* Probe for GBT support on first pass */
  8472. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  8473. tryagain:
  8474. rpc_req = prepare_rpc_req_probe(work, proto, NULL, pool);
  8475. work->pool = pool;
  8476. if (!rpc_req)
  8477. goto out;
  8478. pool->probed = false;
  8479. cgtime(&tv_getwork);
  8480. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  8481. true, false, &rolltime, pool, false);
  8482. cgtime(&tv_getwork_reply);
  8483. free(rpc_req);
  8484. /* Detect if a http getwork pool has an X-Stratum header at startup,
  8485. * and if so, switch to that in preference to getwork if it works */
  8486. if (pool->stratum_url && want_stratum && pool_may_redirect_to(pool, pool->stratum_url) && (pool->has_stratum || stratum_works(pool))) {
  8487. if (!pool->has_stratum) {
  8488. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  8489. if (!pool->rpc_url)
  8490. pool_set_uri(pool, strdup(pool->stratum_url));
  8491. pool->has_stratum = true;
  8492. }
  8493. free_work(work);
  8494. if (val)
  8495. json_decref(val);
  8496. retry_stratum:
  8497. ;
  8498. /* We create the stratum thread for each pool just after
  8499. * successful authorisation. Once the init flag has been set
  8500. * we never unset it and the stratum thread is responsible for
  8501. * setting/unsetting the active flag */
  8502. bool init = pool_tset(pool, &pool->stratum_init);
  8503. if (!init) {
  8504. ret = initiate_stratum(pool) && auth_stratum(pool);
  8505. if (ret)
  8506. {
  8507. detect_algo = 2;
  8508. init_stratum_thread(pool);
  8509. }
  8510. else
  8511. {
  8512. pool_tclear(pool, &pool->stratum_init);
  8513. pool->tv_idle = tv_getwork_reply;
  8514. }
  8515. goto out;
  8516. }
  8517. ret = pool->stratum_active;
  8518. goto out;
  8519. }
  8520. else if (pool->has_stratum)
  8521. shutdown_stratum(pool);
  8522. if (val) {
  8523. bool rc;
  8524. json_t *res;
  8525. res = json_object_get(val, "result");
  8526. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  8527. goto badwork;
  8528. work->rolltime = rolltime;
  8529. rc = work_decode(pool, work, val);
  8530. if (rc) {
  8531. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  8532. pool->pool_no, pool->rpc_url);
  8533. work->pool = pool;
  8534. copy_time(&work->tv_getwork, &tv_getwork);
  8535. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  8536. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  8537. calc_diff(work, 0);
  8538. update_last_work(work);
  8539. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  8540. stage_work(work);
  8541. total_getworks++;
  8542. pool->getwork_requested++;
  8543. ret = true;
  8544. pool->tv_idle = tv_getwork_reply;
  8545. } else {
  8546. badwork:
  8547. json_decref(val);
  8548. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  8549. pool->pool_no, pool->rpc_url);
  8550. pool->proto = proto = pool_protocol_fallback(proto);
  8551. if (PLP_NONE != proto)
  8552. goto tryagain;
  8553. pool->tv_idle = tv_getwork_reply;
  8554. free_work(work);
  8555. goto out;
  8556. }
  8557. json_decref(val);
  8558. if (proto != pool->proto) {
  8559. pool->proto = proto;
  8560. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  8561. }
  8562. if (pool->lp_url)
  8563. goto out;
  8564. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  8565. const struct blktmpl_longpoll_req *lp;
  8566. if (work->tr && (lp = blktmpl_get_longpoll(work->tr->tmpl))) {
  8567. // NOTE: work_decode takes care of lp id
  8568. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  8569. if (!pool->lp_url)
  8570. {
  8571. ret = false;
  8572. goto out;
  8573. }
  8574. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  8575. }
  8576. else
  8577. if (pool->hdr_path && want_getwork) {
  8578. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  8579. if (!pool->lp_url)
  8580. {
  8581. ret = false;
  8582. goto out;
  8583. }
  8584. pool->lp_proto = PLP_GETWORK;
  8585. } else
  8586. pool->lp_url = NULL;
  8587. if (want_longpoll && !pool->lp_started) {
  8588. pool->lp_started = true;
  8589. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8590. quit(1, "Failed to create pool longpoll thread");
  8591. }
  8592. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  8593. pool->proto = proto;
  8594. goto tryagain;
  8595. } else {
  8596. pool->tv_idle = tv_getwork_reply;
  8597. free_work(work);
  8598. nohttp:
  8599. /* If we failed to parse a getwork, this could be a stratum
  8600. * url without the prefix stratum+tcp:// so let's check it */
  8601. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  8602. pool->has_stratum = true;
  8603. goto retry_stratum;
  8604. }
  8605. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  8606. pool->pool_no, pool->rpc_url);
  8607. if (!pinging)
  8608. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  8609. }
  8610. out:
  8611. if (curl)
  8612. curl_easy_cleanup(curl);
  8613. mutex_unlock(&pool->pool_test_lock);
  8614. return ret;
  8615. }
  8616. static void pool_resus(struct pool *pool)
  8617. {
  8618. if (pool->enabled == POOL_ENABLED && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8619. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  8620. else
  8621. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  8622. }
  8623. static
  8624. void *cmd_idle_thread(void * const __maybe_unused userp)
  8625. {
  8626. pthread_detach(pthread_self());
  8627. RenameThread("cmd-idle");
  8628. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8629. sleep(opt_log_interval);
  8630. pthread_testcancel();
  8631. run_cmd(cmd_idle);
  8632. return NULL;
  8633. }
  8634. static struct work *hash_pop(struct cgpu_info * const proc)
  8635. {
  8636. int hc;
  8637. struct work *work, *work_found, *tmp;
  8638. enum {
  8639. HPWS_NONE,
  8640. HPWS_LOWDIFF,
  8641. HPWS_SPARE,
  8642. HPWS_ROLLABLE,
  8643. HPWS_PERFECT,
  8644. } work_score = HPWS_NONE;
  8645. bool did_cmd_idle = false;
  8646. pthread_t cmd_idle_thr;
  8647. retry:
  8648. mutex_lock(stgd_lock);
  8649. while (true)
  8650. {
  8651. work_found = NULL;
  8652. work_score = 0;
  8653. hc = HASH_COUNT(staged_work);
  8654. HASH_ITER(hh, staged_work, work, tmp)
  8655. {
  8656. const struct mining_algorithm * const work_malgo = work_mining_algorithm(work);
  8657. const float min_nonce_diff = drv_min_nonce_diff(proc->drv, proc, work_malgo);
  8658. #define FOUND_WORK(score) do{ \
  8659. if (work_score < score) \
  8660. { \
  8661. work_found = work; \
  8662. work_score = score; \
  8663. } \
  8664. continue; \
  8665. }while(0)
  8666. if (min_nonce_diff < work->work_difficulty)
  8667. {
  8668. if (min_nonce_diff < 0)
  8669. continue;
  8670. FOUND_WORK(HPWS_LOWDIFF);
  8671. }
  8672. if (work->spare)
  8673. FOUND_WORK(HPWS_SPARE);
  8674. if (work->rolltime && hc > staged_rollable)
  8675. FOUND_WORK(HPWS_ROLLABLE);
  8676. #undef FOUND_WORK
  8677. // Good match
  8678. work_found = work;
  8679. work_score = HPWS_PERFECT;
  8680. break;
  8681. }
  8682. if (work_found)
  8683. {
  8684. work = work_found;
  8685. break;
  8686. }
  8687. // Failed to get a usable work
  8688. if (unlikely(staged_full))
  8689. {
  8690. if (likely(opt_queue < 10 + mining_threads))
  8691. {
  8692. ++opt_queue;
  8693. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  8694. }
  8695. else
  8696. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  8697. staged_full = false; // Let it fill up before triggering an underrun again
  8698. no_work = true;
  8699. }
  8700. pthread_cond_signal(&gws_cond);
  8701. if (cmd_idle && !did_cmd_idle)
  8702. {
  8703. if (likely(!pthread_create(&cmd_idle_thr, NULL, cmd_idle_thread, NULL)))
  8704. did_cmd_idle = true;
  8705. }
  8706. pthread_cond_wait(&getq->cond, stgd_lock);
  8707. }
  8708. if (did_cmd_idle)
  8709. pthread_cancel(cmd_idle_thr);
  8710. no_work = false;
  8711. if (can_roll(work) && should_roll(work))
  8712. {
  8713. // Instead of consuming it, force it to be cloned and grab the clone
  8714. mutex_unlock(stgd_lock);
  8715. clone_available();
  8716. goto retry;
  8717. }
  8718. unstage_work(work);
  8719. /* Signal the getwork scheduler to look for more work */
  8720. pthread_cond_signal(&gws_cond);
  8721. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  8722. pthread_cond_signal(&getq->cond);
  8723. mutex_unlock(stgd_lock);
  8724. work->pool->last_work_time = time(NULL);
  8725. cgtime(&work->pool->tv_last_work_time);
  8726. return work;
  8727. }
  8728. /* Clones work by rolling it if possible, and returning a clone instead of the
  8729. * original work item which gets staged again to possibly be rolled again in
  8730. * the future */
  8731. static struct work *clone_work(struct work *work)
  8732. {
  8733. int mrs = mining_threads + opt_queue - total_staged(false);
  8734. struct work *work_clone;
  8735. bool cloned;
  8736. if (mrs < 1)
  8737. return work;
  8738. cloned = false;
  8739. work_clone = make_clone(work);
  8740. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  8741. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  8742. stage_work(work_clone);
  8743. roll_work(work);
  8744. work_clone = make_clone(work);
  8745. /* Roll it again to prevent duplicates should this be used
  8746. * directly later on */
  8747. roll_work(work);
  8748. cloned = true;
  8749. }
  8750. if (cloned) {
  8751. stage_work(work);
  8752. return work_clone;
  8753. }
  8754. free_work(work_clone);
  8755. return work;
  8756. }
  8757. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  8758. {
  8759. unsigned char hash1[32];
  8760. sha256(data, len, hash1);
  8761. sha256(hash1, 32, hash);
  8762. }
  8763. /* PDiff 1 is a 256 bit unsigned integer of
  8764. * 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  8765. * so we use a big endian 32 bit unsigned integer positioned at the Nth byte to
  8766. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  8767. static void pdiff_target_leadzero(void * const target_p, double diff)
  8768. {
  8769. uint8_t *target = target_p;
  8770. diff *= 0x100000000;
  8771. int skip = log2(diff) / 8;
  8772. if (skip)
  8773. {
  8774. if (skip > 0x1c)
  8775. skip = 0x1c;
  8776. diff /= pow(0x100, skip);
  8777. memset(target, 0, skip);
  8778. }
  8779. uint32_t n = 0xffffffff;
  8780. n = (double)n / diff;
  8781. n = htobe32(n);
  8782. memcpy(&target[skip], &n, sizeof(n));
  8783. memset(&target[skip + sizeof(n)], 0xff, 32 - (skip + sizeof(n)));
  8784. }
  8785. void set_target_to_pdiff(void * const dest_target, const double pdiff)
  8786. {
  8787. unsigned char rtarget[32];
  8788. pdiff_target_leadzero(rtarget, pdiff);
  8789. swab256(dest_target, rtarget);
  8790. if (opt_debug) {
  8791. char htarget[65];
  8792. bin2hex(htarget, rtarget, 32);
  8793. applog(LOG_DEBUG, "Generated target %s", htarget);
  8794. }
  8795. }
  8796. void set_target_to_bdiff(void * const dest_target, const double bdiff)
  8797. {
  8798. set_target_to_pdiff(dest_target, bdiff_to_pdiff(bdiff));
  8799. }
  8800. void _test_target(void * const funcp, const char * const funcname, const bool little_endian, const void * const expectp, const double diff)
  8801. {
  8802. uint8_t bufr[32], buf[32], expectr[32], expect[32];
  8803. int off;
  8804. void (*func)(void *, double) = funcp;
  8805. func(little_endian ? bufr : buf, diff);
  8806. if (little_endian)
  8807. swab256(buf, bufr);
  8808. swap32tobe(expect, expectp, 256/32);
  8809. // Fuzzy comparison: the first 32 bits set must match, and the actual target must be >= the expected
  8810. for (off = 0; off < 28 && !buf[off]; ++off)
  8811. {}
  8812. if (memcmp(&buf[off], &expect[off], 4))
  8813. {
  8814. testfail: ;
  8815. ++unittest_failures;
  8816. char hexbuf[65], expectbuf[65];
  8817. bin2hex(hexbuf, buf, 32);
  8818. bin2hex(expectbuf, expect, 32);
  8819. applogr(, LOG_WARNING, "%s test failed: diff %g got %s (expected %s)",
  8820. funcname, diff, hexbuf, expectbuf);
  8821. }
  8822. if (!little_endian)
  8823. swab256(bufr, buf);
  8824. swab256(expectr, expect);
  8825. if (!hash_target_check(expectr, bufr))
  8826. goto testfail;
  8827. }
  8828. #define TEST_TARGET(func, le, expect, diff) \
  8829. _test_target(func, #func, le, expect, diff)
  8830. void test_target()
  8831. {
  8832. uint32_t expect[8] = {0};
  8833. // bdiff 1 should be exactly 00000000ffff0000000006f29cfd29510a6caee84634e86a57257cf03152537f due to floating-point imprecision (pdiff1 / 1.0000152590218966)
  8834. expect[0] = 0x0000ffff;
  8835. TEST_TARGET(set_target_to_bdiff, true, expect, 1./0x10000);
  8836. expect[0] = 0;
  8837. expect[1] = 0xffff0000;
  8838. TEST_TARGET(set_target_to_bdiff, true, expect, 1);
  8839. expect[1] >>= 1;
  8840. TEST_TARGET(set_target_to_bdiff, true, expect, 2);
  8841. expect[1] >>= 3;
  8842. TEST_TARGET(set_target_to_bdiff, true, expect, 0x10);
  8843. expect[1] >>= 4;
  8844. TEST_TARGET(set_target_to_bdiff, true, expect, 0x100);
  8845. memset(&expect[1], '\xff', 28);
  8846. expect[0] = 0x0000ffff;
  8847. TEST_TARGET(set_target_to_pdiff, true, expect, 1./0x10000);
  8848. expect[0] = 0;
  8849. TEST_TARGET(set_target_to_pdiff, true, expect, 1);
  8850. expect[1] >>= 1;
  8851. TEST_TARGET(set_target_to_pdiff, true, expect, 2);
  8852. expect[1] >>= 3;
  8853. TEST_TARGET(set_target_to_pdiff, true, expect, 0x10);
  8854. expect[1] >>= 4;
  8855. TEST_TARGET(set_target_to_pdiff, true, expect, 0x100);
  8856. }
  8857. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  8858. {
  8859. *dst = *src;
  8860. if (dst->tr)
  8861. tmpl_incref(dst->tr);
  8862. dst->nonce1 = maybe_strdup(src->nonce1);
  8863. dst->job_id = maybe_strdup(src->job_id);
  8864. bytes_cpy(&dst->coinbase, &src->coinbase);
  8865. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  8866. }
  8867. void stratum_work_clean(struct stratum_work * const swork)
  8868. {
  8869. if (swork->tr)
  8870. tmpl_decref(swork->tr);
  8871. free(swork->nonce1);
  8872. free(swork->job_id);
  8873. bytes_free(&swork->coinbase);
  8874. bytes_free(&swork->merkle_bin);
  8875. }
  8876. bool pool_has_usable_swork(const struct pool * const pool)
  8877. {
  8878. if (opt_benchmark)
  8879. return true;
  8880. if (pool->swork.tr)
  8881. {
  8882. // GBT
  8883. struct timeval tv_now;
  8884. timer_set_now(&tv_now);
  8885. return blkmk_time_left(pool->swork.tr->tmpl, tv_now.tv_sec);
  8886. }
  8887. return pool->stratum_notify;
  8888. }
  8889. /* Generates stratum based work based on the most recent notify information
  8890. * from the pool. This will keep generating work while a pool is down so we use
  8891. * other means to detect when the pool has died in stratum_thread */
  8892. static void gen_stratum_work(struct pool *pool, struct work *work)
  8893. {
  8894. clean_work(work);
  8895. cg_wlock(&pool->data_lock);
  8896. pool->swork.data_lock_p = &pool->data_lock;
  8897. const int n2size = pool->swork.n2size;
  8898. bytes_resize(&work->nonce2, n2size);
  8899. if (pool->nonce2sz < n2size)
  8900. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, n2size - pool->nonce2sz);
  8901. memcpy(bytes_buf(&work->nonce2),
  8902. #ifdef WORDS_BIGENDIAN
  8903. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  8904. &((char*)&pool->nonce2)[pool->nonce2off],
  8905. #else
  8906. &pool->nonce2,
  8907. #endif
  8908. pool->nonce2sz);
  8909. pool->nonce2++;
  8910. work->pool = pool;
  8911. work->work_restart_id = pool->swork.work_restart_id;
  8912. gen_stratum_work2(work, &pool->swork);
  8913. cgtime(&work->tv_staged);
  8914. }
  8915. void gen_stratum_work2(struct work *work, struct stratum_work *swork)
  8916. {
  8917. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  8918. uint8_t *merkle_bin;
  8919. uint32_t *data32, *swap32;
  8920. int i;
  8921. /* Generate coinbase */
  8922. coinbase = bytes_buf(&swork->coinbase);
  8923. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8924. /* Downgrade to a read lock to read off the variables */
  8925. if (swork->data_lock_p)
  8926. cg_dwlock(swork->data_lock_p);
  8927. /* Generate merkle root */
  8928. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  8929. memcpy(merkle_sha, merkle_root, 32);
  8930. merkle_bin = bytes_buf(&swork->merkle_bin);
  8931. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  8932. memcpy(merkle_sha + 32, merkle_bin, 32);
  8933. gen_hash(merkle_sha, merkle_root, 64);
  8934. memcpy(merkle_sha, merkle_root, 32);
  8935. }
  8936. data32 = (uint32_t *)merkle_sha;
  8937. swap32 = (uint32_t *)merkle_root;
  8938. flip32(swap32, data32);
  8939. memcpy(&work->data[0], swork->header1, 36);
  8940. memcpy(&work->data[36], merkle_root, 32);
  8941. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  8942. memcpy(&work->data[72], swork->diffbits, 4);
  8943. memset(&work->data[76], 0, 4); // nonce
  8944. memcpy(&work->data[80], workpadding_bin, 48);
  8945. work->ntime_roll_limits = swork->ntime_roll_limits;
  8946. /* Copy parameters required for share submission */
  8947. memcpy(work->target, swork->target, sizeof(work->target));
  8948. work->job_id = maybe_strdup(swork->job_id);
  8949. work->nonce1 = maybe_strdup(swork->nonce1);
  8950. if (swork->data_lock_p)
  8951. cg_runlock(swork->data_lock_p);
  8952. if (opt_debug)
  8953. {
  8954. char header[161];
  8955. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  8956. bin2hex(header, work->data, 80);
  8957. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8958. applog(LOG_DEBUG, "Generated stratum header %s", header);
  8959. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  8960. }
  8961. calc_midstate(work);
  8962. local_work++;
  8963. work->stratum = true;
  8964. work->blk.nonce = 0;
  8965. work->id = total_work++;
  8966. work->longpoll = false;
  8967. work->getwork_mode = GETWORK_MODE_STRATUM;
  8968. calc_diff(work, 0);
  8969. }
  8970. void request_work(struct thr_info *thr)
  8971. {
  8972. struct cgpu_info *cgpu = thr->cgpu;
  8973. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8974. /* Tell the watchdog thread this thread is waiting on getwork and
  8975. * should not be restarted */
  8976. thread_reportout(thr);
  8977. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  8978. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8979. {
  8980. if (proc->threads)
  8981. break;
  8982. thread_reportout(proc->thr[0]);
  8983. }
  8984. cgtime(&dev_stats->_get_start);
  8985. }
  8986. // FIXME: Make this non-blocking (and remove HACK above)
  8987. struct work *get_work(struct thr_info *thr)
  8988. {
  8989. const int thr_id = thr->id;
  8990. struct cgpu_info *cgpu = thr->cgpu;
  8991. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8992. struct cgminer_stats *pool_stats;
  8993. struct timeval tv_get;
  8994. struct work *work = NULL;
  8995. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  8996. while (!work) {
  8997. work = hash_pop(cgpu);
  8998. if (stale_work(work, false)) {
  8999. staged_full = false; // It wasn't really full, since it was stale :(
  9000. discard_work(work);
  9001. work = NULL;
  9002. wake_gws();
  9003. }
  9004. }
  9005. last_getwork = time(NULL);
  9006. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  9007. cgpu->proc_repr, work->id, thr_id);
  9008. work->thr_id = thr_id;
  9009. thread_reportin(thr);
  9010. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  9011. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  9012. {
  9013. if (proc->threads)
  9014. break;
  9015. thread_reportin(proc->thr[0]);
  9016. }
  9017. work->mined = true;
  9018. work->blk.nonce = 0;
  9019. cgtime(&tv_get);
  9020. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  9021. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  9022. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  9023. dev_stats->getwork_wait_max = tv_get;
  9024. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  9025. dev_stats->getwork_wait_min = tv_get;
  9026. ++dev_stats->getwork_calls;
  9027. pool_stats = &(work->pool->cgminer_stats);
  9028. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  9029. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  9030. pool_stats->getwork_wait_max = tv_get;
  9031. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  9032. pool_stats->getwork_wait_min = tv_get;
  9033. ++pool_stats->getwork_calls;
  9034. if (work->work_difficulty < 1)
  9035. {
  9036. const float min_nonce_diff = drv_min_nonce_diff(cgpu->drv, cgpu, work_mining_algorithm(work));
  9037. if (unlikely(work->work_difficulty < min_nonce_diff))
  9038. {
  9039. if (min_nonce_diff - work->work_difficulty > 1./0x10000000)
  9040. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  9041. cgpu->proc_repr);
  9042. work->nonce_diff = min_nonce_diff;
  9043. }
  9044. else
  9045. work->nonce_diff = work->work_difficulty;
  9046. }
  9047. else
  9048. work->nonce_diff = 1;
  9049. return work;
  9050. }
  9051. struct dupe_hash_elem {
  9052. uint8_t hash[0x20];
  9053. struct timeval tv_prune;
  9054. UT_hash_handle hh;
  9055. };
  9056. static
  9057. void _submit_work_async(struct work *work)
  9058. {
  9059. applog(LOG_DEBUG, "Pushing submit work to work thread");
  9060. if (opt_benchmark)
  9061. {
  9062. json_t * const jn = json_null(), *result = NULL;
  9063. work_check_for_block(work);
  9064. {
  9065. static struct dupe_hash_elem *dupe_hashes;
  9066. struct dupe_hash_elem *dhe, *dhetmp;
  9067. HASH_FIND(hh, dupe_hashes, &work->hash, sizeof(dhe->hash), dhe);
  9068. if (dhe)
  9069. result = json_string("duplicate");
  9070. else
  9071. {
  9072. struct timeval tv_now;
  9073. timer_set_now(&tv_now);
  9074. // Prune old entries
  9075. HASH_ITER(hh, dupe_hashes, dhe, dhetmp)
  9076. {
  9077. if (!timer_passed(&dhe->tv_prune, &tv_now))
  9078. break;
  9079. HASH_DEL(dupe_hashes, dhe);
  9080. free(dhe);
  9081. }
  9082. dhe = malloc(sizeof(*dhe));
  9083. memcpy(dhe->hash, work->hash, sizeof(dhe->hash));
  9084. timer_set_delay(&dhe->tv_prune, &tv_now, 337500000);
  9085. HASH_ADD(hh, dupe_hashes, hash, sizeof(dhe->hash), dhe);
  9086. }
  9087. }
  9088. if (result)
  9089. {}
  9090. else
  9091. if (stale_work(work, true))
  9092. {
  9093. char stalemsg[0x10];
  9094. snprintf(stalemsg, sizeof(stalemsg), "stale %us", benchmark_update_interval * (work->pool->work_restart_id - work->work_restart_id));
  9095. result = json_string(stalemsg);
  9096. }
  9097. else
  9098. result = json_incref(jn);
  9099. share_result(jn, result, jn, work, false, "");
  9100. free_work(work);
  9101. json_decref(result);
  9102. json_decref(jn);
  9103. return;
  9104. }
  9105. mutex_lock(&submitting_lock);
  9106. ++total_submitting;
  9107. DL_APPEND(submit_waiting, work);
  9108. mutex_unlock(&submitting_lock);
  9109. notifier_wake(submit_waiting_notifier);
  9110. }
  9111. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  9112. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  9113. {
  9114. if (tv_work_found)
  9115. copy_time(&work->tv_work_found, tv_work_found);
  9116. _submit_work_async(work);
  9117. }
  9118. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  9119. {
  9120. struct cgpu_info * const cgpu = thr->cgpu;
  9121. if (bad_nonce_p)
  9122. {
  9123. if (bad_nonce_p == UNKNOWN_NONCE)
  9124. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  9125. cgpu->proc_repr);
  9126. else
  9127. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  9128. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  9129. }
  9130. mutex_lock(&stats_lock);
  9131. hw_errors++;
  9132. ++cgpu->hw_errors;
  9133. if (bad_nonce_p)
  9134. {
  9135. total_bad_diff1 += nonce_diff;
  9136. cgpu->bad_diff1 += nonce_diff;
  9137. }
  9138. mutex_unlock(&stats_lock);
  9139. if (thr->cgpu->drv->hw_error)
  9140. thr->cgpu->drv->hw_error(thr);
  9141. }
  9142. void work_hash(struct work * const work)
  9143. {
  9144. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  9145. malgo->hash_data_f(work->hash, work->data);
  9146. }
  9147. static
  9148. bool test_hash(const void * const phash, const float diff)
  9149. {
  9150. const uint32_t * const hash = phash;
  9151. if (diff >= 1.)
  9152. // FIXME: > 1 should check more
  9153. return !hash[7];
  9154. const uint32_t Htarg = (uint32_t)ceil((1. / diff) - 1);
  9155. const uint32_t tmp_hash7 = le32toh(hash[7]);
  9156. applog(LOG_DEBUG, "htarget %08lx hash %08lx",
  9157. (long unsigned int)Htarg,
  9158. (long unsigned int)tmp_hash7);
  9159. return (tmp_hash7 <= Htarg);
  9160. }
  9161. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  9162. {
  9163. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  9164. *work_nonce = htole32(nonce);
  9165. work_hash(work);
  9166. if (!test_hash(work->hash, work->nonce_diff))
  9167. return TNR_BAD;
  9168. if (checktarget && !hash_target_check_v(work->hash, work->target))
  9169. {
  9170. bool high_hash = true;
  9171. struct pool * const pool = work->pool;
  9172. if (pool->stratum_active)
  9173. {
  9174. // 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
  9175. if (memcmp(pool->next_target, work->target, sizeof(work->target)))
  9176. {
  9177. applog(LOG_DEBUG, "Stratum pool %u target has changed since work job issued, checking that too",
  9178. pool->pool_no);
  9179. if (hash_target_check_v(work->hash, pool->next_target))
  9180. high_hash = false;
  9181. }
  9182. }
  9183. if (high_hash)
  9184. return TNR_HIGH;
  9185. }
  9186. return TNR_GOOD;
  9187. }
  9188. /* Returns true if nonce for work was a valid share */
  9189. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  9190. {
  9191. return submit_noffset_nonce(thr, work, nonce, 0);
  9192. }
  9193. /* Allows drivers to submit work items where the driver has changed the ntime
  9194. * value by noffset. Must be only used with a work protocol that does not ntime
  9195. * roll itself intrinsically to generate work (eg stratum). We do not touch
  9196. * the original work struct, but the copy of it only. */
  9197. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  9198. int noffset)
  9199. {
  9200. struct work *work = make_work();
  9201. _copy_work(work, work_in, noffset);
  9202. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  9203. struct timeval tv_work_found;
  9204. enum test_nonce2_result res;
  9205. bool ret = true;
  9206. thread_reportout(thr);
  9207. cgtime(&tv_work_found);
  9208. *work_nonce = htole32(nonce);
  9209. work->thr_id = thr->id;
  9210. /* Do one last check before attempting to submit the work */
  9211. /* Side effect: sets work->data and work->hash for us */
  9212. res = test_nonce2(work, nonce);
  9213. if (unlikely(res == TNR_BAD))
  9214. {
  9215. inc_hw_errors(thr, work, nonce);
  9216. ret = false;
  9217. goto out;
  9218. }
  9219. mutex_lock(&stats_lock);
  9220. total_diff1 += work->nonce_diff;
  9221. thr ->cgpu->diff1 += work->nonce_diff;
  9222. work->pool->diff1 += work->nonce_diff;
  9223. thr->cgpu->last_device_valid_work = time(NULL);
  9224. mutex_unlock(&stats_lock);
  9225. if (noncelog_file)
  9226. noncelog(work);
  9227. if (res == TNR_HIGH)
  9228. {
  9229. // Share above target, normal
  9230. /* Check the diff of the share, even if it didn't reach the
  9231. * target, just to set the best share value if it's higher. */
  9232. share_diff(work);
  9233. goto out;
  9234. }
  9235. submit_work_async2(work, &tv_work_found);
  9236. work = NULL; // Taken by submit_work_async2
  9237. out:
  9238. if (work)
  9239. free_work(work);
  9240. thread_reportin(thr);
  9241. return ret;
  9242. }
  9243. // return true of we should stop working on this piece of work
  9244. // returning false means we will keep scanning for a nonce
  9245. // assumptions: work->blk.nonce is the number of nonces completed in the work
  9246. // see minerloop_scanhash comments for more details & usage
  9247. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t max_hashes)
  9248. {
  9249. if (work->blk.nonce == 0xffffffff || // known we are scanning a full nonce range
  9250. wdiff->tv_sec > opt_scantime || // scan-time has elapsed (user specified, default 60s)
  9251. work->blk.nonce >= 0xfffffffe - max_hashes || // are there enough nonces left in the work
  9252. max_hashes >= 0xfffffffe || // assume we are scanning a full nonce range
  9253. stale_work(work, false)) // work is stale
  9254. return true;
  9255. return false;
  9256. }
  9257. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  9258. {
  9259. struct cgpu_info *proc = thr->cgpu;
  9260. if (proc->threads > 1)
  9261. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  9262. else
  9263. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  9264. }
  9265. // Called by asynchronous minerloops, when they find their processor should be disabled
  9266. void mt_disable_start(struct thr_info *mythr)
  9267. {
  9268. struct cgpu_info *cgpu = mythr->cgpu;
  9269. struct device_drv *drv = cgpu->drv;
  9270. if (drv->thread_disable)
  9271. drv->thread_disable(mythr);
  9272. hashmeter2(mythr);
  9273. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  9274. mythr->rolling = mythr->cgpu->rolling = 0;
  9275. thread_reportout(mythr);
  9276. mythr->_mt_disable_called = true;
  9277. }
  9278. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  9279. * the driver tells us it's full so that it may extract the work item using
  9280. * the get_queued() function which adds it to the hashtable on
  9281. * cgpu->queued_work. */
  9282. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  9283. {
  9284. thread_reportout(mythr);
  9285. do {
  9286. bool need_work;
  9287. /* Do this lockless just to know if we need more unqueued work. */
  9288. need_work = (!cgpu->unqueued_work);
  9289. /* get_work is a blocking function so do it outside of lock
  9290. * to prevent deadlocks with other locks. */
  9291. if (need_work) {
  9292. struct work *work = get_work(mythr);
  9293. wr_lock(&cgpu->qlock);
  9294. /* Check we haven't grabbed work somehow between
  9295. * checking and picking up the lock. */
  9296. if (likely(!cgpu->unqueued_work))
  9297. cgpu->unqueued_work = work;
  9298. else
  9299. need_work = false;
  9300. wr_unlock(&cgpu->qlock);
  9301. if (unlikely(!need_work))
  9302. discard_work(work);
  9303. }
  9304. /* The queue_full function should be used by the driver to
  9305. * actually place work items on the physical device if it
  9306. * does have a queue. */
  9307. } while (drv->queue_full && !drv->queue_full(cgpu));
  9308. }
  9309. /* Add a work item to a cgpu's queued hashlist */
  9310. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  9311. {
  9312. cgpu->queued_count++;
  9313. HASH_ADD_INT(cgpu->queued_work, id, work);
  9314. }
  9315. /* This function is for retrieving one work item from the unqueued pointer and
  9316. * adding it to the hashtable of queued work. Code using this function must be
  9317. * able to handle NULL as a return which implies there is no work available. */
  9318. struct work *get_queued(struct cgpu_info *cgpu)
  9319. {
  9320. struct work *work = NULL;
  9321. wr_lock(&cgpu->qlock);
  9322. if (cgpu->unqueued_work) {
  9323. work = cgpu->unqueued_work;
  9324. if (unlikely(stale_work(work, false))) {
  9325. discard_work(work);
  9326. work = NULL;
  9327. wake_gws();
  9328. } else
  9329. __add_queued(cgpu, work);
  9330. cgpu->unqueued_work = NULL;
  9331. }
  9332. wr_unlock(&cgpu->qlock);
  9333. return work;
  9334. }
  9335. void add_queued(struct cgpu_info *cgpu, struct work *work)
  9336. {
  9337. wr_lock(&cgpu->qlock);
  9338. __add_queued(cgpu, work);
  9339. wr_unlock(&cgpu->qlock);
  9340. }
  9341. /* Get fresh work and add it to cgpu's queued hashlist */
  9342. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  9343. {
  9344. struct work *work = get_work(thr);
  9345. add_queued(cgpu, work);
  9346. return work;
  9347. }
  9348. /* This function is for finding an already queued work item in the
  9349. * given que hashtable. Code using this function must be able
  9350. * to handle NULL as a return which implies there is no matching work.
  9351. * The calling function must lock access to the que if it is required.
  9352. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9353. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9354. {
  9355. struct work *work, *tmp, *ret = NULL;
  9356. HASH_ITER(hh, que, work, tmp) {
  9357. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  9358. memcmp(work->data + offset, data, datalen) == 0) {
  9359. ret = work;
  9360. break;
  9361. }
  9362. }
  9363. return ret;
  9364. }
  9365. /* This function is for finding an already queued work item in the
  9366. * device's queued_work hashtable. Code using this function must be able
  9367. * to handle NULL as a return which implies there is no matching work.
  9368. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9369. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9370. {
  9371. struct work *ret;
  9372. rd_lock(&cgpu->qlock);
  9373. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9374. rd_unlock(&cgpu->qlock);
  9375. return ret;
  9376. }
  9377. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9378. {
  9379. struct work *work, *ret = NULL;
  9380. rd_lock(&cgpu->qlock);
  9381. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9382. if (work)
  9383. ret = copy_work(work);
  9384. rd_unlock(&cgpu->qlock);
  9385. return ret;
  9386. }
  9387. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  9388. {
  9389. cgpu->queued_count--;
  9390. HASH_DEL(cgpu->queued_work, work);
  9391. }
  9392. /* This iterates over a queued hashlist finding work started more than secs
  9393. * seconds ago and discards the work as completed. The driver must set the
  9394. * work->tv_work_start value appropriately. Returns the number of items aged. */
  9395. int age_queued_work(struct cgpu_info *cgpu, double secs)
  9396. {
  9397. struct work *work, *tmp;
  9398. struct timeval tv_now;
  9399. int aged = 0;
  9400. cgtime(&tv_now);
  9401. wr_lock(&cgpu->qlock);
  9402. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  9403. if (tdiff(&tv_now, &work->tv_work_start) > secs) {
  9404. __work_completed(cgpu, work);
  9405. aged++;
  9406. }
  9407. }
  9408. wr_unlock(&cgpu->qlock);
  9409. return aged;
  9410. }
  9411. /* This function should be used by queued device drivers when they're sure
  9412. * the work struct is no longer in use. */
  9413. void work_completed(struct cgpu_info *cgpu, struct work *work)
  9414. {
  9415. wr_lock(&cgpu->qlock);
  9416. __work_completed(cgpu, work);
  9417. wr_unlock(&cgpu->qlock);
  9418. free_work(work);
  9419. }
  9420. /* Combines find_queued_work_bymidstate and work_completed in one function
  9421. * withOUT destroying the work so the driver must free it. */
  9422. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9423. {
  9424. struct work *work;
  9425. wr_lock(&cgpu->qlock);
  9426. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9427. if (work)
  9428. __work_completed(cgpu, work);
  9429. wr_unlock(&cgpu->qlock);
  9430. return work;
  9431. }
  9432. void flush_queue(struct cgpu_info *cgpu)
  9433. {
  9434. struct work *work = NULL;
  9435. wr_lock(&cgpu->qlock);
  9436. work = cgpu->unqueued_work;
  9437. cgpu->unqueued_work = NULL;
  9438. wr_unlock(&cgpu->qlock);
  9439. if (work) {
  9440. free_work(work);
  9441. applog(LOG_DEBUG, "Discarded queued work item");
  9442. }
  9443. }
  9444. /* This version of hash work is for devices that are fast enough to always
  9445. * perform a full nonce range and need a queue to maintain the device busy.
  9446. * Work creation and destruction is not done from within this function
  9447. * directly. */
  9448. void hash_queued_work(struct thr_info *mythr)
  9449. {
  9450. const long cycle = opt_log_interval / 5 ? : 1;
  9451. struct timeval tv_start = {0, 0}, tv_end;
  9452. struct cgpu_info *cgpu = mythr->cgpu;
  9453. struct device_drv *drv = cgpu->drv;
  9454. const int thr_id = mythr->id;
  9455. int64_t hashes_done = 0;
  9456. if (unlikely(cgpu->deven != DEV_ENABLED))
  9457. mt_disable(mythr);
  9458. while (likely(!cgpu->shutdown)) {
  9459. struct timeval diff;
  9460. int64_t hashes;
  9461. fill_queue(mythr, cgpu, drv, thr_id);
  9462. thread_reportin(mythr);
  9463. hashes = drv->scanwork(mythr);
  9464. /* Reset the bool here in case the driver looks for it
  9465. * synchronously in the scanwork loop. */
  9466. mythr->work_restart = false;
  9467. if (unlikely(hashes == -1 )) {
  9468. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  9469. cgpu->deven = DEV_DISABLED;
  9470. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  9471. mt_disable(mythr);
  9472. }
  9473. hashes_done += hashes;
  9474. cgtime(&tv_end);
  9475. timersub(&tv_end, &tv_start, &diff);
  9476. if (diff.tv_sec >= cycle) {
  9477. hashmeter(thr_id, &diff, hashes_done);
  9478. hashes_done = 0;
  9479. copy_time(&tv_start, &tv_end);
  9480. }
  9481. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  9482. mt_disable(mythr);
  9483. if (unlikely(mythr->work_restart)) {
  9484. flush_queue(cgpu);
  9485. if (drv->flush_work)
  9486. drv->flush_work(cgpu);
  9487. }
  9488. }
  9489. // cgpu->deven = DEV_DISABLED; set in miner_thread
  9490. }
  9491. // Called by minerloop, when it is re-enabling a processor
  9492. void mt_disable_finish(struct thr_info *mythr)
  9493. {
  9494. struct device_drv *drv = mythr->cgpu->drv;
  9495. thread_reportin(mythr);
  9496. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  9497. if (drv->thread_enable)
  9498. drv->thread_enable(mythr);
  9499. mythr->_mt_disable_called = false;
  9500. }
  9501. // Called by synchronous minerloops, when they find their processor should be disabled
  9502. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  9503. void mt_disable(struct thr_info *mythr)
  9504. {
  9505. const struct cgpu_info * const cgpu = mythr->cgpu;
  9506. mt_disable_start(mythr);
  9507. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  9508. do {
  9509. notifier_read(mythr->notifier);
  9510. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  9511. mt_disable_finish(mythr);
  9512. }
  9513. enum {
  9514. STAT_SLEEP_INTERVAL = 1,
  9515. STAT_CTR_INTERVAL = 10000000,
  9516. FAILURE_INTERVAL = 30,
  9517. };
  9518. /* Stage another work item from the work returned in a longpoll */
  9519. 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)
  9520. {
  9521. bool rc;
  9522. work->rolltime = rolltime;
  9523. rc = work_decode(pool, work, val);
  9524. if (unlikely(!rc)) {
  9525. applog(LOG_ERR, "Could not convert longpoll data to work");
  9526. free_work(work);
  9527. return;
  9528. }
  9529. total_getworks++;
  9530. pool->getwork_requested++;
  9531. work->pool = pool;
  9532. copy_time(&work->tv_getwork, tv_lp);
  9533. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  9534. calc_diff(work, 0);
  9535. if (pool->enabled == POOL_REJECTING)
  9536. work->mandatory = true;
  9537. work->longpoll = true;
  9538. work->getwork_mode = GETWORK_MODE_LP;
  9539. update_last_work(work);
  9540. /* We'll be checking this work item twice, but we already know it's
  9541. * from a new block so explicitly force the new block detection now
  9542. * rather than waiting for it to hit the stage thread. This also
  9543. * allows testwork to know whether LP discovered the block or not. */
  9544. test_work_current(work);
  9545. /* Don't use backup LPs as work if we have failover-only enabled. Use
  9546. * the longpoll work from a pool that has been rejecting shares as a
  9547. * way to detect when the pool has recovered.
  9548. */
  9549. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  9550. free_work(work);
  9551. return;
  9552. }
  9553. work = clone_work(work);
  9554. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  9555. stage_work(work);
  9556. applog(LOG_DEBUG, "Converted longpoll data to work");
  9557. }
  9558. /* If we want longpoll, enable it for the chosen default pool, or, if
  9559. * the pool does not support longpoll, find the first one that does
  9560. * and use its longpoll support */
  9561. static
  9562. struct pool *_select_longpoll_pool(struct pool *cp, bool(*func)(struct pool *))
  9563. {
  9564. int i;
  9565. if (func(cp))
  9566. return cp;
  9567. for (i = 0; i < total_pools; i++) {
  9568. struct pool *pool = pools[i];
  9569. if (cp->goal != pool->goal)
  9570. continue;
  9571. if (func(pool))
  9572. return pool;
  9573. }
  9574. return NULL;
  9575. }
  9576. /* This will make the longpoll thread wait till it's the current pool, or it
  9577. * has been flagged as rejecting, before attempting to open any connections.
  9578. */
  9579. static void wait_lpcurrent(struct pool *pool)
  9580. {
  9581. mutex_lock(&lp_lock);
  9582. while (!cnx_needed(pool))
  9583. {
  9584. pool->lp_active = false;
  9585. pthread_cond_wait(&lp_cond, &lp_lock);
  9586. }
  9587. mutex_unlock(&lp_lock);
  9588. }
  9589. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  9590. struct pool *pool = vpool;
  9591. curl_socket_t sock = bfg_socket(addr->family, addr->socktype, addr->protocol);
  9592. pool->lp_socket = sock;
  9593. return sock;
  9594. }
  9595. static void *longpoll_thread(void *userdata)
  9596. {
  9597. struct pool *cp = (struct pool *)userdata;
  9598. /* This *pool is the source of the actual longpoll, not the pool we've
  9599. * tied it to */
  9600. struct timeval start, reply, end;
  9601. struct pool *pool = NULL;
  9602. char threadname[20];
  9603. CURL *curl = NULL;
  9604. int failures = 0;
  9605. char *lp_url;
  9606. int rolltime;
  9607. #ifndef HAVE_PTHREAD_CANCEL
  9608. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9609. #endif
  9610. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  9611. RenameThread(threadname);
  9612. curl = curl_easy_init();
  9613. if (unlikely(!curl)) {
  9614. applog(LOG_ERR, "CURL initialisation failed");
  9615. return NULL;
  9616. }
  9617. retry_pool:
  9618. pool = select_longpoll_pool(cp);
  9619. if (!pool) {
  9620. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  9621. while (!pool) {
  9622. cgsleep_ms(60000);
  9623. pool = select_longpoll_pool(cp);
  9624. }
  9625. }
  9626. if (pool->has_stratum) {
  9627. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9628. cp->rpc_url, pool->rpc_url);
  9629. goto out;
  9630. }
  9631. /* Any longpoll from any pool is enough for this to be true */
  9632. pool->goal->have_longpoll = true;
  9633. wait_lpcurrent(cp);
  9634. {
  9635. lp_url = pool->lp_url;
  9636. if (cp == pool)
  9637. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  9638. else
  9639. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  9640. }
  9641. while (42) {
  9642. json_t *val, *soval;
  9643. struct work *work = make_work();
  9644. char *lpreq;
  9645. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id, pool);
  9646. work->pool = pool;
  9647. if (!lpreq)
  9648. {
  9649. free_work(work);
  9650. goto lpfail;
  9651. }
  9652. wait_lpcurrent(cp);
  9653. cgtime(&start);
  9654. /* Longpoll connections can be persistent for a very long time
  9655. * and any number of issues could have come up in the meantime
  9656. * so always establish a fresh connection instead of relying on
  9657. * a persistent one. */
  9658. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  9659. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  9660. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  9661. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  9662. lpreq, false, true, &rolltime, pool, false);
  9663. pool->lp_socket = CURL_SOCKET_BAD;
  9664. cgtime(&reply);
  9665. free(lpreq);
  9666. if (likely(val)) {
  9667. soval = json_object_get(json_object_get(val, "result"), "submitold");
  9668. if (soval)
  9669. pool->submit_old = json_is_true(soval);
  9670. else
  9671. pool->submit_old = false;
  9672. convert_to_work(val, rolltime, pool, work, &start, &reply);
  9673. failures = 0;
  9674. json_decref(val);
  9675. } else {
  9676. /* Some pools regularly drop the longpoll request so
  9677. * only see this as longpoll failure if it happens
  9678. * immediately and just restart it the rest of the
  9679. * time. */
  9680. cgtime(&end);
  9681. free_work(work);
  9682. if (end.tv_sec - start.tv_sec <= 30)
  9683. {
  9684. if (failures == 1)
  9685. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  9686. lpfail:
  9687. cgsleep_ms(30000);
  9688. }
  9689. }
  9690. if (pool != cp) {
  9691. pool = select_longpoll_pool(cp);
  9692. if (pool->has_stratum) {
  9693. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9694. cp->rpc_url, pool->rpc_url);
  9695. break;
  9696. }
  9697. if (unlikely(!pool))
  9698. goto retry_pool;
  9699. }
  9700. if (unlikely(pool->removed))
  9701. break;
  9702. }
  9703. out:
  9704. pool->lp_active = false;
  9705. curl_easy_cleanup(curl);
  9706. return NULL;
  9707. }
  9708. static void stop_longpoll(void)
  9709. {
  9710. int i;
  9711. want_longpoll = false;
  9712. for (i = 0; i < total_pools; ++i)
  9713. {
  9714. struct pool *pool = pools[i];
  9715. if (unlikely(!pool->lp_started))
  9716. continue;
  9717. pool->lp_started = false;
  9718. pthread_cancel(pool->longpoll_thread);
  9719. }
  9720. struct mining_goal_info *goal, *tmpgoal;
  9721. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  9722. {
  9723. goal->have_longpoll = false;
  9724. }
  9725. }
  9726. static void start_longpoll(void)
  9727. {
  9728. int i;
  9729. want_longpoll = true;
  9730. for (i = 0; i < total_pools; ++i)
  9731. {
  9732. struct pool *pool = pools[i];
  9733. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  9734. continue;
  9735. pool->lp_started = true;
  9736. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  9737. quit(1, "Failed to create pool longpoll thread");
  9738. }
  9739. }
  9740. void reinit_device(struct cgpu_info *cgpu)
  9741. {
  9742. if (cgpu->drv->reinit_device)
  9743. cgpu->drv->reinit_device(cgpu);
  9744. }
  9745. static struct timeval rotate_tv;
  9746. /* We reap curls if they are unused for over a minute */
  9747. static void reap_curl(struct pool *pool)
  9748. {
  9749. struct curl_ent *ent, *iter;
  9750. struct timeval now;
  9751. int reaped = 0;
  9752. cgtime(&now);
  9753. mutex_lock(&pool->pool_lock);
  9754. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  9755. if (pool->curls < 2)
  9756. break;
  9757. if (now.tv_sec - ent->tv.tv_sec > 300) {
  9758. reaped++;
  9759. pool->curls--;
  9760. LL_DELETE(pool->curllist, ent);
  9761. curl_easy_cleanup(ent->curl);
  9762. free(ent);
  9763. }
  9764. }
  9765. mutex_unlock(&pool->pool_lock);
  9766. if (reaped)
  9767. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  9768. }
  9769. static void *watchpool_thread(void __maybe_unused *userdata)
  9770. {
  9771. int intervals = 0;
  9772. #ifndef HAVE_PTHREAD_CANCEL
  9773. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9774. #endif
  9775. RenameThread("watchpool");
  9776. while (42) {
  9777. struct timeval now;
  9778. int i;
  9779. if (++intervals > 20)
  9780. intervals = 0;
  9781. cgtime(&now);
  9782. for (i = 0; i < total_pools; i++) {
  9783. struct pool *pool = pools[i];
  9784. if (!opt_benchmark)
  9785. reap_curl(pool);
  9786. /* Get a rolling utility per pool over 10 mins */
  9787. if (intervals > 19) {
  9788. int shares = pool->diff1 - pool->last_shares;
  9789. pool->last_shares = pool->diff1;
  9790. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  9791. pool->shares = pool->utility;
  9792. }
  9793. if (pool->enabled == POOL_DISABLED)
  9794. continue;
  9795. /* Don't start testing any pools if the test threads
  9796. * from startup are still doing their first attempt. */
  9797. if (unlikely(pool->testing)) {
  9798. pthread_join(pool->test_thread, NULL);
  9799. }
  9800. /* Test pool is idle once every minute */
  9801. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  9802. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  9803. pool_resus(pool);
  9804. }
  9805. /* Only switch pools if the failback pool has been
  9806. * alive for more than 5 minutes (default) to prevent
  9807. * intermittently failing pools from being used. */
  9808. 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)
  9809. {
  9810. if (opt_fail_switch_delay % 60)
  9811. applog(LOG_WARNING, "Pool %d %s stable for %d second%s",
  9812. pool->pool_no, pool->rpc_url,
  9813. opt_fail_switch_delay,
  9814. (opt_fail_switch_delay == 1 ? "" : "s"));
  9815. else
  9816. applog(LOG_WARNING, "Pool %d %s stable for %d minute%s",
  9817. pool->pool_no, pool->rpc_url,
  9818. opt_fail_switch_delay / 60,
  9819. (opt_fail_switch_delay == 60 ? "" : "s"));
  9820. switch_pools(NULL);
  9821. }
  9822. }
  9823. if (current_pool()->idle)
  9824. switch_pools(NULL);
  9825. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  9826. cgtime(&rotate_tv);
  9827. switch_pools(NULL);
  9828. }
  9829. cgsleep_ms(30000);
  9830. }
  9831. return NULL;
  9832. }
  9833. void mt_enable(struct thr_info *thr)
  9834. {
  9835. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  9836. notifier_wake(thr->notifier);
  9837. }
  9838. void proc_enable(struct cgpu_info *cgpu)
  9839. {
  9840. int j;
  9841. cgpu->deven = DEV_ENABLED;
  9842. for (j = cgpu->threads ?: 1; j--; )
  9843. mt_enable(cgpu->thr[j]);
  9844. }
  9845. #define device_recovered(cgpu) proc_enable(cgpu)
  9846. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  9847. {
  9848. struct string_elist *setstr_elist;
  9849. const char *p, *p2;
  9850. char replybuf[0x2000];
  9851. size_t L;
  9852. DL_FOREACH(opt_set_device_list, setstr_elist)
  9853. {
  9854. const char * const setstr = setstr_elist->string;
  9855. p = strchr(setstr, ':');
  9856. if (!p)
  9857. p = setstr;
  9858. {
  9859. L = p - setstr;
  9860. char pattern[L + 1];
  9861. if (L)
  9862. memcpy(pattern, setstr, L);
  9863. pattern[L] = '\0';
  9864. if (!cgpu_match(pattern, cgpu))
  9865. continue;
  9866. }
  9867. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  9868. cgpu->proc_repr, __func__, setstr);
  9869. if (p[0] == ':')
  9870. ++p;
  9871. p2 = strchr(p, '=');
  9872. if (!p2)
  9873. {
  9874. L = strlen(p);
  9875. p2 = "";
  9876. }
  9877. else
  9878. {
  9879. L = p2 - p;
  9880. ++p2;
  9881. }
  9882. char opt[L + 1];
  9883. if (L)
  9884. memcpy(opt, p, L);
  9885. opt[L] = '\0';
  9886. L = strlen(p2);
  9887. char setval[L + 1];
  9888. if (L)
  9889. memcpy(setval, p2, L);
  9890. setval[L] = '\0';
  9891. enum bfg_set_device_replytype success;
  9892. p = proc_set_device(cgpu, opt, setval, replybuf, &success);
  9893. switch (success)
  9894. {
  9895. case SDR_OK:
  9896. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s%s%s",
  9897. cgpu->proc_repr, setstr,
  9898. p ? ": " : "", p ?: "");
  9899. break;
  9900. case SDR_ERR:
  9901. case SDR_HELP:
  9902. case SDR_UNKNOWN:
  9903. applog(LOG_DEBUG, "%"PRIpreprv": Applying rule %s: %s",
  9904. cgpu->proc_repr, setstr, p);
  9905. break;
  9906. case SDR_AUTO:
  9907. case SDR_NOSUPP:
  9908. applog(LOG_DEBUG, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  9909. cgpu->proc_repr, setstr);
  9910. }
  9911. }
  9912. cgpu->already_set_defaults = true;
  9913. }
  9914. 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)
  9915. {
  9916. struct device_drv dummy_drv = *drv;
  9917. struct cgpu_info dummy_cgpu = {
  9918. .drv = &dummy_drv,
  9919. .device = &dummy_cgpu,
  9920. .device_id = -1,
  9921. .proc_id = -1,
  9922. .device_data = userp,
  9923. .device_path = devpath,
  9924. .dev_serial = serial,
  9925. };
  9926. strcpy(dummy_cgpu.proc_repr, drv->name);
  9927. switch (mode)
  9928. {
  9929. case 0:
  9930. dummy_drv.set_device = datap;
  9931. break;
  9932. case 1:
  9933. dummy_drv.set_device = NULL;
  9934. dummy_cgpu.set_device_funcs = datap;
  9935. break;
  9936. }
  9937. cgpu_set_defaults(&dummy_cgpu);
  9938. }
  9939. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  9940. * the screen at regular intervals, and restarts threads if they appear to have
  9941. * died. */
  9942. #define WATCHDOG_SICK_TIME 60
  9943. #define WATCHDOG_DEAD_TIME 600
  9944. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  9945. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  9946. static void *watchdog_thread(void __maybe_unused *userdata)
  9947. {
  9948. const unsigned int interval = WATCHDOG_INTERVAL;
  9949. struct timeval zero_tv;
  9950. #ifndef HAVE_PTHREAD_CANCEL
  9951. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9952. #endif
  9953. RenameThread("watchdog");
  9954. memset(&zero_tv, 0, sizeof(struct timeval));
  9955. cgtime(&rotate_tv);
  9956. while (1) {
  9957. int i;
  9958. struct timeval now;
  9959. sleep(interval);
  9960. discard_stale();
  9961. hashmeter(-1, &zero_tv, 0);
  9962. #ifdef HAVE_CURSES
  9963. const int ts = total_staged(true);
  9964. if (curses_active_locked()) {
  9965. change_logwinsize();
  9966. curses_print_status(ts);
  9967. _refresh_devstatus(true);
  9968. touchwin(logwin);
  9969. wrefresh(logwin);
  9970. unlock_curses();
  9971. }
  9972. #endif
  9973. cgtime(&now);
  9974. if (!sched_paused && !should_run()) {
  9975. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  9976. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9977. if (!schedstart.enable) {
  9978. quit(0, "Terminating execution as planned");
  9979. break;
  9980. }
  9981. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  9982. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  9983. sched_paused = true;
  9984. rd_lock(&mining_thr_lock);
  9985. for (i = 0; i < mining_threads; i++)
  9986. mining_thr[i]->pause = true;
  9987. rd_unlock(&mining_thr_lock);
  9988. } else if (sched_paused && should_run()) {
  9989. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  9990. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  9991. if (schedstop.enable)
  9992. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  9993. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9994. sched_paused = false;
  9995. for (i = 0; i < mining_threads; i++) {
  9996. struct thr_info *thr;
  9997. thr = get_thread(i);
  9998. thr->pause = false;
  9999. }
  10000. for (i = 0; i < total_devices; ++i)
  10001. {
  10002. struct cgpu_info *cgpu = get_devices(i);
  10003. /* Don't touch disabled devices */
  10004. if (cgpu->deven == DEV_DISABLED)
  10005. continue;
  10006. proc_enable(cgpu);
  10007. }
  10008. }
  10009. for (i = 0; i < total_devices; ++i) {
  10010. struct cgpu_info *cgpu = get_devices(i);
  10011. if (!cgpu->disable_watchdog)
  10012. bfg_watchdog(cgpu, &now);
  10013. }
  10014. }
  10015. return NULL;
  10016. }
  10017. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  10018. {
  10019. struct thr_info *thr = cgpu->thr[0];
  10020. enum dev_enable *denable;
  10021. char *dev_str = cgpu->proc_repr;
  10022. if (likely(drv_ready(cgpu)))
  10023. {
  10024. if (unlikely(!cgpu->already_set_defaults))
  10025. cgpu_set_defaults(cgpu);
  10026. if (cgpu->drv->get_stats)
  10027. cgpu->drv->get_stats(cgpu);
  10028. }
  10029. denable = &cgpu->deven;
  10030. if (cgpu->drv->watchdog)
  10031. cgpu->drv->watchdog(cgpu, tvp_now);
  10032. /* Thread is disabled */
  10033. if (*denable == DEV_DISABLED)
  10034. return;
  10035. else
  10036. if (*denable == DEV_RECOVER_ERR) {
  10037. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  10038. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  10039. dev_str);
  10040. if (cgpu->reinit_backoff < 300)
  10041. cgpu->reinit_backoff *= 2;
  10042. device_recovered(cgpu);
  10043. }
  10044. return;
  10045. }
  10046. else
  10047. if (*denable == DEV_RECOVER) {
  10048. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  10049. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  10050. dev_str);
  10051. device_recovered(cgpu);
  10052. }
  10053. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  10054. return;
  10055. }
  10056. else
  10057. if (cgpu->temp > cgpu->cutofftemp)
  10058. {
  10059. applog(LOG_WARNING, "%s hit thermal cutoff limit at %dC, disabling!",
  10060. dev_str, (int)cgpu->temp);
  10061. *denable = DEV_RECOVER;
  10062. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  10063. run_cmd(cmd_idle);
  10064. }
  10065. if (thr->getwork) {
  10066. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  10067. int thrid;
  10068. bool cgpu_idle = true;
  10069. thr->rolling = 0;
  10070. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  10071. if (!cgpu->thr[thrid]->getwork)
  10072. cgpu_idle = false;
  10073. if (cgpu_idle) {
  10074. cgpu->rolling = 0;
  10075. cgpu->status = LIFE_WAIT;
  10076. }
  10077. }
  10078. return;
  10079. }
  10080. else if (cgpu->status == LIFE_WAIT)
  10081. cgpu->status = LIFE_WELL;
  10082. #ifdef USE_CPUMINING
  10083. if (!strcmp(cgpu->drv->dname, "cpu"))
  10084. return;
  10085. #endif
  10086. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  10087. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  10088. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  10089. cgpu->status = LIFE_WELL;
  10090. cgpu->device_last_well = time(NULL);
  10091. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  10092. thr->rolling = cgpu->rolling = 0;
  10093. cgpu->status = LIFE_SICK;
  10094. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  10095. cgtime(&thr->sick);
  10096. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  10097. run_cmd(cmd_sick);
  10098. if (opt_restart && cgpu->drv->reinit_device) {
  10099. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  10100. reinit_device(cgpu);
  10101. }
  10102. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  10103. cgpu->status = LIFE_DEAD;
  10104. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  10105. cgtime(&thr->sick);
  10106. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  10107. run_cmd(cmd_dead);
  10108. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  10109. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  10110. /* Attempt to restart a GPU that's sick or dead once every minute */
  10111. cgtime(&thr->sick);
  10112. if (opt_restart)
  10113. reinit_device(cgpu);
  10114. }
  10115. }
  10116. static void log_print_status(struct cgpu_info *cgpu)
  10117. {
  10118. char logline[255];
  10119. get_statline(logline, sizeof(logline), cgpu);
  10120. applog(LOG_WARNING, "%s", logline);
  10121. }
  10122. void print_summary(void)
  10123. {
  10124. struct timeval diff;
  10125. int hours, mins, secs, i;
  10126. double utility, efficiency = 0.0;
  10127. char xfer[(ALLOC_H2B_SPACED*2)+4+1], bw[(ALLOC_H2B_SPACED*2)+6+1];
  10128. int pool_secs;
  10129. timersub(&total_tv_end, &total_tv_start, &diff);
  10130. hours = diff.tv_sec / 3600;
  10131. mins = (diff.tv_sec % 3600) / 60;
  10132. secs = diff.tv_sec % 60;
  10133. utility = total_accepted / total_secs * 60;
  10134. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  10135. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  10136. applog(LOG_WARNING, "Started at %s", datestamp);
  10137. if (total_pools == 1)
  10138. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  10139. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  10140. if (opt_n_threads > 0)
  10141. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  10142. #endif
  10143. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  10144. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  10145. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  10146. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  10147. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  10148. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  10149. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  10150. total_rejected, total_stale,
  10151. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  10152. );
  10153. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  10154. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  10155. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  10156. applog(LOG_WARNING, "Network transfer: %s (%s)",
  10157. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  10158. (float)total_bytes_rcvd,
  10159. (float)total_bytes_sent),
  10160. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  10161. (float)(total_bytes_rcvd / total_secs),
  10162. (float)(total_bytes_sent / total_secs)));
  10163. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  10164. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  10165. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  10166. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  10167. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  10168. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  10169. if (total_pools > 1) {
  10170. for (i = 0; i < total_pools; i++) {
  10171. struct pool *pool = pools[i];
  10172. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  10173. if (pool->solved)
  10174. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  10175. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  10176. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  10177. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  10178. pool->rejected, pool->stale_shares,
  10179. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  10180. );
  10181. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  10182. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  10183. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  10184. applog(LOG_WARNING, " Network transfer: %s (%s)",
  10185. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  10186. (float)pool->cgminer_pool_stats.net_bytes_received,
  10187. (float)pool->cgminer_pool_stats.net_bytes_sent),
  10188. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  10189. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  10190. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  10191. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  10192. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  10193. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  10194. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  10195. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  10196. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  10197. }
  10198. }
  10199. if (opt_quit_summary != BQS_NONE)
  10200. {
  10201. if (opt_quit_summary == BQS_DEFAULT)
  10202. {
  10203. if (total_devices < 25)
  10204. opt_quit_summary = BQS_PROCS;
  10205. else
  10206. opt_quit_summary = BQS_DEVS;
  10207. }
  10208. if (opt_quit_summary == BQS_DETAILED)
  10209. include_serial_in_statline = true;
  10210. applog(LOG_WARNING, "Summary of per device statistics:\n");
  10211. for (i = 0; i < total_devices; ++i) {
  10212. struct cgpu_info *cgpu = get_devices(i);
  10213. if (!cgpu->proc_id)
  10214. {
  10215. // Device summary line
  10216. opt_show_procs = false;
  10217. log_print_status(cgpu);
  10218. opt_show_procs = true;
  10219. }
  10220. if ((opt_quit_summary == BQS_PROCS || opt_quit_summary == BQS_DETAILED) && cgpu->procs > 1)
  10221. log_print_status(cgpu);
  10222. }
  10223. }
  10224. if (opt_shares) {
  10225. applog(LOG_WARNING, "Mined %g accepted shares of %g requested\n", total_diff_accepted, opt_shares);
  10226. if (opt_shares > total_diff_accepted)
  10227. applog(LOG_WARNING, "WARNING - Mined only %g shares of %g requested.", total_diff_accepted, opt_shares);
  10228. }
  10229. applog(LOG_WARNING, " ");
  10230. fflush(stderr);
  10231. fflush(stdout);
  10232. }
  10233. void _bfg_clean_up(bool restarting)
  10234. {
  10235. #ifdef USE_OPENCL
  10236. clear_adl(nDevs);
  10237. #endif
  10238. #ifdef HAVE_LIBUSB
  10239. if (likely(have_libusb))
  10240. libusb_exit(NULL);
  10241. #endif
  10242. cgtime(&total_tv_end);
  10243. #ifdef WIN32
  10244. timeEndPeriod(1);
  10245. #endif
  10246. if (!restarting) {
  10247. /* Attempting to disable curses or print a summary during a
  10248. * restart can lead to a deadlock. */
  10249. #ifdef HAVE_CURSES
  10250. disable_curses();
  10251. #endif
  10252. if (!opt_realquiet && successful_connect)
  10253. print_summary();
  10254. }
  10255. if (opt_n_threads > 0)
  10256. free(cpus);
  10257. curl_global_cleanup();
  10258. #ifdef WIN32
  10259. WSACleanup();
  10260. #endif
  10261. }
  10262. void _quit(int status)
  10263. {
  10264. if (status) {
  10265. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  10266. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  10267. int *p = NULL;
  10268. // NOTE debugger can bypass with: p = &p
  10269. *p = status; // Segfault, hopefully dumping core
  10270. }
  10271. }
  10272. #if defined(unix) || defined(__APPLE__)
  10273. if (forkpid > 0) {
  10274. kill(forkpid, SIGTERM);
  10275. forkpid = 0;
  10276. }
  10277. #endif
  10278. exit(status);
  10279. }
  10280. #ifdef HAVE_CURSES
  10281. char *curses_input(const char *query)
  10282. {
  10283. char *input;
  10284. echo();
  10285. input = malloc(255);
  10286. if (!input)
  10287. quit(1, "Failed to malloc input");
  10288. leaveok(logwin, false);
  10289. wlogprint("%s:\n", query);
  10290. wgetnstr(logwin, input, 255);
  10291. if (!strlen(input))
  10292. {
  10293. free(input);
  10294. input = NULL;
  10295. }
  10296. leaveok(logwin, true);
  10297. noecho();
  10298. return input;
  10299. }
  10300. #endif
  10301. static void *test_pool_thread(void *arg)
  10302. {
  10303. struct pool *pool = (struct pool *)arg;
  10304. if (pool_active(pool, false)) {
  10305. pool_tset(pool, &pool->lagging);
  10306. pool_tclear(pool, &pool->idle);
  10307. bool first_pool = false;
  10308. cg_wlock(&control_lock);
  10309. if (!pools_active) {
  10310. currentpool = pool;
  10311. if (pool->pool_no != 0)
  10312. first_pool = true;
  10313. pools_active = true;
  10314. }
  10315. cg_wunlock(&control_lock);
  10316. if (unlikely(first_pool))
  10317. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  10318. else
  10319. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  10320. switch_pools(NULL);
  10321. } else
  10322. pool_died(pool);
  10323. pool->testing = false;
  10324. return NULL;
  10325. }
  10326. /* Always returns true that the pool details were added unless we are not
  10327. * live, implying this is the only pool being added, so if no pools are
  10328. * active it returns false. */
  10329. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  10330. {
  10331. size_t siz;
  10332. pool_set_uri(pool, url);
  10333. pool->rpc_user = user;
  10334. pool->rpc_pass = pass;
  10335. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  10336. pool->rpc_userpass = malloc(siz);
  10337. if (!pool->rpc_userpass)
  10338. quit(1, "Failed to malloc userpass");
  10339. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  10340. pool->testing = true;
  10341. pool->idle = true;
  10342. enable_pool(pool);
  10343. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  10344. if (!live) {
  10345. pthread_join(pool->test_thread, NULL);
  10346. return pools_active;
  10347. }
  10348. return true;
  10349. }
  10350. #ifdef HAVE_CURSES
  10351. static bool input_pool(bool live)
  10352. {
  10353. char *url = NULL, *user = NULL, *pass = NULL;
  10354. struct pool *pool;
  10355. bool ret = false;
  10356. immedok(logwin, true);
  10357. wlogprint("Input server details.\n");
  10358. url = curses_input("URL");
  10359. if (!url)
  10360. goto out;
  10361. user = curses_input("Username");
  10362. if (!user)
  10363. goto out;
  10364. pass = curses_input("Password");
  10365. if (!pass)
  10366. pass = calloc(1, 1);
  10367. pool = add_pool();
  10368. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  10369. strncmp(url, "https://", 8)) {
  10370. char *httpinput;
  10371. httpinput = malloc(256);
  10372. if (!httpinput)
  10373. quit(1, "Failed to malloc httpinput");
  10374. strcpy(httpinput, "http://");
  10375. strncat(httpinput, url, 248);
  10376. free(url);
  10377. url = httpinput;
  10378. }
  10379. ret = add_pool_details(pool, live, url, user, pass);
  10380. out:
  10381. immedok(logwin, false);
  10382. if (!ret) {
  10383. if (url)
  10384. free(url);
  10385. if (user)
  10386. free(user);
  10387. if (pass)
  10388. free(pass);
  10389. }
  10390. return ret;
  10391. }
  10392. #endif
  10393. #if BLKMAKER_VERSION > 1 && defined(USE_SHA256D)
  10394. static
  10395. bool _add_local_gbt(const char * const filepath, void *userp)
  10396. {
  10397. const bool * const live_p = userp;
  10398. struct pool *pool;
  10399. char buf[0x100];
  10400. char *rpcuser = NULL, *rpcpass = NULL, *rpcconnect = NULL;
  10401. int rpcport = 0, rpcssl = -101;
  10402. FILE * const F = fopen(filepath, "r");
  10403. if (!F)
  10404. applogr(false, LOG_WARNING, "%s: Failed to open %s for reading", "add_local_gbt", filepath);
  10405. while (fgets(buf, sizeof(buf), F))
  10406. {
  10407. if (!strncasecmp(buf, "rpcuser=", 8))
  10408. rpcuser = trimmed_strdup(&buf[8]);
  10409. else
  10410. if (!strncasecmp(buf, "rpcpassword=", 12))
  10411. rpcpass = trimmed_strdup(&buf[12]);
  10412. else
  10413. if (!strncasecmp(buf, "rpcport=", 8))
  10414. rpcport = atoi(&buf[8]);
  10415. else
  10416. if (!strncasecmp(buf, "rpcssl=", 7))
  10417. rpcssl = atoi(&buf[7]);
  10418. else
  10419. if (!strncasecmp(buf, "rpcconnect=", 11))
  10420. rpcconnect = trimmed_strdup(&buf[11]);
  10421. else
  10422. continue;
  10423. if (rpcuser && rpcpass && rpcport && rpcssl != -101 && rpcconnect)
  10424. break;
  10425. }
  10426. fclose(F);
  10427. if (!rpcpass)
  10428. {
  10429. applog(LOG_DEBUG, "%s: Did not find rpcpassword in %s", "add_local_gbt", filepath);
  10430. err:
  10431. free(rpcuser);
  10432. free(rpcpass);
  10433. goto out;
  10434. }
  10435. if (!rpcport)
  10436. rpcport = 8332;
  10437. if (rpcssl == -101)
  10438. rpcssl = 0;
  10439. const bool have_cbaddr = get_mining_goal("default")->generation_script;
  10440. const int uri_sz = 0x30;
  10441. char * const uri = malloc(uri_sz);
  10442. snprintf(uri, uri_sz, "http%s://%s:%d/%s#allblocks", rpcssl ? "s" : "", rpcconnect ?: "localhost", rpcport, have_cbaddr ? "" : "#getcbaddr");
  10443. char hfuri[0x40];
  10444. if (rpcconnect)
  10445. snprintf(hfuri, sizeof(hfuri), "%s:%d", rpcconnect, rpcport);
  10446. else
  10447. snprintf(hfuri, sizeof(hfuri), "port %d", rpcport);
  10448. applog(LOG_DEBUG, "Local bitcoin RPC server on %s found in %s", hfuri, filepath);
  10449. for (int i = 0; i < total_pools; ++i)
  10450. {
  10451. struct pool *pool = pools[i];
  10452. if (!(strcmp(pool->rpc_url, uri) || strcmp(pool->rpc_pass, rpcpass)))
  10453. {
  10454. applog(LOG_DEBUG, "Server on %s is already configured, not adding as failover", hfuri);
  10455. free(uri);
  10456. goto err;
  10457. }
  10458. }
  10459. pool = add_pool();
  10460. if (!pool)
  10461. {
  10462. applog(LOG_ERR, "%s: Error adding pool for bitcoin configured in %s", "add_local_gbt", filepath);
  10463. goto err;
  10464. }
  10465. if (!rpcuser)
  10466. rpcuser = "";
  10467. pool->quota = 0;
  10468. adjust_quota_gcd();
  10469. pool->failover_only = true;
  10470. add_pool_details(pool, *live_p, uri, rpcuser, rpcpass);
  10471. applog(LOG_NOTICE, "Added local bitcoin RPC server on %s as pool %d", hfuri, pool->pool_no);
  10472. out:
  10473. return false;
  10474. }
  10475. static
  10476. void add_local_gbt(bool live)
  10477. {
  10478. appdata_file_call("Bitcoin", "bitcoin.conf", _add_local_gbt, &live);
  10479. }
  10480. #endif
  10481. #if defined(unix) || defined(__APPLE__)
  10482. static void fork_monitor()
  10483. {
  10484. // Make a pipe: [readFD, writeFD]
  10485. int pfd[2];
  10486. int r = pipe(pfd);
  10487. if (r < 0) {
  10488. perror("pipe - failed to create pipe for --monitor");
  10489. exit(1);
  10490. }
  10491. // Make stderr write end of pipe
  10492. fflush(stderr);
  10493. r = dup2(pfd[1], 2);
  10494. if (r < 0) {
  10495. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  10496. exit(1);
  10497. }
  10498. r = close(pfd[1]);
  10499. if (r < 0) {
  10500. perror("close - failed to close write end of pipe for --monitor");
  10501. exit(1);
  10502. }
  10503. // Don't allow a dying monitor to kill the main process
  10504. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  10505. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  10506. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  10507. perror("signal - failed to edit signal mask for --monitor");
  10508. exit(1);
  10509. }
  10510. // Fork a child process
  10511. forkpid = fork();
  10512. if (forkpid < 0) {
  10513. perror("fork - failed to fork child process for --monitor");
  10514. exit(1);
  10515. }
  10516. // Child: launch monitor command
  10517. if (0 == forkpid) {
  10518. // Make stdin read end of pipe
  10519. r = dup2(pfd[0], 0);
  10520. if (r < 0) {
  10521. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  10522. exit(1);
  10523. }
  10524. close(pfd[0]);
  10525. if (r < 0) {
  10526. perror("close - in child, failed to close read end of pipe for --monitor");
  10527. exit(1);
  10528. }
  10529. // Launch user specified command
  10530. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  10531. perror("execl - in child failed to exec user specified command for --monitor");
  10532. exit(1);
  10533. }
  10534. // Parent: clean up unused fds and bail
  10535. r = close(pfd[0]);
  10536. if (r < 0) {
  10537. perror("close - failed to close read end of pipe for --monitor");
  10538. exit(1);
  10539. }
  10540. }
  10541. #endif // defined(unix)
  10542. #ifdef HAVE_CURSES
  10543. #ifdef USE_UNICODE
  10544. static
  10545. wchar_t select_unicode_char(const wchar_t *opt)
  10546. {
  10547. for ( ; *opt; ++opt)
  10548. if (iswprint(*opt))
  10549. return *opt;
  10550. return '?';
  10551. }
  10552. #endif
  10553. void enable_curses(void) {
  10554. int x;
  10555. __maybe_unused int y;
  10556. lock_curses();
  10557. if (curses_active) {
  10558. unlock_curses();
  10559. return;
  10560. }
  10561. #ifdef USE_UNICODE
  10562. if (use_unicode)
  10563. {
  10564. setlocale(LC_CTYPE, "");
  10565. if (iswprint(0xb0))
  10566. have_unicode_degrees = true;
  10567. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  10568. }
  10569. #endif
  10570. mainwin = initscr();
  10571. start_color();
  10572. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  10573. if (ERR != use_default_colors())
  10574. default_bgcolor = -1;
  10575. #endif
  10576. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  10577. {
  10578. menu_attr = COLOR_PAIR(1);
  10579. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  10580. attr_bad |= COLOR_PAIR(2);
  10581. }
  10582. keypad(mainwin, true);
  10583. getmaxyx(mainwin, y, x);
  10584. statuswin = newwin(logstart, x, 0, 0);
  10585. leaveok(statuswin, true);
  10586. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  10587. // We resize the window later anyway, so just start it off at 1 :)
  10588. logwin = newwin(1, 0, logcursor, 0);
  10589. idlok(logwin, true);
  10590. scrollok(logwin, true);
  10591. leaveok(logwin, true);
  10592. cbreak();
  10593. noecho();
  10594. nonl();
  10595. curses_active = true;
  10596. statusy = logstart;
  10597. unlock_curses();
  10598. }
  10599. #endif
  10600. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  10601. #ifndef USE_CPUMINING
  10602. struct device_drv cpu_drv;
  10603. struct device_drv cpu_drv = {
  10604. .name = "CPU",
  10605. };
  10606. #endif
  10607. static int cgminer_id_count = 0;
  10608. static int device_line_id_count;
  10609. void register_device(struct cgpu_info *cgpu)
  10610. {
  10611. cgpu->deven = DEV_ENABLED;
  10612. wr_lock(&devices_lock);
  10613. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  10614. wr_unlock(&devices_lock);
  10615. if (!cgpu->proc_id)
  10616. cgpu->device_line_id = device_line_id_count++;
  10617. int thr_objs = cgpu->threads ?: 1;
  10618. mining_threads += thr_objs;
  10619. base_queue += thr_objs + cgpu->extra_work_queue;
  10620. {
  10621. const struct device_drv * const drv = cgpu->drv;
  10622. struct mining_algorithm *malgo;
  10623. LL_FOREACH(mining_algorithms, malgo)
  10624. {
  10625. if (drv_min_nonce_diff(drv, cgpu, malgo) < 0)
  10626. continue;
  10627. malgo->base_queue += thr_objs + cgpu->extra_work_queue;
  10628. }
  10629. }
  10630. #ifdef HAVE_CURSES
  10631. adj_width(mining_threads, &dev_width);
  10632. #endif
  10633. rwlock_init(&cgpu->qlock);
  10634. cgpu->queued_work = NULL;
  10635. }
  10636. struct _cgpu_devid_counter {
  10637. char name[4];
  10638. int lastid;
  10639. UT_hash_handle hh;
  10640. };
  10641. void renumber_cgpu(struct cgpu_info *cgpu)
  10642. {
  10643. static struct _cgpu_devid_counter *devids = NULL;
  10644. struct _cgpu_devid_counter *d;
  10645. HASH_FIND_STR(devids, cgpu->drv->name, d);
  10646. if (d)
  10647. cgpu->device_id = ++d->lastid;
  10648. else {
  10649. d = malloc(sizeof(*d));
  10650. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  10651. cgpu->device_id = d->lastid = 0;
  10652. HASH_ADD_STR(devids, name, d);
  10653. }
  10654. // Build repr strings
  10655. sprintf(cgpu->dev_repr, "%s%2u", cgpu->drv->name, cgpu->device_id % 100);
  10656. sprintf(cgpu->dev_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id % 100);
  10657. strcpy(cgpu->proc_repr, cgpu->dev_repr);
  10658. sprintf(cgpu->proc_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id);
  10659. const int lpcount = cgpu->procs;
  10660. if (lpcount > 1)
  10661. {
  10662. int ns;
  10663. struct cgpu_info *slave;
  10664. int lpdigits = 1;
  10665. for (int i = lpcount; i > 26 && lpdigits < 3; i /= 26)
  10666. ++lpdigits;
  10667. if (lpdigits > max_lpdigits)
  10668. max_lpdigits = lpdigits;
  10669. memset(&cgpu->proc_repr[5], 'a', lpdigits);
  10670. cgpu->proc_repr[5 + lpdigits] = '\0';
  10671. ns = strlen(cgpu->proc_repr_ns);
  10672. strcpy(&cgpu->proc_repr_ns[ns], &cgpu->proc_repr[5]);
  10673. slave = cgpu;
  10674. for (int i = 1; i < lpcount; ++i)
  10675. {
  10676. slave = slave->next_proc;
  10677. strcpy(slave->proc_repr, cgpu->proc_repr);
  10678. strcpy(slave->proc_repr_ns, cgpu->proc_repr_ns);
  10679. for (int x = i, y = lpdigits; --y, x; x /= 26)
  10680. {
  10681. slave->proc_repr_ns[ns + y] =
  10682. slave->proc_repr[5 + y] += (x % 26);
  10683. }
  10684. }
  10685. }
  10686. }
  10687. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  10688. {
  10689. sha256(buffer, length, digest);
  10690. return true;
  10691. }
  10692. static
  10693. bool drv_algo_check(const struct device_drv * const drv)
  10694. {
  10695. struct mining_goal_info *goal, *tmpgoal;
  10696. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  10697. {
  10698. if (drv_min_nonce_diff(drv, NULL, goal->malgo) >= 0)
  10699. return true;
  10700. }
  10701. return false;
  10702. }
  10703. #ifndef HAVE_PTHREAD_CANCEL
  10704. extern void setup_pthread_cancel_workaround();
  10705. extern struct sigaction pcwm_orig_term_handler;
  10706. #endif
  10707. bool bfg_need_detect_rescan;
  10708. extern void probe_device(struct lowlevel_device_info *);
  10709. static void schedule_rescan(const struct timeval *);
  10710. static
  10711. void drv_detect_all()
  10712. {
  10713. bool rescanning = false;
  10714. rescan:
  10715. bfg_need_detect_rescan = false;
  10716. #ifdef HAVE_BFG_LOWLEVEL
  10717. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  10718. LL_FOREACH_SAFE(infolist, info, infotmp)
  10719. probe_device(info);
  10720. LL_FOREACH_SAFE(infolist, info, infotmp)
  10721. pthread_join(info->probe_pth, NULL);
  10722. #endif
  10723. struct driver_registration *reg, *tmp;
  10724. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  10725. {
  10726. const struct device_drv * const drv = reg->drv;
  10727. if (!(drv_algo_check(drv) && drv->drv_detect))
  10728. continue;
  10729. drv->drv_detect();
  10730. }
  10731. #ifdef HAVE_BFG_LOWLEVEL
  10732. lowlevel_scan_free();
  10733. #endif
  10734. if (bfg_need_detect_rescan)
  10735. {
  10736. if (rescanning)
  10737. {
  10738. applog(LOG_DEBUG, "Device rescan requested a second time, delaying");
  10739. struct timeval tv_when;
  10740. timer_set_delay_from_now(&tv_when, rescan_delay_ms * 1000);
  10741. schedule_rescan(&tv_when);
  10742. }
  10743. else
  10744. {
  10745. rescanning = true;
  10746. applog(LOG_DEBUG, "Device rescan requested");
  10747. goto rescan;
  10748. }
  10749. }
  10750. }
  10751. static
  10752. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  10753. {
  10754. struct thr_info *thr;
  10755. int j;
  10756. struct device_drv *api = cgpu->drv;
  10757. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10758. int threadobj = cgpu->threads;
  10759. if (!threadobj)
  10760. // Create a fake thread object to handle hashmeter etc
  10761. threadobj = 1;
  10762. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  10763. cgpu->thr[threadobj] = NULL;
  10764. cgpu->status = LIFE_INIT;
  10765. if (opt_devices_enabled_list)
  10766. {
  10767. struct string_elist *enablestr_elist;
  10768. cgpu->deven = DEV_DISABLED;
  10769. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  10770. {
  10771. const char * const enablestr = enablestr_elist->string;
  10772. if (cgpu_match(enablestr, cgpu))
  10773. {
  10774. cgpu->deven = DEV_ENABLED;
  10775. break;
  10776. }
  10777. }
  10778. }
  10779. cgpu->max_hashes = 0;
  10780. BFGINIT(cgpu->cutofftemp, opt_cutofftemp);
  10781. BFGINIT(cgpu->targettemp, cgpu->cutofftemp - 6);
  10782. // Setup thread structs before starting any of the threads, in case they try to interact
  10783. for (j = 0; j < threadobj; ++j, ++*kp) {
  10784. thr = get_thread(*kp);
  10785. thr->id = *kp;
  10786. thr->cgpu = cgpu;
  10787. thr->device_thread = j;
  10788. thr->work_restart_notifier[1] = INVSOCK;
  10789. thr->mutex_request[1] = INVSOCK;
  10790. thr->_job_transition_in_progress = true;
  10791. timerclear(&thr->tv_morework);
  10792. thr->scanhash_working = true;
  10793. thr->hashes_done = 0;
  10794. timerclear(&thr->tv_hashes_done);
  10795. cgtime(&thr->tv_lastupdate);
  10796. thr->tv_poll.tv_sec = -1;
  10797. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  10798. cgpu->thr[j] = thr;
  10799. }
  10800. if (!cgpu->device->threads)
  10801. notifier_init_invalid(cgpu->thr[0]->notifier);
  10802. else
  10803. if (!cgpu->threads)
  10804. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  10805. else
  10806. for (j = 0; j < cgpu->threads; ++j)
  10807. {
  10808. thr = cgpu->thr[j];
  10809. notifier_init(thr->notifier);
  10810. }
  10811. }
  10812. static
  10813. void start_cgpu(struct cgpu_info *cgpu)
  10814. {
  10815. struct thr_info *thr;
  10816. int j;
  10817. for (j = 0; j < cgpu->threads; ++j) {
  10818. thr = cgpu->thr[j];
  10819. /* Enable threads for devices set not to mine but disable
  10820. * their queue in case we wish to enable them later */
  10821. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  10822. continue;
  10823. thread_reportout(thr);
  10824. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  10825. quit(1, "thread %d create failed", thr->id);
  10826. notifier_wake(thr->notifier);
  10827. }
  10828. if (cgpu->deven == DEV_ENABLED)
  10829. proc_enable(cgpu);
  10830. }
  10831. static
  10832. void _scan_serial(void *p)
  10833. {
  10834. const char *s = p;
  10835. struct string_elist *iter, *tmp;
  10836. struct string_elist *orig_scan_devices = scan_devices;
  10837. if (s)
  10838. {
  10839. // Make temporary scan_devices list
  10840. scan_devices = NULL;
  10841. string_elist_add("noauto", &scan_devices);
  10842. add_serial(s);
  10843. }
  10844. drv_detect_all();
  10845. if (s)
  10846. {
  10847. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  10848. {
  10849. string_elist_del(&scan_devices, iter);
  10850. }
  10851. scan_devices = orig_scan_devices;
  10852. }
  10853. }
  10854. #ifdef HAVE_BFG_LOWLEVEL
  10855. static
  10856. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  10857. {
  10858. if (!(false
  10859. || (info->serial && !strcasecmp(ser, info->serial))
  10860. || (info->path && !strcasecmp(ser, info->path ))
  10861. || (info->devid && !strcasecmp(ser, info->devid ))
  10862. ))
  10863. {
  10864. char *devid = devpath_to_devid(ser);
  10865. if (!devid)
  10866. return false;
  10867. const bool different = strcmp(info->devid, devid);
  10868. free(devid);
  10869. if (different)
  10870. return false;
  10871. }
  10872. return true;
  10873. }
  10874. static
  10875. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  10876. {
  10877. struct driver_registration *dreg;
  10878. char dname[dnamelen];
  10879. int i;
  10880. for (i = 0; i < dnamelen; ++i)
  10881. dname[i] = tolower(_dname[i]);
  10882. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  10883. if (!dreg)
  10884. {
  10885. for (i = 0; i < dnamelen; ++i)
  10886. dname[i] = toupper(_dname[i]);
  10887. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  10888. if (!dreg)
  10889. return NULL;
  10890. }
  10891. if (!drv_algo_check(dreg->drv))
  10892. return NULL;
  10893. return dreg->drv;
  10894. }
  10895. static
  10896. bool _probe_device_do_probe(const struct device_drv * const drv, const struct lowlevel_device_info * const info, bool * const request_rescan_p)
  10897. {
  10898. bfg_probe_result_flags = 0;
  10899. if (drv->lowl_probe(info))
  10900. {
  10901. if (!(bfg_probe_result_flags & BPR_CONTINUE_PROBES))
  10902. return true;
  10903. }
  10904. else
  10905. if (request_rescan_p && opt_hotplug && !(bfg_probe_result_flags & BPR_DONT_RESCAN))
  10906. *request_rescan_p = true;
  10907. return false;
  10908. }
  10909. bool dummy_check_never_true = false;
  10910. static
  10911. void *probe_device_thread(void *p)
  10912. {
  10913. struct lowlevel_device_info * const infolist = p;
  10914. struct lowlevel_device_info *info = infolist;
  10915. bool request_rescan = false;
  10916. {
  10917. char threadname[5 + strlen(info->devid) + 1];
  10918. sprintf(threadname, "probe_%s", info->devid);
  10919. RenameThread(threadname);
  10920. }
  10921. // If already in use, ignore
  10922. if (bfg_claim_any(NULL, NULL, info->devid))
  10923. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  10924. __func__, info->product);
  10925. // if lowlevel device matches specific user assignment, probe requested driver(s)
  10926. struct string_elist *sd_iter, *sd_tmp;
  10927. struct driver_registration *dreg, *dreg_tmp;
  10928. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10929. {
  10930. const char * const dname = sd_iter->string;
  10931. const char * const colon = strpbrk(dname, ":@");
  10932. if (!(colon && colon != dname))
  10933. continue;
  10934. const char * const ser = &colon[1];
  10935. LL_FOREACH2(infolist, info, same_devid_next)
  10936. {
  10937. if (!_probe_device_match(info, ser))
  10938. continue;
  10939. const size_t dnamelen = (colon - dname);
  10940. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  10941. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  10942. continue;
  10943. if (_probe_device_do_probe(drv, info, &request_rescan))
  10944. return NULL;
  10945. }
  10946. }
  10947. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  10948. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  10949. {
  10950. const struct device_drv * const drv = dreg->drv;
  10951. if (!drv_algo_check(drv))
  10952. continue;
  10953. // Check for "noauto" flag
  10954. // NOTE: driver-specific configuration overrides general
  10955. bool doauto = true;
  10956. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10957. {
  10958. const char * const dname = sd_iter->string;
  10959. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  10960. const char *colon = strchr(dname, ':');
  10961. if (!colon)
  10962. colon = &dname[-1];
  10963. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  10964. continue;
  10965. const ssize_t dnamelen = (colon - dname);
  10966. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  10967. continue;
  10968. doauto = (tolower(colon[1]) == 'a');
  10969. if (dnamelen != -1)
  10970. break;
  10971. }
  10972. if (doauto && drv->lowl_match)
  10973. {
  10974. LL_FOREACH2(infolist, info, same_devid_next)
  10975. {
  10976. /*
  10977. The below call to applog is absolutely necessary
  10978. Starting with commit 76d0cc183b1c9ddcc0ef34d2e43bc696ef9de92e installing BFGMiner on
  10979. Mac OS X using Homebrew results in a binary that segfaults on startup
  10980. There are two unresolved issues:
  10981. 1) The BFGMiner authors cannot find a way to install BFGMiner with Homebrew that results
  10982. in debug symbols being available to help troubleshoot the issue
  10983. 2) The issue disappears when unrelated code changes are made, such as adding the following
  10984. call to applog with infolist and / or p
  10985. We would encourage revisiting this in the future to come up with a more concrete solution
  10986. Reproducing should only require commenting / removing the following line and installing
  10987. BFGMiner using "brew install bfgminer --HEAD"
  10988. */
  10989. if (dummy_check_never_true)
  10990. applog(LOG_DEBUG, "lowl_match: %p(%s) %p %p %p", drv, drv->dname, info, infolist, p);
  10991. if (!drv->lowl_match(info))
  10992. continue;
  10993. if (_probe_device_do_probe(drv, info, &request_rescan))
  10994. return NULL;
  10995. }
  10996. }
  10997. }
  10998. // probe driver(s) with 'all' enabled
  10999. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  11000. {
  11001. const char * const dname = sd_iter->string;
  11002. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  11003. const char * const colon = strchr(dname, ':');
  11004. if (!colon)
  11005. {
  11006. LL_FOREACH2(infolist, info, same_devid_next)
  11007. {
  11008. if (
  11009. #ifdef NEED_BFG_LOWL_VCOM
  11010. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  11011. #endif
  11012. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  11013. {
  11014. bool dont_rescan = false;
  11015. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  11016. {
  11017. const struct device_drv * const drv = dreg->drv;
  11018. if (!drv_algo_check(drv))
  11019. continue;
  11020. if (drv->lowl_probe_by_name_only)
  11021. continue;
  11022. if (!drv->lowl_probe)
  11023. continue;
  11024. if (_probe_device_do_probe(drv, info, NULL))
  11025. return NULL;
  11026. if (bfg_probe_result_flags & BPR_DONT_RESCAN)
  11027. dont_rescan = true;
  11028. }
  11029. if (opt_hotplug && !dont_rescan)
  11030. request_rescan = true;
  11031. break;
  11032. }
  11033. }
  11034. continue;
  11035. }
  11036. if (strcasecmp(&colon[1], "all"))
  11037. continue;
  11038. const size_t dnamelen = (colon - dname);
  11039. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  11040. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  11041. continue;
  11042. LL_FOREACH2(infolist, info, same_devid_next)
  11043. {
  11044. if (info->lowl->exclude_from_all)
  11045. continue;
  11046. if (_probe_device_do_probe(drv, info, NULL))
  11047. return NULL;
  11048. }
  11049. }
  11050. // Only actually request a rescan if we never found any cgpu
  11051. if (request_rescan)
  11052. bfg_need_detect_rescan = true;
  11053. return NULL;
  11054. }
  11055. void probe_device(struct lowlevel_device_info * const info)
  11056. {
  11057. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  11058. }
  11059. #endif
  11060. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  11061. {
  11062. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  11063. int devcount, i, mining_threads_new = 0;
  11064. unsigned int k;
  11065. struct cgpu_info *cgpu;
  11066. struct thr_info *thr;
  11067. void *p;
  11068. mutex_lock(&mutex);
  11069. devcount = total_devices;
  11070. addfunc(arg);
  11071. if (!total_devices_new)
  11072. goto out;
  11073. wr_lock(&devices_lock);
  11074. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  11075. if (unlikely(!p))
  11076. {
  11077. wr_unlock(&devices_lock);
  11078. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  11079. goto out;
  11080. }
  11081. devices = p;
  11082. wr_unlock(&devices_lock);
  11083. for (i = 0; i < total_devices_new; ++i)
  11084. {
  11085. cgpu = devices_new[i];
  11086. mining_threads_new += cgpu->threads ?: 1;
  11087. }
  11088. wr_lock(&mining_thr_lock);
  11089. mining_threads_new += mining_threads;
  11090. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  11091. if (unlikely(!p))
  11092. {
  11093. wr_unlock(&mining_thr_lock);
  11094. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  11095. goto out;
  11096. }
  11097. mining_thr = p;
  11098. wr_unlock(&mining_thr_lock);
  11099. for (i = mining_threads; i < mining_threads_new; ++i) {
  11100. mining_thr[i] = calloc(1, sizeof(*thr));
  11101. if (!mining_thr[i])
  11102. {
  11103. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  11104. for ( ; --i >= mining_threads; )
  11105. free(mining_thr[i]);
  11106. goto out;
  11107. }
  11108. }
  11109. k = mining_threads;
  11110. for (i = 0; i < total_devices_new; ++i)
  11111. {
  11112. cgpu = devices_new[i];
  11113. allocate_cgpu(cgpu, &k);
  11114. }
  11115. for (i = 0; i < total_devices_new; ++i)
  11116. {
  11117. cgpu = devices_new[i];
  11118. start_cgpu(cgpu);
  11119. register_device(cgpu);
  11120. ++total_devices;
  11121. }
  11122. #ifdef HAVE_CURSES
  11123. switch_logsize();
  11124. #endif
  11125. out:
  11126. total_devices_new = 0;
  11127. devcount = total_devices - devcount;
  11128. mutex_unlock(&mutex);
  11129. return devcount;
  11130. }
  11131. int scan_serial(const char *s)
  11132. {
  11133. return create_new_cgpus(_scan_serial, (void*)s);
  11134. }
  11135. static pthread_mutex_t rescan_mutex = PTHREAD_MUTEX_INITIALIZER;
  11136. static bool rescan_active;
  11137. static struct timeval tv_rescan;
  11138. static notifier_t rescan_notifier;
  11139. static
  11140. void *rescan_thread(__maybe_unused void *p)
  11141. {
  11142. pthread_detach(pthread_self());
  11143. RenameThread("rescan");
  11144. struct timeval tv_timeout, tv_now;
  11145. fd_set rfds;
  11146. while (true)
  11147. {
  11148. mutex_lock(&rescan_mutex);
  11149. tv_timeout = tv_rescan;
  11150. if (!timer_isset(&tv_timeout))
  11151. {
  11152. rescan_active = false;
  11153. mutex_unlock(&rescan_mutex);
  11154. break;
  11155. }
  11156. mutex_unlock(&rescan_mutex);
  11157. FD_ZERO(&rfds);
  11158. FD_SET(rescan_notifier[0], &rfds);
  11159. const int maxfd = rescan_notifier[0];
  11160. timer_set_now(&tv_now);
  11161. if (select(maxfd+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now)) > 0)
  11162. notifier_read(rescan_notifier);
  11163. mutex_lock(&rescan_mutex);
  11164. if (timer_passed(&tv_rescan, NULL))
  11165. {
  11166. timer_unset(&tv_rescan);
  11167. mutex_unlock(&rescan_mutex);
  11168. applog(LOG_DEBUG, "Rescan timer expired, triggering");
  11169. scan_serial(NULL);
  11170. }
  11171. else
  11172. mutex_unlock(&rescan_mutex);
  11173. }
  11174. return NULL;
  11175. }
  11176. static
  11177. void _schedule_rescan(const struct timeval * const tvp_when)
  11178. {
  11179. if (rescan_active)
  11180. {
  11181. if (timercmp(tvp_when, &tv_rescan, <))
  11182. applog(LOG_DEBUG, "schedule_rescan: New schedule is before current, waiting it out");
  11183. else
  11184. {
  11185. applog(LOG_DEBUG, "schedule_rescan: New schedule is after current, delaying rescan");
  11186. tv_rescan = *tvp_when;
  11187. }
  11188. return;
  11189. }
  11190. applog(LOG_DEBUG, "schedule_rescan: Scheduling rescan (no rescans currently pending)");
  11191. tv_rescan = *tvp_when;
  11192. rescan_active = true;
  11193. static pthread_t pth;
  11194. if (unlikely(pthread_create(&pth, NULL, rescan_thread, NULL)))
  11195. applog(LOG_ERR, "Failed to start rescan thread");
  11196. }
  11197. static
  11198. void schedule_rescan(const struct timeval * const tvp_when)
  11199. {
  11200. mutex_lock(&rescan_mutex);
  11201. _schedule_rescan(tvp_when);
  11202. mutex_unlock(&rescan_mutex);
  11203. }
  11204. static
  11205. void hotplug_trigger()
  11206. {
  11207. applog(LOG_DEBUG, "%s: Scheduling rescan immediately", __func__);
  11208. struct timeval tv_now;
  11209. timer_set_now(&tv_now);
  11210. schedule_rescan(&tv_now);
  11211. }
  11212. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  11213. static
  11214. void *hotplug_thread(__maybe_unused void *p)
  11215. {
  11216. pthread_detach(pthread_self());
  11217. RenameThread("hotplug");
  11218. struct udev * const udev = udev_new();
  11219. if (unlikely(!udev))
  11220. applogfailr(NULL, LOG_ERR, "udev_new");
  11221. struct udev_monitor * const mon = udev_monitor_new_from_netlink(udev, "udev");
  11222. if (unlikely(!mon))
  11223. applogfailr(NULL, LOG_ERR, "udev_monitor_new_from_netlink");
  11224. if (unlikely(udev_monitor_enable_receiving(mon)))
  11225. applogfailr(NULL, LOG_ERR, "udev_monitor_enable_receiving");
  11226. const int epfd = epoll_create(1);
  11227. if (unlikely(epfd == -1))
  11228. applogfailr(NULL, LOG_ERR, "epoll_create");
  11229. {
  11230. const int fd = udev_monitor_get_fd(mon);
  11231. struct epoll_event ev = {
  11232. .events = EPOLLIN | EPOLLPRI,
  11233. .data.fd = fd,
  11234. };
  11235. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev))
  11236. applogfailr(NULL, LOG_ERR, "epoll_ctl");
  11237. }
  11238. struct epoll_event ev;
  11239. int rv;
  11240. bool pending = false;
  11241. while (true)
  11242. {
  11243. rv = epoll_wait(epfd, &ev, 1, pending ? hotplug_delay_ms : -1);
  11244. if (rv == -1)
  11245. {
  11246. if (errno == EAGAIN || errno == EINTR)
  11247. continue;
  11248. break;
  11249. }
  11250. if (!rv)
  11251. {
  11252. hotplug_trigger();
  11253. pending = false;
  11254. continue;
  11255. }
  11256. struct udev_device * const device = udev_monitor_receive_device(mon);
  11257. if (!device)
  11258. continue;
  11259. const char * const action = udev_device_get_action(device);
  11260. applog(LOG_DEBUG, "%s: Received %s event", __func__, action);
  11261. if (!strcmp(action, "add"))
  11262. pending = true;
  11263. udev_device_unref(device);
  11264. }
  11265. applogfailr(NULL, LOG_ERR, "epoll_wait");
  11266. }
  11267. #elif defined(WIN32)
  11268. static UINT_PTR _hotplug_wintimer_id;
  11269. VOID CALLBACK hotplug_win_timer(HWND hwnd, UINT msg, UINT_PTR idEvent, DWORD dwTime)
  11270. {
  11271. KillTimer(NULL, _hotplug_wintimer_id);
  11272. _hotplug_wintimer_id = 0;
  11273. hotplug_trigger();
  11274. }
  11275. LRESULT CALLBACK hotplug_win_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  11276. {
  11277. if (msg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED)
  11278. {
  11279. applog(LOG_DEBUG, "%s: Received DBT_DEVNODES_CHANGED event", __func__);
  11280. _hotplug_wintimer_id = SetTimer(NULL, _hotplug_wintimer_id, hotplug_delay_ms, hotplug_win_timer);
  11281. }
  11282. return DefWindowProc(hwnd, msg, wParam, lParam);
  11283. }
  11284. static
  11285. void *hotplug_thread(__maybe_unused void *p)
  11286. {
  11287. pthread_detach(pthread_self());
  11288. WNDCLASS DummyWinCls = {
  11289. .lpszClassName = "BFGDummyWinCls",
  11290. .lpfnWndProc = hotplug_win_callback,
  11291. };
  11292. ATOM a = RegisterClass(&DummyWinCls);
  11293. if (unlikely(!a))
  11294. applogfailinfor(NULL, LOG_ERR, "RegisterClass", "%d", (int)GetLastError());
  11295. HWND hwnd = CreateWindow((void*)(intptr_t)a, NULL, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
  11296. if (unlikely(!hwnd))
  11297. applogfailinfor(NULL, LOG_ERR, "CreateWindow", "%d", (int)GetLastError());
  11298. MSG msg;
  11299. while (GetMessage(&msg, NULL, 0, 0))
  11300. {
  11301. TranslateMessage(&msg);
  11302. DispatchMessage(&msg);
  11303. }
  11304. quit(0, "WM_QUIT received");
  11305. return NULL;
  11306. }
  11307. #endif
  11308. #ifdef HAVE_BFG_HOTPLUG
  11309. static
  11310. void hotplug_start()
  11311. {
  11312. pthread_t pth;
  11313. if (unlikely(pthread_create(&pth, NULL, hotplug_thread, NULL)))
  11314. applog(LOG_ERR, "Failed to start hotplug thread");
  11315. }
  11316. #endif
  11317. static void probe_pools(void)
  11318. {
  11319. int i;
  11320. for (i = 0; i < total_pools; i++) {
  11321. struct pool *pool = pools[i];
  11322. pool->testing = true;
  11323. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  11324. }
  11325. }
  11326. static void raise_fd_limits(void)
  11327. {
  11328. #ifdef HAVE_SETRLIMIT
  11329. struct rlimit fdlimit;
  11330. rlim_t old_soft_limit;
  11331. char frombuf[0x10] = "unlimited";
  11332. char hardbuf[0x10] = "unlimited";
  11333. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  11334. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  11335. old_soft_limit = fdlimit.rlim_cur;
  11336. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  11337. fdlimit.rlim_cur = FD_SETSIZE;
  11338. else
  11339. fdlimit.rlim_cur = fdlimit.rlim_max;
  11340. if (fdlimit.rlim_max != RLIM_INFINITY)
  11341. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  11342. if (old_soft_limit != RLIM_INFINITY)
  11343. snprintf(frombuf, sizeof(frombuf), "%lu", (unsigned long)old_soft_limit);
  11344. if (fdlimit.rlim_cur == old_soft_limit)
  11345. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11346. (unsigned long)old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  11347. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  11348. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11349. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11350. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11351. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11352. #else
  11353. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  11354. #endif
  11355. }
  11356. static
  11357. void bfg_atexit(void)
  11358. {
  11359. puts("");
  11360. }
  11361. extern void bfg_init_threadlocal();
  11362. extern void stratumsrv_start();
  11363. extern void test_aan_pll(void);
  11364. int main(int argc, char *argv[])
  11365. {
  11366. struct sigaction handler;
  11367. struct thr_info *thr;
  11368. unsigned int k;
  11369. int i;
  11370. int rearrange_pools = 0;
  11371. char *s;
  11372. #ifdef WIN32
  11373. LoadLibrary("backtrace.dll");
  11374. #endif
  11375. atexit(bfg_atexit);
  11376. b58_sha256_impl = my_blkmaker_sha256_callback;
  11377. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  11378. bfg_init_threadlocal();
  11379. #ifndef HAVE_PTHREAD_CANCEL
  11380. setup_pthread_cancel_workaround();
  11381. #endif
  11382. bfg_init_checksums();
  11383. #ifdef WIN32
  11384. {
  11385. WSADATA wsa;
  11386. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  11387. if (i)
  11388. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  11389. }
  11390. #endif
  11391. /* This dangerous functions tramples random dynamically allocated
  11392. * variables so do it before anything at all */
  11393. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  11394. quit(1, "Failed to curl_global_init");
  11395. initial_args = malloc(sizeof(char *) * (argc + 1));
  11396. for (i = 0; i < argc; i++)
  11397. initial_args[i] = strdup(argv[i]);
  11398. initial_args[argc] = NULL;
  11399. mutex_init(&hash_lock);
  11400. mutex_init(&console_lock);
  11401. cglock_init(&control_lock);
  11402. mutex_init(&stats_lock);
  11403. mutex_init(&sharelog_lock);
  11404. cglock_init(&ch_lock);
  11405. mutex_init(&sshare_lock);
  11406. rwlock_init(&blk_lock);
  11407. rwlock_init(&netacc_lock);
  11408. rwlock_init(&mining_thr_lock);
  11409. rwlock_init(&devices_lock);
  11410. mutex_init(&lp_lock);
  11411. if (unlikely(pthread_cond_init(&lp_cond, bfg_condattr)))
  11412. quit(1, "Failed to pthread_cond_init lp_cond");
  11413. if (unlikely(pthread_cond_init(&gws_cond, bfg_condattr)))
  11414. quit(1, "Failed to pthread_cond_init gws_cond");
  11415. notifier_init(submit_waiting_notifier);
  11416. timer_unset(&tv_rescan);
  11417. notifier_init(rescan_notifier);
  11418. /* Create a unique get work queue */
  11419. getq = tq_new();
  11420. if (!getq)
  11421. quit(1, "Failed to create getq");
  11422. /* We use the getq mutex as the staged lock */
  11423. stgd_lock = &getq->mutex;
  11424. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  11425. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  11426. init_max_name_len();
  11427. #endif
  11428. handler.sa_handler = &sighandler;
  11429. handler.sa_flags = 0;
  11430. sigemptyset(&handler.sa_mask);
  11431. #ifdef HAVE_PTHREAD_CANCEL
  11432. sigaction(SIGTERM, &handler, &termhandler);
  11433. #else
  11434. // Need to let pthread_cancel emulation handle SIGTERM first
  11435. termhandler = pcwm_orig_term_handler;
  11436. pcwm_orig_term_handler = handler;
  11437. #endif
  11438. sigaction(SIGINT, &handler, &inthandler);
  11439. #ifndef WIN32
  11440. signal(SIGPIPE, SIG_IGN);
  11441. #else
  11442. timeBeginPeriod(1);
  11443. #endif
  11444. opt_kernel_path = CGMINER_PREFIX;
  11445. cgminer_path = alloca(PATH_MAX);
  11446. s = strdup(argv[0]);
  11447. strcpy(cgminer_path, dirname(s));
  11448. free(s);
  11449. strcat(cgminer_path, "/");
  11450. #if defined(USE_CPUMINING) && defined(WIN32)
  11451. {
  11452. char buf[32];
  11453. int gev = GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, sizeof(buf));
  11454. if (gev > 0 && gev < sizeof(buf))
  11455. {
  11456. setup_benchmark_pool();
  11457. double rate = bench_algo_stage3(atoi(buf));
  11458. // Write result to shared memory for parent
  11459. char unique_name[64];
  11460. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32))
  11461. {
  11462. HANDLE map_handle = CreateFileMapping(
  11463. INVALID_HANDLE_VALUE, // use paging file
  11464. NULL, // default security attributes
  11465. PAGE_READWRITE, // read/write access
  11466. 0, // size: high 32-bits
  11467. 4096, // size: low 32-bits
  11468. unique_name // name of map object
  11469. );
  11470. if (NULL != map_handle) {
  11471. void *shared_mem = MapViewOfFile(
  11472. map_handle, // object to map view of
  11473. FILE_MAP_WRITE, // read/write access
  11474. 0, // high offset: map from
  11475. 0, // low offset: beginning
  11476. 0 // default: map entire file
  11477. );
  11478. if (NULL != shared_mem)
  11479. CopyMemory(shared_mem, &rate, sizeof(rate));
  11480. (void)UnmapViewOfFile(shared_mem);
  11481. }
  11482. (void)CloseHandle(map_handle);
  11483. }
  11484. exit(0);
  11485. }
  11486. }
  11487. #endif
  11488. #ifdef HAVE_CURSES
  11489. devcursor = 8;
  11490. logstart = devcursor;
  11491. logcursor = logstart;
  11492. #endif
  11493. mutex_init(&submitting_lock);
  11494. // Ensure at least the default goal is created
  11495. get_mining_goal("default");
  11496. #ifdef USE_OPENCL
  11497. opencl_early_init();
  11498. #endif
  11499. schedstart.tm.tm_sec = 1;
  11500. schedstop .tm.tm_sec = 1;
  11501. opt_register_table(opt_early_table, NULL);
  11502. opt_register_table(opt_config_table, NULL);
  11503. opt_register_table(opt_cmdline_table, NULL);
  11504. opt_early_parse(argc, argv, applog_and_exit);
  11505. if (!config_loaded)
  11506. {
  11507. load_default_config();
  11508. rearrange_pools = total_pools;
  11509. }
  11510. opt_free_table();
  11511. /* parse command line */
  11512. opt_register_table(opt_config_table,
  11513. "Options for both config file and command line");
  11514. opt_register_table(opt_cmdline_table,
  11515. "Options for command line only");
  11516. opt_parse(&argc, argv, applog_and_exit);
  11517. if (argc != 1)
  11518. quit(1, "Unexpected extra commandline arguments");
  11519. if (rearrange_pools && rearrange_pools < total_pools)
  11520. {
  11521. // Prioritise commandline pools before default-config pools
  11522. for (i = 0; i < rearrange_pools; ++i)
  11523. pools[i]->prio += rearrange_pools;
  11524. for ( ; i < total_pools; ++i)
  11525. pools[i]->prio -= rearrange_pools;
  11526. }
  11527. #ifndef HAVE_PTHREAD_CANCEL
  11528. // Can't do this any earlier, or config isn't loaded
  11529. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  11530. #endif
  11531. #ifdef HAVE_PWD_H
  11532. struct passwd *user_info = NULL;
  11533. if (opt_setuid != NULL) {
  11534. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  11535. quit(1, "Unable to find setuid user information");
  11536. }
  11537. }
  11538. #endif
  11539. #ifdef HAVE_CHROOT
  11540. if (chroot_dir != NULL) {
  11541. #ifdef HAVE_PWD_H
  11542. if (user_info == NULL && getuid() == 0) {
  11543. applog(LOG_WARNING, "Running as root inside chroot");
  11544. }
  11545. #endif
  11546. if (chroot(chroot_dir) != 0) {
  11547. quit(1, "Unable to chroot");
  11548. }
  11549. if (chdir("/"))
  11550. quit(1, "Unable to chdir to chroot");
  11551. }
  11552. #endif
  11553. #ifdef HAVE_PWD_H
  11554. if (user_info != NULL) {
  11555. if (setgid((*user_info).pw_gid) != 0)
  11556. quit(1, "Unable to setgid");
  11557. if (setuid((*user_info).pw_uid) != 0)
  11558. quit(1, "Unable to setuid");
  11559. }
  11560. #endif
  11561. raise_fd_limits();
  11562. if (opt_benchmark) {
  11563. while (total_pools)
  11564. remove_pool(pools[0]);
  11565. setup_benchmark_pool();
  11566. }
  11567. if (opt_unittest) {
  11568. test_cgpu_match();
  11569. test_intrange();
  11570. test_decimal_width();
  11571. test_domain_funcs();
  11572. #ifdef USE_SCRYPT
  11573. test_scrypt();
  11574. #endif
  11575. test_target();
  11576. test_uri_get_param();
  11577. utf8_test();
  11578. #ifdef USE_JINGTIAN
  11579. test_aan_pll();
  11580. #endif
  11581. if (unittest_failures)
  11582. quit(1, "Unit tests failed");
  11583. }
  11584. #ifdef HAVE_CURSES
  11585. if (opt_realquiet || opt_display_devs)
  11586. use_curses = false;
  11587. setlocale(LC_ALL, "C");
  11588. if (use_curses)
  11589. enable_curses();
  11590. #endif
  11591. #ifdef HAVE_LIBUSB
  11592. int err = libusb_init(NULL);
  11593. if (err)
  11594. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  11595. else
  11596. have_libusb = true;
  11597. #endif
  11598. applog(LOG_WARNING, "Started %s", packagename);
  11599. {
  11600. struct bfg_loaded_configfile *configfile;
  11601. LL_FOREACH(bfg_loaded_configfiles, configfile)
  11602. {
  11603. char * const cnfbuf = configfile->filename;
  11604. int fileconf_load = configfile->fileconf_load;
  11605. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  11606. switch (fileconf_load) {
  11607. case 0:
  11608. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  11609. applog(LOG_WARNING, "Configuration file could not be used.");
  11610. break;
  11611. case -1:
  11612. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  11613. if (use_curses)
  11614. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  11615. break;
  11616. default:
  11617. break;
  11618. }
  11619. }
  11620. }
  11621. i = strlen(opt_kernel_path) + 2;
  11622. char __kernel_path[i];
  11623. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  11624. opt_kernel_path = __kernel_path;
  11625. if (want_per_device_stats)
  11626. opt_log_output = true;
  11627. bfg_devapi_init();
  11628. drv_detect_all();
  11629. total_devices = total_devices_new;
  11630. devices = devices_new;
  11631. total_devices_new = 0;
  11632. devices_new = NULL;
  11633. if (opt_display_devs) {
  11634. int devcount = 0;
  11635. applog(LOG_ERR, "Devices detected:");
  11636. for (i = 0; i < total_devices; ++i) {
  11637. struct cgpu_info *cgpu = devices[i];
  11638. char buf[0x100];
  11639. if (cgpu->device != cgpu)
  11640. continue;
  11641. if (cgpu->name)
  11642. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  11643. else
  11644. if (cgpu->dev_manufacturer)
  11645. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  11646. else
  11647. if (cgpu->dev_product)
  11648. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  11649. else
  11650. strcpy(buf, " Device");
  11651. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  11652. if (cgpu->dev_serial)
  11653. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  11654. if (cgpu->device_path)
  11655. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  11656. tailsprintf(buf, sizeof(buf), ")");
  11657. _applog(LOG_NOTICE, buf);
  11658. ++devcount;
  11659. }
  11660. quit(0, "%d devices listed", devcount);
  11661. }
  11662. mining_threads = 0;
  11663. for (i = 0; i < total_devices; ++i)
  11664. register_device(devices[i]);
  11665. if (!total_devices) {
  11666. applog(LOG_WARNING, "No devices detected!");
  11667. if (use_curses)
  11668. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  11669. else
  11670. applog(LOG_WARNING, "Waiting for devices");
  11671. }
  11672. #ifdef HAVE_CURSES
  11673. switch_logsize();
  11674. #endif
  11675. #if BLKMAKER_VERSION > 1 && defined(USE_SHA256D)
  11676. if (opt_load_bitcoin_conf && !(get_mining_goal("default")->malgo->algo != POW_SHA256D || opt_benchmark))
  11677. add_local_gbt(total_pools);
  11678. #endif
  11679. if (!total_pools) {
  11680. applog(LOG_WARNING, "Need to specify at least one pool server.");
  11681. #ifdef HAVE_CURSES
  11682. if (!use_curses || !input_pool(false))
  11683. #endif
  11684. quit(1, "Pool setup failed");
  11685. }
  11686. for (i = 0; i < total_pools; i++) {
  11687. struct pool *pool = pools[i];
  11688. size_t siz;
  11689. if (!pool->rpc_url)
  11690. quit(1, "No URI supplied for pool %u", i);
  11691. if (!pool->rpc_userpass) {
  11692. if (!pool->rpc_user || !pool->rpc_pass)
  11693. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  11694. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  11695. pool->rpc_userpass = malloc(siz);
  11696. if (!pool->rpc_userpass)
  11697. quit(1, "Failed to malloc userpass");
  11698. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  11699. }
  11700. }
  11701. /* Set the currentpool to pool with priority 0 */
  11702. validate_pool_priorities();
  11703. for (i = 0; i < total_pools; i++) {
  11704. struct pool *pool = pools[i];
  11705. if (!pool->prio)
  11706. currentpool = pool;
  11707. }
  11708. #ifdef HAVE_SYSLOG_H
  11709. if (use_syslog)
  11710. openlog(PACKAGE, LOG_PID, LOG_USER);
  11711. #endif
  11712. #if defined(unix) || defined(__APPLE__)
  11713. if (opt_stderr_cmd)
  11714. fork_monitor();
  11715. #endif // defined(unix)
  11716. mining_thr = calloc(mining_threads, sizeof(thr));
  11717. if (!mining_thr)
  11718. quit(1, "Failed to calloc mining_thr");
  11719. for (i = 0; i < mining_threads; i++) {
  11720. mining_thr[i] = calloc(1, sizeof(*thr));
  11721. if (!mining_thr[i])
  11722. quit(1, "Failed to calloc mining_thr[%d]", i);
  11723. }
  11724. total_control_threads = 6;
  11725. control_thr = calloc(total_control_threads, sizeof(*thr));
  11726. if (!control_thr)
  11727. quit(1, "Failed to calloc control_thr");
  11728. if (opt_benchmark)
  11729. goto begin_bench;
  11730. applog(LOG_NOTICE, "Probing for an alive pool");
  11731. do {
  11732. bool still_testing;
  11733. int i;
  11734. /* Look for at least one active pool before starting */
  11735. probe_pools();
  11736. do {
  11737. sleep(1);
  11738. if (pools_active)
  11739. break;
  11740. still_testing = false;
  11741. for (int i = 0; i < total_pools; ++i)
  11742. if (pools[i]->testing)
  11743. still_testing = true;
  11744. } while (still_testing);
  11745. if (!pools_active) {
  11746. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  11747. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  11748. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  11749. for (i = 0; i < total_pools; i++) {
  11750. struct pool *pool;
  11751. pool = pools[i];
  11752. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  11753. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  11754. }
  11755. #ifdef HAVE_CURSES
  11756. if (use_curses) {
  11757. halfdelay(150);
  11758. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  11759. if (getch() != ERR)
  11760. quit(0, "No servers could be used! Exiting.");
  11761. cbreak();
  11762. } else
  11763. #endif
  11764. quit(0, "No servers could be used! Exiting.");
  11765. }
  11766. } while (!pools_active);
  11767. #ifdef USE_SCRYPT
  11768. if (detect_algo == 1 && get_mining_goal("default")->malgo->algo != POW_SCRYPT) {
  11769. applog(LOG_NOTICE, "Detected scrypt algorithm");
  11770. set_malgo_scrypt();
  11771. }
  11772. #endif
  11773. detect_algo = 0;
  11774. begin_bench:
  11775. total_mhashes_done = 0;
  11776. for (i = 0; i < total_devices; i++) {
  11777. struct cgpu_info *cgpu = devices[i];
  11778. cgpu->rolling = cgpu->total_mhashes = 0;
  11779. }
  11780. cgtime(&total_tv_start);
  11781. cgtime(&total_tv_end);
  11782. miner_started = total_tv_start;
  11783. time_t miner_start_ts = time(NULL);
  11784. if (schedstart.tm.tm_sec)
  11785. localtime_r(&miner_start_ts, &schedstart.tm);
  11786. if (schedstop.tm.tm_sec)
  11787. localtime_r(&miner_start_ts, &schedstop .tm);
  11788. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  11789. // Initialise processors and threads
  11790. k = 0;
  11791. for (i = 0; i < total_devices; ++i) {
  11792. struct cgpu_info *cgpu = devices[i];
  11793. allocate_cgpu(cgpu, &k);
  11794. }
  11795. // Start threads
  11796. for (i = 0; i < total_devices; ++i) {
  11797. struct cgpu_info *cgpu = devices[i];
  11798. start_cgpu(cgpu);
  11799. }
  11800. #ifdef USE_OPENCL
  11801. for (i = 0; i < nDevs; i++)
  11802. pause_dynamic_threads(i);
  11803. #endif
  11804. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  11805. if (opt_n_threads > 0)
  11806. applog(LOG_INFO, "%d cpu miner threads started, using '%s' algorithm.",
  11807. opt_n_threads, algo_names[opt_algo]);
  11808. #endif
  11809. cgtime(&total_tv_start);
  11810. cgtime(&total_tv_end);
  11811. if (!opt_benchmark)
  11812. {
  11813. pthread_t submit_thread;
  11814. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  11815. quit(1, "submit_work thread create failed");
  11816. }
  11817. watchpool_thr_id = 1;
  11818. thr = &control_thr[watchpool_thr_id];
  11819. /* start watchpool thread */
  11820. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  11821. quit(1, "watchpool thread create failed");
  11822. pthread_detach(thr->pth);
  11823. watchdog_thr_id = 2;
  11824. thr = &control_thr[watchdog_thr_id];
  11825. /* start watchdog thread */
  11826. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  11827. quit(1, "watchdog thread create failed");
  11828. pthread_detach(thr->pth);
  11829. #ifdef USE_OPENCL
  11830. /* Create reinit gpu thread */
  11831. gpur_thr_id = 3;
  11832. thr = &control_thr[gpur_thr_id];
  11833. thr->q = tq_new();
  11834. if (!thr->q)
  11835. quit(1, "tq_new failed for gpur_thr_id");
  11836. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  11837. quit(1, "reinit_gpu thread create failed");
  11838. #endif
  11839. /* Create API socket thread */
  11840. api_thr_id = 4;
  11841. thr = &control_thr[api_thr_id];
  11842. if (thr_info_create(thr, NULL, api_thread, thr))
  11843. quit(1, "API thread create failed");
  11844. #ifdef USE_LIBMICROHTTPD
  11845. if (httpsrv_port != -1)
  11846. httpsrv_start(httpsrv_port);
  11847. #endif
  11848. #ifdef USE_LIBEVENT
  11849. if (stratumsrv_port != -1)
  11850. stratumsrv_start();
  11851. #endif
  11852. #ifdef HAVE_BFG_HOTPLUG
  11853. if (opt_hotplug)
  11854. hotplug_start();
  11855. #endif
  11856. #ifdef HAVE_CURSES
  11857. /* Create curses input thread for keyboard input. Create this last so
  11858. * that we know all threads are created since this can call kill_work
  11859. * to try and shut down ll previous threads. */
  11860. input_thr_id = 5;
  11861. thr = &control_thr[input_thr_id];
  11862. if (thr_info_create(thr, NULL, input_thread, thr))
  11863. quit(1, "input thread create failed");
  11864. pthread_detach(thr->pth);
  11865. #endif
  11866. /* Just to be sure */
  11867. if (total_control_threads != 6)
  11868. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  11869. /* Once everything is set up, main() becomes the getwork scheduler */
  11870. while (42) {
  11871. int ts, max_staged = opt_queue;
  11872. struct pool *pool, *cp;
  11873. bool lagging = false;
  11874. struct curl_ent *ce;
  11875. struct work *work;
  11876. struct mining_algorithm *malgo = NULL;
  11877. cp = current_pool();
  11878. // Generally, each processor needs a new work, and all at once during work restarts
  11879. max_staged += base_queue;
  11880. mutex_lock(stgd_lock);
  11881. ts = __total_staged(false);
  11882. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  11883. lagging = true;
  11884. /* Wait until hash_pop tells us we need to create more work */
  11885. if (ts > max_staged) {
  11886. {
  11887. LL_FOREACH(mining_algorithms, malgo)
  11888. {
  11889. if (!malgo->goal_refs)
  11890. continue;
  11891. if (!malgo->base_queue)
  11892. continue;
  11893. if (malgo->staged < malgo->base_queue + opt_queue)
  11894. {
  11895. mutex_unlock(stgd_lock);
  11896. pool = select_pool(lagging, malgo);
  11897. if (pool)
  11898. {
  11899. work = make_work();
  11900. work->spare = true;
  11901. goto retry;
  11902. }
  11903. }
  11904. }
  11905. malgo = NULL;
  11906. }
  11907. staged_full = true;
  11908. pthread_cond_wait(&gws_cond, stgd_lock);
  11909. ts = __total_staged(false);
  11910. }
  11911. mutex_unlock(stgd_lock);
  11912. if (ts > max_staged)
  11913. continue;
  11914. work = make_work();
  11915. if (lagging && !pool_tset(cp, &cp->lagging)) {
  11916. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  11917. cp->getfail_occasions++;
  11918. total_go++;
  11919. }
  11920. pool = select_pool(lagging, malgo);
  11921. retry:
  11922. if (pool->has_stratum) {
  11923. while (!pool->stratum_active || !pool->stratum_notify) {
  11924. struct pool *altpool = select_pool(true, malgo);
  11925. if (altpool == pool && pool->has_stratum)
  11926. cgsleep_ms(5000);
  11927. pool = altpool;
  11928. goto retry;
  11929. }
  11930. gen_stratum_work(pool, work);
  11931. applog(LOG_DEBUG, "Generated stratum work");
  11932. stage_work(work);
  11933. continue;
  11934. }
  11935. if (pool->last_work_copy) {
  11936. mutex_lock(&pool->last_work_lock);
  11937. struct work *last_work = pool->last_work_copy;
  11938. if (!last_work)
  11939. {}
  11940. else
  11941. if (can_roll(last_work) && should_roll(last_work)) {
  11942. struct timeval tv_now;
  11943. cgtime(&tv_now);
  11944. free_work(work);
  11945. work = make_clone(pool->last_work_copy);
  11946. mutex_unlock(&pool->last_work_lock);
  11947. roll_work(work);
  11948. 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));
  11949. stage_work(work);
  11950. continue;
  11951. } else if (last_work->tr && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tr->tmpl) > (unsigned long)mining_threads) {
  11952. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  11953. } else {
  11954. free_work(last_work);
  11955. pool->last_work_copy = NULL;
  11956. }
  11957. mutex_unlock(&pool->last_work_lock);
  11958. }
  11959. if (clone_available()) {
  11960. applog(LOG_DEBUG, "Cloned getwork work");
  11961. free_work(work);
  11962. continue;
  11963. }
  11964. if (opt_benchmark) {
  11965. get_benchmark_work(work, opt_benchmark_intense);
  11966. applog(LOG_DEBUG, "Generated benchmark work");
  11967. stage_work(work);
  11968. continue;
  11969. }
  11970. work->pool = pool;
  11971. ce = pop_curl_entry3(pool, 2);
  11972. /* obtain new work from bitcoin via JSON-RPC */
  11973. if (!get_upstream_work(work, ce->curl)) {
  11974. struct pool *next_pool;
  11975. /* Make sure the pool just hasn't stopped serving
  11976. * requests but is up as we'll keep hammering it */
  11977. push_curl_entry(ce, pool);
  11978. ++pool->seq_getfails;
  11979. pool_died(pool);
  11980. next_pool = select_pool(!opt_fail_only, malgo);
  11981. if (pool == next_pool) {
  11982. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  11983. cgsleep_ms(5000);
  11984. } else {
  11985. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  11986. pool = next_pool;
  11987. }
  11988. goto retry;
  11989. }
  11990. if (ts >= max_staged)
  11991. pool_tclear(pool, &pool->lagging);
  11992. if (pool_tclear(pool, &pool->idle))
  11993. pool_resus(pool);
  11994. applog(LOG_DEBUG, "Generated getwork work");
  11995. stage_work(work);
  11996. push_curl_entry(ce, pool);
  11997. }
  11998. return 0;
  11999. }