miner.c 354 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730
  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 "scrypt.h"
  76. #include "util.h"
  77. #ifdef USE_AVALON
  78. #include "driver-avalon.h"
  79. #endif
  80. #ifdef HAVE_BFG_LOWLEVEL
  81. #include "lowlevel.h"
  82. #endif
  83. #if defined(unix) || defined(__APPLE__)
  84. #include <errno.h>
  85. #include <fcntl.h>
  86. #include <sys/wait.h>
  87. #endif
  88. #ifdef USE_SCRYPT
  89. #include "scrypt.h"
  90. #endif
  91. #include "version.h"
  92. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_NANOFURY) || defined(USE_X6500) || defined(USE_ZTEX)
  93. # define USE_FPGA
  94. #endif
  95. enum bfg_quit_summary {
  96. BQS_DEFAULT,
  97. BQS_NONE,
  98. BQS_DEVS,
  99. BQS_PROCS,
  100. BQS_DETAILED,
  101. };
  102. struct strategies strategies[] = {
  103. { "Failover" },
  104. { "Round Robin" },
  105. { "Rotate" },
  106. { "Load Balance" },
  107. { "Balance" },
  108. };
  109. static char packagename[256];
  110. bool opt_protocol;
  111. bool opt_dev_protocol;
  112. static bool opt_benchmark, opt_benchmark_intense;
  113. static bool want_longpoll = true;
  114. static bool want_gbt = true;
  115. static bool want_getwork = true;
  116. #if BLKMAKER_VERSION > 1
  117. static bool opt_load_bitcoin_conf = true;
  118. static uint32_t coinbase_script_block_id;
  119. static uint32_t template_nonce;
  120. #endif
  121. #if BLKMAKER_VERSION > 0
  122. char *opt_coinbase_sig;
  123. #endif
  124. static enum bfg_quit_summary opt_quit_summary = BQS_DEFAULT;
  125. static bool include_serial_in_statline;
  126. char *request_target_str;
  127. float request_pdiff = 1.0;
  128. double request_bdiff;
  129. static bool want_stratum = true;
  130. int opt_skip_checks;
  131. bool want_per_device_stats;
  132. bool use_syslog;
  133. bool opt_quiet_work_updates = true;
  134. bool opt_quiet;
  135. bool opt_realquiet;
  136. int loginput_size;
  137. bool opt_compact;
  138. bool opt_show_procs;
  139. const int opt_cutofftemp = 95;
  140. int opt_hysteresis = 3;
  141. static int opt_retries = -1;
  142. int opt_fail_pause = 5;
  143. int opt_log_interval = 20;
  144. int opt_queue = 1;
  145. int opt_scantime = 60;
  146. int opt_expiry = 120;
  147. int opt_expiry_lp = 3600;
  148. unsigned long long global_hashrate;
  149. static bool opt_unittest = false;
  150. unsigned unittest_failures;
  151. unsigned long global_quota_gcd = 1;
  152. time_t last_getwork;
  153. #ifdef HAVE_OPENCL
  154. int opt_dynamic_interval = 7;
  155. int nDevs;
  156. int opt_g_threads = -1;
  157. #endif
  158. #ifdef USE_SCRYPT
  159. static char detect_algo = 1;
  160. #else
  161. static char detect_algo;
  162. #endif
  163. bool opt_restart = true;
  164. #ifdef USE_LIBMICROHTTPD
  165. #include "httpsrv.h"
  166. int httpsrv_port = -1;
  167. #endif
  168. #ifdef USE_LIBEVENT
  169. int stratumsrv_port = -1;
  170. #endif
  171. const
  172. int rescan_delay_ms = 1000;
  173. #ifdef HAVE_BFG_HOTPLUG
  174. bool opt_hotplug = 1;
  175. const
  176. int hotplug_delay_ms = 100;
  177. #else
  178. const bool opt_hotplug;
  179. #endif
  180. struct string_elist *scan_devices;
  181. static struct string_elist *opt_set_device_list;
  182. bool opt_force_dev_init;
  183. static struct string_elist *opt_devices_enabled_list;
  184. static bool opt_display_devs;
  185. int total_devices;
  186. struct cgpu_info **devices;
  187. int total_devices_new;
  188. struct cgpu_info **devices_new;
  189. bool have_opencl;
  190. int opt_n_threads = -1;
  191. int mining_threads;
  192. int base_queue;
  193. int num_processors;
  194. #ifdef HAVE_CURSES
  195. bool use_curses = true;
  196. #else
  197. bool use_curses;
  198. #endif
  199. int last_logstatusline_len;
  200. #ifdef HAVE_LIBUSB
  201. bool have_libusb;
  202. #endif
  203. static bool opt_submit_stale = true;
  204. static float opt_shares;
  205. static int opt_submit_threads = 0x40;
  206. bool opt_fail_only;
  207. int opt_fail_switch_delay = 300;
  208. bool opt_autofan;
  209. bool opt_autoengine;
  210. bool opt_noadl;
  211. char *opt_api_allow = NULL;
  212. char *opt_api_groups;
  213. char *opt_api_description = PACKAGE_STRING;
  214. int opt_api_port = 4028;
  215. bool opt_api_listen;
  216. bool opt_api_mcast;
  217. char *opt_api_mcast_addr = API_MCAST_ADDR;
  218. char *opt_api_mcast_code = API_MCAST_CODE;
  219. char *opt_api_mcast_des = "";
  220. int opt_api_mcast_port = 4028;
  221. bool opt_api_network;
  222. bool opt_delaynet;
  223. bool opt_disable_pool;
  224. bool opt_disable_client_reconnect = false;
  225. static bool no_work;
  226. bool opt_worktime;
  227. bool opt_weighed_stats;
  228. char *opt_kernel_path;
  229. char *cgminer_path;
  230. #if defined(USE_BITFORCE)
  231. bool opt_bfl_noncerange;
  232. #endif
  233. #define QUIET (opt_quiet || opt_realquiet)
  234. struct thr_info *control_thr;
  235. struct thr_info **mining_thr;
  236. static int watchpool_thr_id;
  237. static int watchdog_thr_id;
  238. #ifdef HAVE_CURSES
  239. static int input_thr_id;
  240. #endif
  241. int gpur_thr_id;
  242. static int api_thr_id;
  243. static int total_control_threads;
  244. pthread_mutex_t hash_lock;
  245. static pthread_mutex_t *stgd_lock;
  246. pthread_mutex_t console_lock;
  247. cglock_t ch_lock;
  248. static pthread_rwlock_t blk_lock;
  249. static pthread_mutex_t sshare_lock;
  250. pthread_rwlock_t netacc_lock;
  251. pthread_rwlock_t mining_thr_lock;
  252. pthread_rwlock_t devices_lock;
  253. static pthread_mutex_t lp_lock;
  254. static pthread_cond_t lp_cond;
  255. pthread_cond_t gws_cond;
  256. bool shutting_down;
  257. double total_rolling;
  258. double total_mhashes_done;
  259. static struct timeval total_tv_start, total_tv_end;
  260. static struct timeval miner_started;
  261. cglock_t control_lock;
  262. pthread_mutex_t stats_lock;
  263. static pthread_mutex_t submitting_lock;
  264. static int total_submitting;
  265. static struct work *submit_waiting;
  266. notifier_t submit_waiting_notifier;
  267. int hw_errors;
  268. int total_accepted, total_rejected;
  269. int total_getworks, total_stale, total_discarded;
  270. uint64_t total_bytes_rcvd, total_bytes_sent;
  271. double total_diff1, total_bad_diff1;
  272. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  273. static int staged_rollable;
  274. unsigned int new_blocks;
  275. unsigned int found_blocks;
  276. unsigned int local_work;
  277. unsigned int total_go, total_ro;
  278. struct pool **pools;
  279. static struct pool *currentpool = NULL;
  280. int total_pools, enabled_pools;
  281. enum pool_strategy pool_strategy = POOL_FAILOVER;
  282. int opt_rotate_period;
  283. static int total_urls, total_users, total_passes;
  284. static
  285. #ifndef HAVE_CURSES
  286. const
  287. #endif
  288. bool curses_active;
  289. #ifdef HAVE_CURSES
  290. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  291. const
  292. #endif
  293. short default_bgcolor = COLOR_BLACK;
  294. static int attr_title = A_BOLD;
  295. #endif
  296. static
  297. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  298. bool use_unicode;
  299. static
  300. bool have_unicode_degrees;
  301. static
  302. wchar_t unicode_micro = 'u';
  303. #else
  304. const bool use_unicode;
  305. static
  306. const bool have_unicode_degrees;
  307. #ifdef HAVE_CURSES
  308. static
  309. const char unicode_micro = 'u';
  310. #endif
  311. #endif
  312. #ifdef HAVE_CURSES
  313. #define U8_BAD_START "\xef\x80\x81"
  314. #define U8_BAD_END "\xef\x80\x80"
  315. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  316. /* logstart is where the log window should start */
  317. static int devcursor, logstart, logcursor;
  318. bool selecting_device;
  319. unsigned selected_device;
  320. #endif
  321. static int max_lpdigits;
  322. // current_hash was replaced with goal->current_goal_detail
  323. // current_block_id was replaced with blkchain->currentblk->block_id
  324. static char datestamp[40];
  325. static char best_share[ALLOC_H2B_SHORTV] = "0";
  326. double best_diff = 0;
  327. struct mining_algorithm *mining_algorithms;
  328. struct mining_goal_info *mining_goals;
  329. int active_goals = 1;
  330. int swork_id;
  331. /* For creating a hash database of stratum shares submitted that have not had
  332. * a response yet */
  333. struct stratum_share {
  334. UT_hash_handle hh;
  335. bool block;
  336. struct work *work;
  337. int id;
  338. };
  339. static struct stratum_share *stratum_shares = NULL;
  340. char *opt_socks_proxy = NULL;
  341. static const char def_conf[] = "bfgminer.conf";
  342. static bool config_loaded;
  343. static int include_count;
  344. #define JSON_INCLUDE_CONF "include"
  345. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  346. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  347. #define JSON_MAX_DEPTH 10
  348. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  349. char *cmd_idle, *cmd_sick, *cmd_dead;
  350. #if defined(unix) || defined(__APPLE__)
  351. static char *opt_stderr_cmd = NULL;
  352. static int forkpid;
  353. #endif // defined(unix)
  354. #ifdef HAVE_CHROOT
  355. char *chroot_dir;
  356. #endif
  357. #ifdef HAVE_PWD_H
  358. char *opt_setuid;
  359. #endif
  360. struct sigaction termhandler, inthandler;
  361. struct thread_q *getq;
  362. static int total_work;
  363. static bool staged_full;
  364. struct work *staged_work = NULL;
  365. struct schedtime {
  366. bool enable;
  367. struct tm tm;
  368. };
  369. struct schedtime schedstart;
  370. struct schedtime schedstop;
  371. bool sched_paused;
  372. static bool time_before(struct tm *tm1, struct tm *tm2)
  373. {
  374. if (tm1->tm_hour < tm2->tm_hour)
  375. return true;
  376. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  377. return true;
  378. return false;
  379. }
  380. static bool should_run(void)
  381. {
  382. struct tm tm;
  383. time_t tt;
  384. bool within_range;
  385. if (!schedstart.enable && !schedstop.enable)
  386. return true;
  387. tt = time(NULL);
  388. localtime_r(&tt, &tm);
  389. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  390. if (time_before(&schedstop.tm, &schedstart.tm))
  391. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  392. else
  393. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  394. if (within_range && !schedstop.enable)
  395. /* This is a once off event with no stop time set */
  396. schedstart.enable = false;
  397. return within_range;
  398. }
  399. void get_datestamp(char *f, size_t fsiz, time_t tt)
  400. {
  401. struct tm _tm;
  402. struct tm *tm = &_tm;
  403. if (tt == INVALID_TIMESTAMP)
  404. tt = time(NULL);
  405. localtime_r(&tt, tm);
  406. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  407. tm->tm_year + 1900,
  408. tm->tm_mon + 1,
  409. tm->tm_mday,
  410. tm->tm_hour,
  411. tm->tm_min,
  412. tm->tm_sec);
  413. }
  414. static
  415. void get_timestamp(char *f, size_t fsiz, time_t tt)
  416. {
  417. struct tm _tm;
  418. struct tm *tm = &_tm;
  419. localtime_r(&tt, tm);
  420. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  421. tm->tm_hour,
  422. tm->tm_min,
  423. tm->tm_sec);
  424. }
  425. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  426. static char exit_buf[512];
  427. static void applog_and_exit(const char *fmt, ...)
  428. {
  429. va_list ap;
  430. va_start(ap, fmt);
  431. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  432. va_end(ap);
  433. _applog(LOG_ERR, exit_buf);
  434. exit(1);
  435. }
  436. static
  437. float drv_min_nonce_diff(const struct device_drv * const drv, struct cgpu_info * const proc, const struct mining_algorithm * const malgo)
  438. {
  439. if (drv->drv_min_nonce_diff)
  440. return drv->drv_min_nonce_diff(proc, malgo);
  441. return (malgo->algo == POW_SHA256D) ? 1. : -1.;
  442. }
  443. char *devpath_to_devid(const char *devpath)
  444. {
  445. #ifndef WIN32
  446. if (devpath[0] != '/')
  447. return NULL;
  448. struct stat my_stat;
  449. if (stat(devpath, &my_stat))
  450. return NULL;
  451. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  452. memcpy(devs, "dev_t:", 6);
  453. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  454. #else
  455. if (!strncmp(devpath, "\\\\.\\", 4))
  456. devpath += 4;
  457. if (strncasecmp(devpath, "COM", 3) || !devpath[3])
  458. return NULL;
  459. devpath += 3;
  460. char *p;
  461. strtol(devpath, &p, 10);
  462. if (p[0])
  463. return NULL;
  464. const int sz = (p - devpath);
  465. char *devs = malloc(4 + sz + 1);
  466. sprintf(devs, "com:%s", devpath);
  467. #endif
  468. return devs;
  469. }
  470. static
  471. bool devpaths_match(const char * const ap, const char * const bp)
  472. {
  473. char * const a = devpath_to_devid(ap);
  474. if (!a)
  475. return false;
  476. char * const b = devpath_to_devid(bp);
  477. bool rv = false;
  478. if (b)
  479. {
  480. rv = !strcmp(a, b);
  481. free(b);
  482. }
  483. free(a);
  484. return rv;
  485. }
  486. static
  487. int proc_letter_to_number(const char *s, const char ** const rem)
  488. {
  489. int n = 0, c;
  490. for ( ; s[0]; ++s)
  491. {
  492. if (unlikely(n > INT_MAX / 26))
  493. break;
  494. c = tolower(s[0]) - 'a';
  495. if (unlikely(c < 0 || c > 25))
  496. break;
  497. if (unlikely(INT_MAX - c < n))
  498. break;
  499. n = (n * 26) + c;
  500. }
  501. *rem = s;
  502. return n;
  503. }
  504. static
  505. bool cgpu_match(const char * const pattern, const struct cgpu_info * const cgpu)
  506. {
  507. // all - matches anything
  508. // d0 - matches all processors of device 0
  509. // d0-3 - matches all processors of device 0, 1, 2, or 3
  510. // d0a - matches first processor of device 0
  511. // 0 - matches processor 0
  512. // 0-4 - matches processors 0, 1, 2, 3, or 4
  513. // ___ - matches all processors on all devices using driver/name ___
  514. // ___0 - matches all processors of 0th device using driver/name ___
  515. // ___0a - matches first processor of 0th device using driver/name ___
  516. // @* - matches device with serial or path *
  517. // @*@a - matches first processor of device with serial or path *
  518. // ___@* - matches device with serial or path * using driver/name ___
  519. if (!strcasecmp(pattern, "all"))
  520. return true;
  521. const struct device_drv * const drv = cgpu->drv;
  522. const char *p = pattern, *p2;
  523. size_t L;
  524. int n, i, c = -1;
  525. int n2;
  526. int proc_first = -1, proc_last = -1;
  527. struct cgpu_info *device;
  528. if (!(strncasecmp(drv->dname, p, (L = strlen(drv->dname)))
  529. && strncasecmp(drv-> name, p, (L = strlen(drv-> name)))))
  530. // dname or name
  531. p = &pattern[L];
  532. else
  533. if (p[0] == 'd' && (isdigit(p[1]) || p[1] == '-'))
  534. // d#
  535. ++p;
  536. else
  537. if (isdigit(p[0]) || p[0] == '@' || p[0] == '-')
  538. // # or @
  539. {}
  540. else
  541. return false;
  542. L = p - pattern;
  543. while (isspace(p[0]))
  544. ++p;
  545. if (p[0] == '@')
  546. {
  547. // Serial/path
  548. const char * const ser = &p[1];
  549. for (p = ser; p[0] != '@' && p[0] != '\0'; ++p)
  550. {}
  551. p2 = (p[0] == '@') ? &p[1] : p;
  552. const size_t serlen = (p - ser);
  553. p = "";
  554. n = n2 = 0;
  555. const char * const devpath = cgpu->device_path ?: "";
  556. const char * const devser = cgpu->dev_serial ?: "";
  557. if ((!strncmp(devpath, ser, serlen)) && devpath[serlen] == '\0')
  558. {} // Match
  559. else
  560. if ((!strncmp(devser, ser, serlen)) && devser[serlen] == '\0')
  561. {} // Match
  562. else
  563. {
  564. char devpath2[serlen + 1];
  565. memcpy(devpath2, ser, serlen);
  566. devpath2[serlen] = '\0';
  567. if (!devpaths_match(devpath, ser))
  568. return false;
  569. }
  570. }
  571. else
  572. {
  573. if (isdigit(p[0]))
  574. n = strtol(p, (void*)&p2, 0);
  575. else
  576. {
  577. n = 0;
  578. p2 = p;
  579. }
  580. if (p2[0] == '-')
  581. {
  582. ++p2;
  583. if (p2[0] && isdigit(p2[0]))
  584. n2 = strtol(p2, (void*)&p2, 0);
  585. else
  586. n2 = INT_MAX;
  587. }
  588. else
  589. n2 = n;
  590. if (p == pattern)
  591. {
  592. if (!p[0])
  593. return true;
  594. if (p2 && p2[0])
  595. goto invsyntax;
  596. for (i = n; i <= n2; ++i)
  597. {
  598. if (i >= total_devices)
  599. break;
  600. if (cgpu == devices[i])
  601. return true;
  602. }
  603. return false;
  604. }
  605. }
  606. if (p2[0])
  607. {
  608. proc_first = proc_letter_to_number(&p2[0], &p2);
  609. if (p2[0] == '-')
  610. {
  611. ++p2;
  612. if (p2[0])
  613. proc_last = proc_letter_to_number(p2, &p2);
  614. else
  615. proc_last = INT_MAX;
  616. }
  617. else
  618. proc_last = proc_first;
  619. if (p2[0])
  620. goto invsyntax;
  621. }
  622. if (L > 1 || tolower(pattern[0]) != 'd' || !p[0])
  623. {
  624. if ((L == 3 && !strncasecmp(pattern, drv->name, 3)) ||
  625. (!L) ||
  626. (L == strlen(drv->dname) && !strncasecmp(pattern, drv->dname, L)))
  627. {} // Matched name or dname
  628. else
  629. return false;
  630. if (p[0] && (cgpu->device_id < n || cgpu->device_id > n2))
  631. return false;
  632. if (proc_first != -1 && (cgpu->proc_id < proc_first || cgpu->proc_id > proc_last))
  633. return false;
  634. return true;
  635. }
  636. // d#
  637. c = -1;
  638. for (i = 0; ; ++i)
  639. {
  640. if (i == total_devices)
  641. return false;
  642. if (devices[i]->device != devices[i])
  643. continue;
  644. ++c;
  645. if (c < n)
  646. continue;
  647. if (c > n2)
  648. break;
  649. for (device = devices[i]; device; device = device->next_proc)
  650. {
  651. if (proc_first != -1 && (device->proc_id < proc_first || device->proc_id > proc_last))
  652. continue;
  653. if (device == cgpu)
  654. return true;
  655. }
  656. }
  657. return false;
  658. invsyntax:
  659. applog(LOG_WARNING, "%s: Invalid syntax: %s", __func__, pattern);
  660. return false;
  661. }
  662. #define TEST_CGPU_MATCH(pattern) \
  663. if (!cgpu_match(pattern, &cgpu)) \
  664. { \
  665. ++unittest_failures; \
  666. applog(LOG_ERR, "%s: Pattern \"%s\" should have matched!", __func__, pattern); \
  667. } \
  668. // END TEST_CGPU_MATCH
  669. #define TEST_CGPU_NOMATCH(pattern) \
  670. if (cgpu_match(pattern, &cgpu)) \
  671. { \
  672. ++unittest_failures; \
  673. applog(LOG_ERR, "%s: Pattern \"%s\" should NOT have matched!", __func__, pattern); \
  674. } \
  675. // END TEST_CGPU_MATCH
  676. static __maybe_unused
  677. void test_cgpu_match()
  678. {
  679. struct device_drv drv = {
  680. .dname = "test",
  681. .name = "TST",
  682. };
  683. struct cgpu_info cgpu = {
  684. .drv = &drv,
  685. .device = &cgpu,
  686. .device_id = 1,
  687. .proc_id = 1,
  688. .proc_repr = "TST 1b",
  689. }, cgpu0a = {
  690. .drv = &drv,
  691. .device = &cgpu0a,
  692. .device_id = 0,
  693. .proc_id = 0,
  694. .proc_repr = "TST 0a",
  695. }, cgpu1a = {
  696. .drv = &drv,
  697. .device = &cgpu0a,
  698. .device_id = 1,
  699. .proc_id = 0,
  700. .proc_repr = "TST 1a",
  701. };
  702. struct cgpu_info *devices_list[3] = {&cgpu0a, &cgpu1a, &cgpu,};
  703. devices = devices_list;
  704. total_devices = 3;
  705. TEST_CGPU_MATCH("all")
  706. TEST_CGPU_MATCH("d1")
  707. TEST_CGPU_NOMATCH("d2")
  708. TEST_CGPU_MATCH("d0-5")
  709. TEST_CGPU_NOMATCH("d0-0")
  710. TEST_CGPU_NOMATCH("d2-5")
  711. TEST_CGPU_MATCH("d-1")
  712. TEST_CGPU_MATCH("d1-")
  713. TEST_CGPU_NOMATCH("d-0")
  714. TEST_CGPU_NOMATCH("d2-")
  715. TEST_CGPU_MATCH("2")
  716. TEST_CGPU_NOMATCH("3")
  717. TEST_CGPU_MATCH("1-2")
  718. TEST_CGPU_MATCH("2-3")
  719. TEST_CGPU_NOMATCH("1-1")
  720. TEST_CGPU_NOMATCH("3-4")
  721. TEST_CGPU_MATCH("TST")
  722. TEST_CGPU_MATCH("test")
  723. TEST_CGPU_MATCH("tst")
  724. TEST_CGPU_MATCH("TEST")
  725. TEST_CGPU_NOMATCH("TSF")
  726. TEST_CGPU_NOMATCH("TS")
  727. TEST_CGPU_NOMATCH("TSTF")
  728. TEST_CGPU_MATCH("TST1")
  729. TEST_CGPU_MATCH("test1")
  730. TEST_CGPU_MATCH("TST0-1")
  731. TEST_CGPU_MATCH("TST 1")
  732. TEST_CGPU_MATCH("TST 1-2")
  733. TEST_CGPU_MATCH("TEST 1-2")
  734. TEST_CGPU_NOMATCH("TST2")
  735. TEST_CGPU_NOMATCH("TST2-3")
  736. TEST_CGPU_NOMATCH("TST0-0")
  737. TEST_CGPU_MATCH("TST1b")
  738. TEST_CGPU_MATCH("tst1b")
  739. TEST_CGPU_NOMATCH("TST1c")
  740. TEST_CGPU_NOMATCH("TST1bb")
  741. TEST_CGPU_MATCH("TST0-1b")
  742. TEST_CGPU_NOMATCH("TST0-1c")
  743. TEST_CGPU_MATCH("TST1a-d")
  744. TEST_CGPU_NOMATCH("TST1a-a")
  745. TEST_CGPU_NOMATCH("TST1-a")
  746. TEST_CGPU_NOMATCH("TST1c-z")
  747. TEST_CGPU_NOMATCH("TST1c-")
  748. TEST_CGPU_MATCH("@")
  749. TEST_CGPU_NOMATCH("@abc")
  750. TEST_CGPU_MATCH("@@b")
  751. TEST_CGPU_NOMATCH("@@c")
  752. TEST_CGPU_MATCH("TST@")
  753. TEST_CGPU_NOMATCH("TST@abc")
  754. TEST_CGPU_MATCH("TST@@b")
  755. TEST_CGPU_NOMATCH("TST@@c")
  756. TEST_CGPU_MATCH("TST@@b-f")
  757. TEST_CGPU_NOMATCH("TST@@c-f")
  758. TEST_CGPU_NOMATCH("TST@@-a")
  759. cgpu.device_path = "/dev/test";
  760. cgpu.dev_serial = "testy";
  761. TEST_CGPU_MATCH("TST@/dev/test")
  762. TEST_CGPU_MATCH("TST@testy")
  763. TEST_CGPU_NOMATCH("TST@")
  764. TEST_CGPU_NOMATCH("TST@/dev/test5@b")
  765. TEST_CGPU_NOMATCH("TST@testy3@b")
  766. TEST_CGPU_MATCH("TST@/dev/test@b")
  767. TEST_CGPU_MATCH("TST@testy@b")
  768. TEST_CGPU_NOMATCH("TST@/dev/test@c")
  769. TEST_CGPU_NOMATCH("TST@testy@c")
  770. cgpu.device_path = "usb:000:999";
  771. TEST_CGPU_MATCH("TST@usb:000:999")
  772. drv.dname = "test7";
  773. TEST_CGPU_MATCH("test7")
  774. TEST_CGPU_MATCH("TEST7")
  775. TEST_CGPU_NOMATCH("test&")
  776. TEST_CGPU_MATCH("test7 1-2")
  777. TEST_CGPU_MATCH("test7@testy@b")
  778. }
  779. static
  780. int cgpu_search(const char * const pattern, const int first)
  781. {
  782. int i;
  783. struct cgpu_info *cgpu;
  784. #define CHECK_CGPU_SEARCH do{ \
  785. cgpu = get_devices(i); \
  786. if (cgpu_match(pattern, cgpu)) \
  787. return i; \
  788. }while(0)
  789. for (i = first; i < total_devices; ++i)
  790. CHECK_CGPU_SEARCH;
  791. for (i = 0; i < first; ++i)
  792. CHECK_CGPU_SEARCH;
  793. #undef CHECK_CGPU_SEARCH
  794. return -1;
  795. }
  796. static pthread_mutex_t sharelog_lock;
  797. static FILE *sharelog_file = NULL;
  798. struct thr_info *get_thread(int thr_id)
  799. {
  800. struct thr_info *thr;
  801. rd_lock(&mining_thr_lock);
  802. thr = mining_thr[thr_id];
  803. rd_unlock(&mining_thr_lock);
  804. return thr;
  805. }
  806. static struct cgpu_info *get_thr_cgpu(int thr_id)
  807. {
  808. struct thr_info *thr = get_thread(thr_id);
  809. return thr->cgpu;
  810. }
  811. struct cgpu_info *get_devices(int id)
  812. {
  813. struct cgpu_info *cgpu;
  814. rd_lock(&devices_lock);
  815. cgpu = devices[id];
  816. rd_unlock(&devices_lock);
  817. return cgpu;
  818. }
  819. static pthread_mutex_t noncelog_lock = PTHREAD_MUTEX_INITIALIZER;
  820. static FILE *noncelog_file = NULL;
  821. static
  822. void noncelog(const struct work * const work)
  823. {
  824. const int thr_id = work->thr_id;
  825. const struct cgpu_info *proc = get_thr_cgpu(thr_id);
  826. char buf[0x200], hash[65], data[161], midstate[65];
  827. int rv;
  828. size_t ret;
  829. bin2hex(hash, work->hash, 32);
  830. bin2hex(data, work->data, 80);
  831. bin2hex(midstate, work->midstate, 32);
  832. // timestamp,proc,hash,data,midstate
  833. rv = snprintf(buf, sizeof(buf), "%lu,%s,%s,%s,%s\n",
  834. (unsigned long)time(NULL), proc->proc_repr_ns,
  835. hash, data, midstate);
  836. if (unlikely(rv < 1))
  837. {
  838. applog(LOG_ERR, "noncelog printf error");
  839. return;
  840. }
  841. mutex_lock(&noncelog_lock);
  842. ret = fwrite(buf, rv, 1, noncelog_file);
  843. fflush(noncelog_file);
  844. mutex_unlock(&noncelog_lock);
  845. if (ret != 1)
  846. applog(LOG_ERR, "noncelog fwrite error");
  847. }
  848. static void sharelog(const char*disposition, const struct work*work)
  849. {
  850. char target[(sizeof(work->target) * 2) + 1];
  851. char hash[(sizeof(work->hash) * 2) + 1];
  852. char data[(sizeof(work->data) * 2) + 1];
  853. struct cgpu_info *cgpu;
  854. unsigned long int t;
  855. struct pool *pool;
  856. int thr_id, rv;
  857. char s[1024];
  858. size_t ret;
  859. if (!sharelog_file)
  860. return;
  861. thr_id = work->thr_id;
  862. cgpu = get_thr_cgpu(thr_id);
  863. pool = work->pool;
  864. t = work->ts_getwork + timer_elapsed(&work->tv_getwork, &work->tv_work_found);
  865. bin2hex(target, work->target, sizeof(work->target));
  866. bin2hex(hash, work->hash, sizeof(work->hash));
  867. bin2hex(data, work->data, sizeof(work->data));
  868. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  869. 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);
  870. if (rv >= (int)(sizeof(s)))
  871. s[sizeof(s) - 1] = '\0';
  872. else if (rv < 0) {
  873. applog(LOG_ERR, "sharelog printf error");
  874. return;
  875. }
  876. mutex_lock(&sharelog_lock);
  877. ret = fwrite(s, rv, 1, sharelog_file);
  878. fflush(sharelog_file);
  879. mutex_unlock(&sharelog_lock);
  880. if (ret != 1)
  881. applog(LOG_ERR, "sharelog fwrite error");
  882. }
  883. #ifdef HAVE_CURSES
  884. static void switch_logsize(void);
  885. #endif
  886. static void hotplug_trigger();
  887. static
  888. void goal_set_malgo(struct mining_goal_info * const goal, struct mining_algorithm * const malgo)
  889. {
  890. if (goal->malgo == malgo)
  891. return;
  892. if (goal->malgo)
  893. --goal->malgo->goal_refs;
  894. if (malgo->goal_refs++)
  895. // First time using a new mining algorithm may means we need to add mining hardware to support it
  896. // 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)
  897. if (opt_hotplug && api_thr_id)
  898. hotplug_trigger();
  899. goal->malgo = malgo;
  900. }
  901. static struct mining_algorithm malgo_sha256d = {
  902. .algo = POW_SHA256D,
  903. .ui_skip_hash_bytes = 4,
  904. .worktime_skip_prevblk_u32 = 1,
  905. .reasonable_low_nonce_diff = 1.,
  906. .hash_data_f = hash_data,
  907. };
  908. #ifdef USE_SCRYPT
  909. static struct mining_algorithm malgo_scrypt = {
  910. .algo = POW_SCRYPT,
  911. .ui_skip_hash_bytes = 2,
  912. .reasonable_low_nonce_diff = 1./0x10000,
  913. .hash_data_f = scrypt_hash_data,
  914. };
  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. __attribute__((constructor))
  924. void init_mining_goals(struct mining_goal_info * const goal, const struct mining_algorithm * const malgo)
  925. {
  926. LL_APPEND(mining_algorithms, (&malgo_sha256d));
  927. #ifdef USE_SCRYPT
  928. LL_APPEND(mining_algorithms, (&malgo_scrypt));
  929. #endif
  930. }
  931. static
  932. int mining_goals_name_cmp(const struct mining_goal_info * const a, const struct mining_goal_info * const b)
  933. {
  934. // default always goes first
  935. if (a->is_default)
  936. return -1;
  937. if (b->is_default)
  938. return 1;
  939. return strcmp(a->name, b->name);
  940. }
  941. static
  942. void blkchain_init_block(struct blockchain_info * const blkchain)
  943. {
  944. struct block_info * const dummy_block = calloc(sizeof(*dummy_block), 1);
  945. memset(dummy_block->prevblkhash, 0, 0x20);
  946. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(dummy_block->prevblkhash), dummy_block);
  947. blkchain->currentblk = dummy_block;
  948. }
  949. struct mining_goal_info *get_mining_goal(const char * const name)
  950. {
  951. static unsigned next_goal_id;
  952. struct mining_goal_info *goal;
  953. HASH_FIND_STR(mining_goals, name, goal);
  954. if (!goal)
  955. {
  956. struct blockchain_info * const blkchain = malloc(sizeof(*blkchain) + sizeof(*goal));
  957. goal = (void*)(&blkchain[1]);
  958. *blkchain = (struct blockchain_info){
  959. .currentblk = NULL,
  960. };
  961. blkchain_init_block(blkchain);
  962. *goal = (struct mining_goal_info){
  963. .id = next_goal_id++,
  964. .name = strdup(name),
  965. .is_default = !strcmp(name, "default"),
  966. .blkchain = blkchain,
  967. .current_diff = 0xFFFFFFFFFFFFFFFFULL,
  968. };
  969. goal_set_malgo(goal, &malgo_sha256d);
  970. HASH_ADD_STR(mining_goals, name, goal);
  971. HASH_SORT(mining_goals, mining_goals_name_cmp);
  972. #ifdef HAVE_CURSES
  973. devcursor = 7 + active_goals;
  974. switch_logsize();
  975. #endif
  976. }
  977. return goal;
  978. }
  979. void mining_goal_reset(struct mining_goal_info * const goal)
  980. {
  981. struct blockchain_info * const blkchain = goal->blkchain;
  982. struct block_info *blkinfo, *tmpblkinfo;
  983. HASH_ITER(hh, blkchain->blocks, blkinfo, tmpblkinfo)
  984. {
  985. HASH_DEL(blkchain->blocks, blkinfo);
  986. free(blkinfo);
  987. }
  988. blkchain_init_block(blkchain);
  989. }
  990. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  991. /* Adjust all the pools' quota to the greatest common denominator after a pool
  992. * has been added or the quotas changed. */
  993. void adjust_quota_gcd(void)
  994. {
  995. unsigned long gcd, lowest_quota = ~0UL, quota;
  996. struct pool *pool;
  997. int i;
  998. for (i = 0; i < total_pools; i++) {
  999. pool = pools[i];
  1000. quota = pool->quota;
  1001. if (!quota)
  1002. continue;
  1003. if (quota < lowest_quota)
  1004. lowest_quota = quota;
  1005. }
  1006. if (likely(lowest_quota < ~0UL)) {
  1007. gcd = lowest_quota;
  1008. for (i = 0; i < total_pools; i++) {
  1009. pool = pools[i];
  1010. quota = pool->quota;
  1011. if (!quota)
  1012. continue;
  1013. while (quota % gcd)
  1014. gcd--;
  1015. }
  1016. } else
  1017. gcd = 1;
  1018. for (i = 0; i < total_pools; i++) {
  1019. pool = pools[i];
  1020. pool->quota_used *= global_quota_gcd;
  1021. pool->quota_used /= gcd;
  1022. pool->quota_gcd = pool->quota / gcd;
  1023. }
  1024. global_quota_gcd = gcd;
  1025. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  1026. }
  1027. /* Return value is ignored if not called from add_pool_details */
  1028. struct pool *add_pool2(struct mining_goal_info * const goal)
  1029. {
  1030. struct pool *pool;
  1031. pool = calloc(sizeof(struct pool), 1);
  1032. if (!pool)
  1033. quit(1, "Failed to malloc pool in add_pool");
  1034. pool->pool_no = pool->prio = total_pools;
  1035. mutex_init(&pool->last_work_lock);
  1036. mutex_init(&pool->pool_lock);
  1037. mutex_init(&pool->pool_test_lock);
  1038. if (unlikely(pthread_cond_init(&pool->cr_cond, bfg_condattr)))
  1039. quit(1, "Failed to pthread_cond_init in add_pool");
  1040. cglock_init(&pool->data_lock);
  1041. mutex_init(&pool->stratum_lock);
  1042. timer_unset(&pool->swork.tv_transparency);
  1043. pool->swork.pool = pool;
  1044. pool->goal = goal;
  1045. pool->idle = true;
  1046. /* Make sure the pool doesn't think we've been idle since time 0 */
  1047. pool->tv_idle.tv_sec = ~0UL;
  1048. cgtime(&pool->cgminer_stats.start_tv);
  1049. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  1050. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  1051. pool->rpc_proxy = NULL;
  1052. pool->quota = 1;
  1053. pool->sock = INVSOCK;
  1054. pool->lp_socket = CURL_SOCKET_BAD;
  1055. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  1056. pools[total_pools++] = pool;
  1057. if (opt_benchmark)
  1058. {
  1059. // Immediately remove it
  1060. remove_pool(pool);
  1061. return pool;
  1062. }
  1063. adjust_quota_gcd();
  1064. if (!currentpool)
  1065. currentpool = pool;
  1066. enable_pool(pool);
  1067. return pool;
  1068. }
  1069. static
  1070. void pool_set_uri(struct pool * const pool, char * const uri)
  1071. {
  1072. pool->rpc_url = uri;
  1073. }
  1074. /* Pool variant of test and set */
  1075. static bool pool_tset(struct pool *pool, bool *var)
  1076. {
  1077. bool ret;
  1078. mutex_lock(&pool->pool_lock);
  1079. ret = *var;
  1080. *var = true;
  1081. mutex_unlock(&pool->pool_lock);
  1082. return ret;
  1083. }
  1084. bool pool_tclear(struct pool *pool, bool *var)
  1085. {
  1086. bool ret;
  1087. mutex_lock(&pool->pool_lock);
  1088. ret = *var;
  1089. *var = false;
  1090. mutex_unlock(&pool->pool_lock);
  1091. return ret;
  1092. }
  1093. struct pool *current_pool(void)
  1094. {
  1095. struct pool *pool;
  1096. cg_rlock(&control_lock);
  1097. pool = currentpool;
  1098. cg_runlock(&control_lock);
  1099. return pool;
  1100. }
  1101. static
  1102. char *set_bool_ignore_arg(const char * const arg, bool * const b)
  1103. {
  1104. return opt_set_bool(b);
  1105. }
  1106. char *set_int_range(const char *arg, int *i, int min, int max)
  1107. {
  1108. char *err = opt_set_intval(arg, i);
  1109. if (err)
  1110. return err;
  1111. if (*i < min || *i > max)
  1112. return "Value out of range";
  1113. return NULL;
  1114. }
  1115. static char *set_int_0_to_9999(const char *arg, int *i)
  1116. {
  1117. return set_int_range(arg, i, 0, 9999);
  1118. }
  1119. static char *set_int_1_to_65535(const char *arg, int *i)
  1120. {
  1121. return set_int_range(arg, i, 1, 65535);
  1122. }
  1123. static char *set_int_0_to_10(const char *arg, int *i)
  1124. {
  1125. return set_int_range(arg, i, 0, 10);
  1126. }
  1127. static char *set_int_1_to_10(const char *arg, int *i)
  1128. {
  1129. return set_int_range(arg, i, 1, 10);
  1130. }
  1131. char *set_strdup(const char *arg, char **p)
  1132. {
  1133. *p = strdup((char *)arg);
  1134. return NULL;
  1135. }
  1136. #if BLKMAKER_VERSION > 1
  1137. static
  1138. char *set_b58addr(const char * const arg, bytes_t * const b)
  1139. {
  1140. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  1141. if (!scriptsz)
  1142. return "Invalid address";
  1143. char *script = malloc(scriptsz);
  1144. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  1145. free(script);
  1146. return "Failed to convert address to script";
  1147. }
  1148. bytes_assimilate_raw(b, script, scriptsz, scriptsz);
  1149. return NULL;
  1150. }
  1151. static char *set_generate_addr2(struct mining_goal_info *, const char *);
  1152. static
  1153. char *set_generate_addr(char *arg)
  1154. {
  1155. char * const colon = strchr(arg, ':');
  1156. struct mining_goal_info *goal;
  1157. if (colon)
  1158. {
  1159. colon[0] = '\0';
  1160. goal = get_mining_goal(arg);
  1161. arg = &colon[1];
  1162. }
  1163. else
  1164. goal = get_mining_goal("default");
  1165. return set_generate_addr2(goal, arg);
  1166. }
  1167. static
  1168. char *set_generate_addr2(struct mining_goal_info * const goal, const char * const arg)
  1169. {
  1170. bytes_t newscript = BYTES_INIT;
  1171. char *estr = set_b58addr(arg, &newscript);
  1172. if (estr)
  1173. {
  1174. bytes_free(&newscript);
  1175. return estr;
  1176. }
  1177. if (!goal->generation_script)
  1178. {
  1179. goal->generation_script = malloc(sizeof(*goal->generation_script));
  1180. bytes_init(goal->generation_script);
  1181. }
  1182. bytes_assimilate(goal->generation_script, &newscript);
  1183. bytes_free(&newscript);
  1184. return NULL;
  1185. }
  1186. #endif
  1187. static
  1188. char *set_quit_summary(const char * const arg)
  1189. {
  1190. if (!(strcasecmp(arg, "none") && strcasecmp(arg, "no")))
  1191. opt_quit_summary = BQS_NONE;
  1192. else
  1193. if (!(strcasecmp(arg, "devs") && strcasecmp(arg, "devices")))
  1194. opt_quit_summary = BQS_DEVS;
  1195. else
  1196. if (!(strcasecmp(arg, "procs") && strcasecmp(arg, "processors") && strcasecmp(arg, "chips") && strcasecmp(arg, "cores")))
  1197. opt_quit_summary = BQS_PROCS;
  1198. else
  1199. if (!(strcasecmp(arg, "detailed") && strcasecmp(arg, "detail") && strcasecmp(arg, "all")))
  1200. opt_quit_summary = BQS_DETAILED;
  1201. else
  1202. return "Quit summary must be one of none/devs/procs/detailed";
  1203. return NULL;
  1204. }
  1205. static void pdiff_target_leadzero(void *, double);
  1206. char *set_request_diff(const char *arg, float *p)
  1207. {
  1208. unsigned char target[32];
  1209. char *e = opt_set_floatval(arg, p);
  1210. if (e)
  1211. return e;
  1212. request_bdiff = (double)*p * 0.9999847412109375;
  1213. pdiff_target_leadzero(target, *p);
  1214. request_target_str = malloc(65);
  1215. bin2hex(request_target_str, target, 32);
  1216. return NULL;
  1217. }
  1218. #ifdef NEED_BFG_LOWL_VCOM
  1219. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1220. #ifdef WIN32
  1221. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1222. {
  1223. char dev[PATH_MAX];
  1224. char *devp = dev;
  1225. size_t bufLen = 0x100;
  1226. tryagain: ;
  1227. char buf[bufLen];
  1228. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1229. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1230. bufLen *= 2;
  1231. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1232. goto tryagain;
  1233. }
  1234. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1235. }
  1236. size_t tLen;
  1237. memcpy(devp, "\\\\.\\", 4);
  1238. devp = &devp[4];
  1239. for (char *t = buf; *t; t += tLen) {
  1240. tLen = strlen(t) + 1;
  1241. if (strncmp("COM", t, 3))
  1242. continue;
  1243. memcpy(devp, t, tLen);
  1244. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1245. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1246. }
  1247. }
  1248. #else
  1249. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1250. {
  1251. char dev[PATH_MAX];
  1252. char *devp = dev;
  1253. DIR *D;
  1254. struct dirent *de;
  1255. const char devdir[] = "/dev";
  1256. const size_t devdirlen = sizeof(devdir) - 1;
  1257. char *devpath = devp;
  1258. char *devfile = devpath + devdirlen + 1;
  1259. D = opendir(devdir);
  1260. if (!D)
  1261. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1262. memcpy(devpath, devdir, devdirlen);
  1263. devpath[devdirlen] = '/';
  1264. while ( (de = readdir(D)) ) {
  1265. if (!strncmp(de->d_name, "cu.", 3)
  1266. //don't probe Bluetooth devices - causes bus errors and segfaults
  1267. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1268. goto trydev;
  1269. if (strncmp(de->d_name, "tty", 3))
  1270. continue;
  1271. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1272. continue;
  1273. trydev:
  1274. strcpy(devfile, de->d_name);
  1275. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1276. }
  1277. closedir(D);
  1278. }
  1279. #endif
  1280. #endif
  1281. static char *add_serial(const char *arg)
  1282. {
  1283. string_elist_add(arg, &scan_devices);
  1284. return NULL;
  1285. }
  1286. static
  1287. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1288. {
  1289. string_elist_add(arg, elist);
  1290. return NULL;
  1291. }
  1292. bool get_intrange(const char *arg, int *val1, int *val2)
  1293. {
  1294. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1295. char *p, *p2;
  1296. *val1 = strtol(arg, &p, 0);
  1297. if (arg == p)
  1298. // Zero-length ending number, invalid
  1299. return false;
  1300. while (true)
  1301. {
  1302. if (!p[0])
  1303. {
  1304. *val2 = *val1;
  1305. return true;
  1306. }
  1307. if (p[0] == '-')
  1308. break;
  1309. if (!isspace(p[0]))
  1310. // Garbage, invalid
  1311. return false;
  1312. ++p;
  1313. }
  1314. p2 = &p[1];
  1315. *val2 = strtol(p2, &p, 0);
  1316. if (p2 == p)
  1317. // Zero-length ending number, invalid
  1318. return false;
  1319. while (true)
  1320. {
  1321. if (!p[0])
  1322. return true;
  1323. if (!isspace(p[0]))
  1324. // Garbage, invalid
  1325. return false;
  1326. ++p;
  1327. }
  1328. }
  1329. static
  1330. void _test_intrange(const char *s, const int v[2])
  1331. {
  1332. int a[2];
  1333. if (!get_intrange(s, &a[0], &a[1]))
  1334. {
  1335. ++unittest_failures;
  1336. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1337. }
  1338. for (int i = 0; i < 2; ++i)
  1339. if (unlikely(a[i] != v[i]))
  1340. {
  1341. ++unittest_failures;
  1342. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1343. }
  1344. }
  1345. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1346. static
  1347. void _test_intrange_fail(const char *s)
  1348. {
  1349. int a[2];
  1350. if (get_intrange(s, &a[0], &a[1]))
  1351. {
  1352. ++unittest_failures;
  1353. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1354. }
  1355. }
  1356. static
  1357. void test_intrange()
  1358. {
  1359. _test_intrange("-1--2", -1, -2);
  1360. _test_intrange("-1-2", -1, 2);
  1361. _test_intrange("1--2", 1, -2);
  1362. _test_intrange("1-2", 1, 2);
  1363. _test_intrange("111-222", 111, 222);
  1364. _test_intrange(" 11 - 22 ", 11, 22);
  1365. _test_intrange("+11-+22", 11, 22);
  1366. _test_intrange("-1", -1, -1);
  1367. _test_intrange_fail("all");
  1368. _test_intrange_fail("1-");
  1369. _test_intrange_fail("");
  1370. _test_intrange_fail("1-54x");
  1371. }
  1372. static char *set_devices(char *arg)
  1373. {
  1374. if (*arg) {
  1375. if (*arg == '?') {
  1376. opt_display_devs = true;
  1377. return NULL;
  1378. }
  1379. } else
  1380. return "Invalid device parameters";
  1381. string_elist_add(arg, &opt_devices_enabled_list);
  1382. return NULL;
  1383. }
  1384. static char *set_balance(enum pool_strategy *strategy)
  1385. {
  1386. *strategy = POOL_BALANCE;
  1387. return NULL;
  1388. }
  1389. static char *set_loadbalance(enum pool_strategy *strategy)
  1390. {
  1391. *strategy = POOL_LOADBALANCE;
  1392. return NULL;
  1393. }
  1394. static char *set_rotate(const char *arg, int *i)
  1395. {
  1396. pool_strategy = POOL_ROTATE;
  1397. return set_int_range(arg, i, 0, 9999);
  1398. }
  1399. static char *set_rr(enum pool_strategy *strategy)
  1400. {
  1401. *strategy = POOL_ROUNDROBIN;
  1402. return NULL;
  1403. }
  1404. static
  1405. char *set_benchmark_intense()
  1406. {
  1407. opt_benchmark = true;
  1408. opt_benchmark_intense = true;
  1409. return NULL;
  1410. }
  1411. /* Detect that url is for a stratum protocol either via the presence of
  1412. * stratum+tcp or by detecting a stratum server response */
  1413. bool detect_stratum(struct pool *pool, char *url)
  1414. {
  1415. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1416. return false;
  1417. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1418. pool_set_uri(pool, strdup(url));
  1419. pool->has_stratum = true;
  1420. pool->stratum_url = pool->sockaddr_url;
  1421. return true;
  1422. }
  1423. return false;
  1424. }
  1425. static struct pool *add_url(void)
  1426. {
  1427. total_urls++;
  1428. if (total_urls > total_pools)
  1429. add_pool();
  1430. return pools[total_urls - 1];
  1431. }
  1432. static void setup_url(struct pool *pool, char *arg)
  1433. {
  1434. if (detect_stratum(pool, arg))
  1435. return;
  1436. opt_set_charp(arg, &pool->rpc_url);
  1437. if (strncmp(arg, "http://", 7) &&
  1438. strncmp(arg, "https://", 8)) {
  1439. const size_t L = strlen(arg);
  1440. char *httpinput;
  1441. httpinput = malloc(8 + L);
  1442. if (!httpinput)
  1443. quit(1, "Failed to malloc httpinput");
  1444. sprintf(httpinput, "http://%s", arg);
  1445. pool_set_uri(pool, httpinput);
  1446. }
  1447. }
  1448. static char *set_url(char *arg)
  1449. {
  1450. struct pool *pool = add_url();
  1451. setup_url(pool, arg);
  1452. return NULL;
  1453. }
  1454. static char *set_quota(char *arg)
  1455. {
  1456. char *semicolon = strchr(arg, ';'), *url;
  1457. int len, qlen, quota;
  1458. struct pool *pool;
  1459. if (!semicolon)
  1460. return "No semicolon separated quota;URL pair found";
  1461. len = strlen(arg);
  1462. *semicolon = '\0';
  1463. qlen = strlen(arg);
  1464. if (!qlen)
  1465. return "No parameter for quota found";
  1466. len -= qlen + 1;
  1467. if (len < 1)
  1468. return "No parameter for URL found";
  1469. quota = atoi(arg);
  1470. if (quota < 0)
  1471. return "Invalid negative parameter for quota set";
  1472. url = arg + qlen + 1;
  1473. pool = add_url();
  1474. setup_url(pool, url);
  1475. pool->quota = quota;
  1476. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1477. adjust_quota_gcd();
  1478. return NULL;
  1479. }
  1480. static char *set_user(const char *arg)
  1481. {
  1482. struct pool *pool;
  1483. total_users++;
  1484. if (total_users > total_pools)
  1485. add_pool();
  1486. pool = pools[total_users - 1];
  1487. opt_set_charp(arg, &pool->rpc_user);
  1488. return NULL;
  1489. }
  1490. static char *set_pass(const char *arg)
  1491. {
  1492. struct pool *pool;
  1493. total_passes++;
  1494. if (total_passes > total_pools)
  1495. add_pool();
  1496. pool = pools[total_passes - 1];
  1497. opt_set_charp(arg, &pool->rpc_pass);
  1498. return NULL;
  1499. }
  1500. static char *set_userpass(const char *arg)
  1501. {
  1502. struct pool *pool;
  1503. char *updup;
  1504. if (total_users != total_passes)
  1505. return "User + pass options must be balanced before userpass";
  1506. ++total_users;
  1507. ++total_passes;
  1508. if (total_users > total_pools)
  1509. add_pool();
  1510. pool = pools[total_users - 1];
  1511. updup = strdup(arg);
  1512. opt_set_charp(arg, &pool->rpc_userpass);
  1513. pool->rpc_user = updup;
  1514. pool->rpc_pass = strchr(updup, ':');
  1515. if (pool->rpc_pass)
  1516. pool->rpc_pass++[0] = '\0';
  1517. else
  1518. pool->rpc_pass = &updup[strlen(updup)];
  1519. return NULL;
  1520. }
  1521. static char *set_cbcaddr(char *arg)
  1522. {
  1523. struct pool *pool;
  1524. char *p, *addr;
  1525. bytes_t target_script = BYTES_INIT;
  1526. if (!total_pools)
  1527. return "Define pool first, then the --coinbase-check-addr list";
  1528. pool = pools[total_pools - 1];
  1529. /* NOTE: 'x' is a new prefix which leads both mainnet and testnet address, we would
  1530. * need support it later, but now leave the code just so.
  1531. *
  1532. * Regarding details of address prefix 'x', check the below URL:
  1533. * https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Serialization_format
  1534. */
  1535. pool->cb_param.testnet = (arg[0] != '1' && arg[0] != '3' && arg[0] != 'x');
  1536. for (; (addr = strtok_r(arg, ",", &p)); arg = NULL)
  1537. {
  1538. struct bytes_hashtbl *ah;
  1539. if (set_b58addr(addr, &target_script))
  1540. /* No bother to free memory since we are going to exit anyway */
  1541. return "Invalid address in --coinbase-check-address list";
  1542. HASH_FIND(hh, pool->cb_param.scripts, bytes_buf(&target_script), bytes_len(&target_script), ah);
  1543. if (!ah)
  1544. {
  1545. /* Note: for the below allocated memory we have good way to release its memory
  1546. * since we can't be sure there are no reference to the pool struct when remove_pool()
  1547. * get called.
  1548. *
  1549. * We just hope the remove_pool() would not be called many many times during
  1550. * the whole running life of this program.
  1551. */
  1552. ah = malloc(sizeof(*ah));
  1553. bytes_init(&ah->b);
  1554. bytes_assimilate(&ah->b, &target_script);
  1555. HASH_ADD(hh, pool->cb_param.scripts, b.buf, bytes_len(&ah->b), ah);
  1556. }
  1557. }
  1558. bytes_free(&target_script);
  1559. return NULL;
  1560. }
  1561. static char *set_cbctotal(const char *arg)
  1562. {
  1563. struct pool *pool;
  1564. if (!total_pools)
  1565. return "Define pool first, then the --coinbase-check-total argument";
  1566. pool = pools[total_pools - 1];
  1567. pool->cb_param.total = atoll(arg);
  1568. if (pool->cb_param.total < 0)
  1569. return "The total payout amount in coinbase should be greater than 0";
  1570. return NULL;
  1571. }
  1572. static char *set_cbcperc(const char *arg)
  1573. {
  1574. struct pool *pool;
  1575. if (!total_pools)
  1576. return "Define pool first, then the --coinbase-check-percent argument";
  1577. pool = pools[total_pools - 1];
  1578. if (!pool->cb_param.scripts)
  1579. return "Define --coinbase-check-addr list first, then the --coinbase-check-total argument";
  1580. pool->cb_param.perc = atof(arg) / 100;
  1581. if (pool->cb_param.perc < 0.0 || pool->cb_param.perc > 1.0)
  1582. return "The percentage should be between 0 and 100";
  1583. return NULL;
  1584. }
  1585. static
  1586. 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)
  1587. {
  1588. *out_success = SDR_ERR;
  1589. if (!(strcasecmp(optname, "malgo") && strcasecmp(optname, "algo")))
  1590. {
  1591. if (!newvalue)
  1592. return "Goal option 'malgo' requires a value (eg, SHA256d)";
  1593. struct mining_algorithm *new_malgo;
  1594. if (!(strcasecmp(newvalue, "SHA256d") && strcasecmp(newvalue, "SHA256") && strcasecmp(newvalue, "SHA2")))
  1595. new_malgo = &malgo_sha256d;
  1596. #ifdef USE_SCRYPT
  1597. else
  1598. if (!strcasecmp(newvalue, "scrypt"))
  1599. new_malgo = &malgo_scrypt;
  1600. #endif
  1601. else
  1602. return "Unrecognised mining algorithm";
  1603. goal_set_malgo(goal, new_malgo);
  1604. goto success;
  1605. }
  1606. #if BLKMAKER_VERSION > 1
  1607. 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))
  1608. {
  1609. if (!newvalue)
  1610. return "Missing value for 'generate-to' goal option";
  1611. const char * const emsg = set_generate_addr2(goal, newvalue);
  1612. if (emsg)
  1613. return emsg;
  1614. goto success;
  1615. }
  1616. #endif
  1617. *out_success = SDR_UNKNOWN;
  1618. return "Unknown goal option";
  1619. success:
  1620. *out_success = SDR_OK;
  1621. return NULL;
  1622. }
  1623. // May leak replybuf if returning an error
  1624. static
  1625. const char *set_goal_params(struct mining_goal_info * const goal, char *arg)
  1626. {
  1627. bytes_t replybuf = BYTES_INIT;
  1628. for (char *param, *nextptr; (param = strtok_r(arg, ",", &nextptr)); arg = NULL)
  1629. {
  1630. char *val = strchr(param, '=');
  1631. if (val)
  1632. val++[0] = '\0';
  1633. enum bfg_set_device_replytype success;
  1634. const char * const emsg = goal_set(goal, param, val, &replybuf, &success);
  1635. if (success != SDR_OK)
  1636. return emsg ?: "Error setting goal param";
  1637. }
  1638. bytes_free(&replybuf);
  1639. return NULL;
  1640. }
  1641. static
  1642. const char *set_pool_goal(const char * const arg)
  1643. {
  1644. struct pool *pool;
  1645. if (!total_pools)
  1646. return "Usage of --pool-goal before pools are defined does not make sense";
  1647. pool = pools[total_pools - 1];
  1648. char *param = strchr(arg, ':');
  1649. if (param)
  1650. param++[0] = '\0';
  1651. pool->goal = get_mining_goal(arg);
  1652. if (param)
  1653. return set_goal_params(pool->goal, param);
  1654. return NULL;
  1655. }
  1656. static char *set_pool_priority(const char *arg)
  1657. {
  1658. struct pool *pool;
  1659. if (!total_pools)
  1660. return "Usage of --pool-priority before pools are defined does not make sense";
  1661. pool = pools[total_pools - 1];
  1662. opt_set_intval(arg, &pool->prio);
  1663. return NULL;
  1664. }
  1665. static char *set_pool_proxy(const char *arg)
  1666. {
  1667. struct pool *pool;
  1668. if (!total_pools)
  1669. return "Usage of --pool-proxy before pools are defined does not make sense";
  1670. if (!our_curl_supports_proxy_uris())
  1671. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1672. pool = pools[total_pools - 1];
  1673. opt_set_charp(arg, &pool->rpc_proxy);
  1674. return NULL;
  1675. }
  1676. static char *set_pool_force_rollntime(const char *arg)
  1677. {
  1678. struct pool *pool;
  1679. if (!total_pools)
  1680. return "Usage of --force-rollntime before pools are defined does not make sense";
  1681. pool = pools[total_pools - 1];
  1682. opt_set_intval(arg, &pool->force_rollntime);
  1683. return NULL;
  1684. }
  1685. static char *enable_debug(bool *flag)
  1686. {
  1687. *flag = true;
  1688. opt_debug_console = true;
  1689. /* Turn on verbose output, too. */
  1690. opt_log_output = true;
  1691. return NULL;
  1692. }
  1693. static char *set_schedtime(const char *arg, struct schedtime *st)
  1694. {
  1695. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1696. {
  1697. if (strcasecmp(arg, "now"))
  1698. return "Invalid time set, should be HH:MM";
  1699. } else
  1700. schedstop.tm.tm_sec = 0;
  1701. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1702. return "Invalid time set.";
  1703. st->enable = true;
  1704. return NULL;
  1705. }
  1706. static
  1707. char *set_log_file(char *arg)
  1708. {
  1709. char *r = "";
  1710. long int i = strtol(arg, &r, 10);
  1711. int fd, stderr_fd = fileno(stderr);
  1712. if ((!*r) && i >= 0 && i <= INT_MAX)
  1713. fd = i;
  1714. else
  1715. if (!strcmp(arg, "-"))
  1716. {
  1717. fd = fileno(stdout);
  1718. if (unlikely(fd == -1))
  1719. return "Standard output missing for log-file";
  1720. }
  1721. else
  1722. {
  1723. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1724. if (unlikely(fd == -1))
  1725. return "Failed to open log-file";
  1726. }
  1727. close(stderr_fd);
  1728. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1729. return "Failed to dup2 for log-file";
  1730. close(fd);
  1731. return NULL;
  1732. }
  1733. static
  1734. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1735. {
  1736. char *r = "";
  1737. long int i = strtol(arg, &r, 10);
  1738. static char *err = NULL;
  1739. const size_t errbufsz = 0x100;
  1740. free(err);
  1741. err = NULL;
  1742. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1743. *F = fdopen((int)i, mode);
  1744. if (!*F)
  1745. {
  1746. err = malloc(errbufsz);
  1747. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1748. (int)i, purpose);
  1749. return err;
  1750. }
  1751. } else if (!strcmp(arg, "-")) {
  1752. *F = (mode[0] == 'a') ? stdout : stdin;
  1753. if (!*F)
  1754. {
  1755. err = malloc(errbufsz);
  1756. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1757. (mode[0] == 'a') ? "out" : "in", purpose);
  1758. return err;
  1759. }
  1760. } else {
  1761. *F = fopen(arg, mode);
  1762. if (!*F)
  1763. {
  1764. err = malloc(errbufsz);
  1765. snprintf(err, errbufsz, "Failed to open %s for %s",
  1766. arg, purpose);
  1767. return err;
  1768. }
  1769. }
  1770. return NULL;
  1771. }
  1772. static char *set_noncelog(char *arg)
  1773. {
  1774. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1775. }
  1776. static char *set_sharelog(char *arg)
  1777. {
  1778. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1779. }
  1780. static
  1781. void _add_set_device_option(const char * const func, const char * const buf)
  1782. {
  1783. applog(LOG_DEBUG, "%s: Using --set-device %s", func, buf);
  1784. string_elist_add(buf, &opt_set_device_list);
  1785. }
  1786. #define add_set_device_option(...) do{ \
  1787. char _tmp1718[0x100]; \
  1788. snprintf(_tmp1718, sizeof(_tmp1718), __VA_ARGS__); \
  1789. _add_set_device_option(__func__, _tmp1718); \
  1790. }while(0)
  1791. char *set_temp_cutoff(char *arg)
  1792. {
  1793. if (strchr(arg, ','))
  1794. return "temp-cutoff no longer supports comma-delimited syntax, use --set-device for better control";
  1795. applog(LOG_WARNING, "temp-cutoff is deprecated! Use --set-device for better control");
  1796. add_set_device_option("all:temp-cutoff=%s", arg);
  1797. return NULL;
  1798. }
  1799. char *set_temp_target(char *arg)
  1800. {
  1801. if (strchr(arg, ','))
  1802. return "temp-target no longer supports comma-delimited syntax, use --set-device for better control";
  1803. applog(LOG_WARNING, "temp-target is deprecated! Use --set-device for better control");
  1804. add_set_device_option("all:temp-target=%s", arg);
  1805. return NULL;
  1806. }
  1807. #ifdef HAVE_OPENCL
  1808. static
  1809. char *set_no_opencl_binaries(__maybe_unused void * const dummy)
  1810. {
  1811. applog(LOG_WARNING, "The --no-opencl-binaries option is deprecated! Use --set-device OCL:binary=no");
  1812. add_set_device_option("OCL:binary=no");
  1813. return NULL;
  1814. }
  1815. #endif
  1816. static
  1817. char *disable_pool_redirect(__maybe_unused void * const dummy)
  1818. {
  1819. opt_disable_client_reconnect = true;
  1820. want_stratum = false;
  1821. return NULL;
  1822. }
  1823. static char *set_api_allow(const char *arg)
  1824. {
  1825. opt_set_charp(arg, &opt_api_allow);
  1826. return NULL;
  1827. }
  1828. static char *set_api_groups(const char *arg)
  1829. {
  1830. opt_set_charp(arg, &opt_api_groups);
  1831. return NULL;
  1832. }
  1833. static char *set_api_description(const char *arg)
  1834. {
  1835. opt_set_charp(arg, &opt_api_description);
  1836. return NULL;
  1837. }
  1838. static char *set_api_mcast_des(const char *arg)
  1839. {
  1840. opt_set_charp(arg, &opt_api_mcast_des);
  1841. return NULL;
  1842. }
  1843. #ifdef USE_ICARUS
  1844. extern const struct bfg_set_device_definition icarus_set_device_funcs[];
  1845. static char *set_icarus_options(const char *arg)
  1846. {
  1847. if (strchr(arg, ','))
  1848. return "icarus-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1849. applog(LOG_WARNING, "icarus-options is deprecated! See README.FPGA for better control");
  1850. char *opts = strdup(arg), *argdup;
  1851. argdup = opts;
  1852. const struct bfg_set_device_definition *sdf = icarus_set_device_funcs;
  1853. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1854. char *saveptr, *opt;
  1855. for (int i = 0; i < 4; ++i, ++sdf)
  1856. {
  1857. opt = strtok_r(opts, ":", &saveptr);
  1858. opts = NULL;
  1859. if (!opt)
  1860. break;
  1861. if (!opt[0])
  1862. continue;
  1863. for (int j = 0; j < 4; ++j)
  1864. add_set_device_option("%s:%s=%s", drivers[j], sdf->optname, opt);
  1865. }
  1866. free(argdup);
  1867. return NULL;
  1868. }
  1869. static char *set_icarus_timing(const char *arg)
  1870. {
  1871. if (strchr(arg, ','))
  1872. return "icarus-timing no longer supports comma-delimited syntax, see README.FPGA for better control";
  1873. applog(LOG_WARNING, "icarus-timing is deprecated! See README.FPGA for better control");
  1874. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1875. for (int j = 0; j < 4; ++j)
  1876. add_set_device_option("%s:timing=%s", drivers[j], arg);
  1877. return NULL;
  1878. }
  1879. #endif
  1880. #ifdef USE_AVALON
  1881. extern const struct bfg_set_device_definition avalon_set_device_funcs[];
  1882. static char *set_avalon_options(const char *arg)
  1883. {
  1884. if (strchr(arg, ','))
  1885. return "avalon-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1886. applog(LOG_WARNING, "avalon-options is deprecated! See README.FPGA for better control");
  1887. char *opts = strdup(arg), *argdup;
  1888. argdup = opts;
  1889. const struct bfg_set_device_definition *sdf = avalon_set_device_funcs;
  1890. char *saveptr, *opt;
  1891. for (int i = 0; i < 5; ++i, ++sdf)
  1892. {
  1893. opt = strtok_r(opts, ":", &saveptr);
  1894. opts = NULL;
  1895. if (!opt)
  1896. break;
  1897. if (!opt[0])
  1898. continue;
  1899. add_set_device_option("avalon:%s=%s", sdf->optname, opt);
  1900. }
  1901. free(argdup);
  1902. return NULL;
  1903. }
  1904. #endif
  1905. #ifdef USE_KLONDIKE
  1906. static char *set_klondike_options(const char *arg)
  1907. {
  1908. int hashclock;
  1909. double temptarget;
  1910. switch (sscanf(arg, "%d:%lf", &hashclock, &temptarget))
  1911. {
  1912. default:
  1913. return "Unrecognised --klondike-options";
  1914. case 2:
  1915. add_set_device_option("klondike:temp-target=%lf", temptarget);
  1916. // fallthru
  1917. case 1:
  1918. add_set_device_option("klondike:clock=%d", hashclock);
  1919. }
  1920. applog(LOG_WARNING, "klondike-options is deprecated! Use --set-device for better control");
  1921. return NULL;
  1922. }
  1923. #endif
  1924. __maybe_unused
  1925. static char *set_null(const char __maybe_unused *arg)
  1926. {
  1927. return NULL;
  1928. }
  1929. /* These options are available from config file or commandline */
  1930. static struct opt_table opt_config_table[] = {
  1931. #ifdef WANT_CPUMINE
  1932. OPT_WITH_ARG("--algo",
  1933. set_algo, show_algo, &opt_algo,
  1934. "Specify sha256 implementation for CPU mining:\n"
  1935. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1936. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1937. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1938. #ifdef WANT_SSE2_4WAY
  1939. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1940. #endif
  1941. #ifdef WANT_VIA_PADLOCK
  1942. "\n\tvia\t\tVIA padlock implementation"
  1943. #endif
  1944. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1945. #ifdef WANT_CRYPTOPP_ASM32
  1946. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1947. #endif
  1948. #ifdef WANT_X8632_SSE2
  1949. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1950. #endif
  1951. #ifdef WANT_X8664_SSE2
  1952. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1953. #endif
  1954. #ifdef WANT_X8664_SSE4
  1955. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1956. #endif
  1957. #ifdef WANT_ALTIVEC_4WAY
  1958. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1959. #endif
  1960. ),
  1961. OPT_WITH_ARG("-a",
  1962. set_algo, show_algo, &opt_algo,
  1963. opt_hidden),
  1964. #endif
  1965. OPT_WITH_ARG("--api-allow",
  1966. set_api_allow, NULL, NULL,
  1967. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1968. OPT_WITH_ARG("--api-description",
  1969. set_api_description, NULL, NULL,
  1970. "Description placed in the API status header, default: BFGMiner version"),
  1971. OPT_WITH_ARG("--api-groups",
  1972. set_api_groups, NULL, NULL,
  1973. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1974. OPT_WITHOUT_ARG("--api-listen",
  1975. opt_set_bool, &opt_api_listen,
  1976. "Enable API, default: disabled"),
  1977. OPT_WITHOUT_ARG("--api-mcast",
  1978. opt_set_bool, &opt_api_mcast,
  1979. "Enable API Multicast listener, default: disabled"),
  1980. OPT_WITH_ARG("--api-mcast-addr",
  1981. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  1982. "API Multicast listen address"),
  1983. OPT_WITH_ARG("--api-mcast-code",
  1984. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  1985. "Code expected in the API Multicast message, don't use '-'"),
  1986. OPT_WITH_ARG("--api-mcast-des",
  1987. set_api_mcast_des, NULL, NULL,
  1988. "Description appended to the API Multicast reply, default: ''"),
  1989. OPT_WITH_ARG("--api-mcast-port",
  1990. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  1991. "API Multicast listen port"),
  1992. OPT_WITHOUT_ARG("--api-network",
  1993. opt_set_bool, &opt_api_network,
  1994. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1995. OPT_WITH_ARG("--api-port",
  1996. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1997. "Port number of miner API"),
  1998. #ifdef HAVE_ADL
  1999. OPT_WITHOUT_ARG("--auto-fan",
  2000. opt_set_bool, &opt_autofan,
  2001. opt_hidden),
  2002. OPT_WITHOUT_ARG("--auto-gpu",
  2003. opt_set_bool, &opt_autoengine,
  2004. opt_hidden),
  2005. #endif
  2006. OPT_WITHOUT_ARG("--balance",
  2007. set_balance, &pool_strategy,
  2008. "Change multipool strategy from failover to even share balance"),
  2009. OPT_WITHOUT_ARG("--benchmark",
  2010. opt_set_bool, &opt_benchmark,
  2011. "Run BFGMiner in benchmark mode - produces no shares"),
  2012. OPT_WITHOUT_ARG("--benchmark-intense",
  2013. set_benchmark_intense, &opt_benchmark_intense,
  2014. "Run BFGMiner in intensive benchmark mode - produces no shares"),
  2015. #if defined(USE_BITFORCE)
  2016. OPT_WITHOUT_ARG("--bfl-range",
  2017. opt_set_bool, &opt_bfl_noncerange,
  2018. "Use nonce range on bitforce devices if supported"),
  2019. #endif
  2020. #ifdef HAVE_CHROOT
  2021. OPT_WITH_ARG("--chroot-dir",
  2022. opt_set_charp, NULL, &chroot_dir,
  2023. "Chroot to a directory right after startup"),
  2024. #endif
  2025. OPT_WITH_ARG("--cmd-idle",
  2026. opt_set_charp, NULL, &cmd_idle,
  2027. "Execute a command when a device is allowed to be idle (rest or wait)"),
  2028. OPT_WITH_ARG("--cmd-sick",
  2029. opt_set_charp, NULL, &cmd_sick,
  2030. "Execute a command when a device is declared sick"),
  2031. OPT_WITH_ARG("--cmd-dead",
  2032. opt_set_charp, NULL, &cmd_dead,
  2033. "Execute a command when a device is declared dead"),
  2034. #if BLKMAKER_VERSION > 0
  2035. OPT_WITH_ARG("--coinbase-sig",
  2036. set_strdup, NULL, &opt_coinbase_sig,
  2037. "Set coinbase signature when possible"),
  2038. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  2039. set_strdup, NULL, &opt_coinbase_sig,
  2040. opt_hidden),
  2041. #endif
  2042. #ifdef HAVE_CURSES
  2043. OPT_WITHOUT_ARG("--compact",
  2044. opt_set_bool, &opt_compact,
  2045. "Use compact display without per device statistics"),
  2046. #endif
  2047. #ifdef WANT_CPUMINE
  2048. OPT_WITH_ARG("--cpu-threads",
  2049. force_nthreads_int, opt_show_intval, &opt_n_threads,
  2050. "Number of miner CPU threads"),
  2051. OPT_WITH_ARG("-t",
  2052. force_nthreads_int, opt_show_intval, &opt_n_threads,
  2053. opt_hidden),
  2054. #endif
  2055. OPT_WITHOUT_ARG("--debug|-D",
  2056. enable_debug, &opt_debug,
  2057. "Enable debug output"),
  2058. OPT_WITHOUT_ARG("--debuglog",
  2059. opt_set_bool, &opt_debug,
  2060. "Enable debug logging"),
  2061. OPT_WITHOUT_ARG("--device-protocol-dump",
  2062. opt_set_bool, &opt_dev_protocol,
  2063. "Verbose dump of device protocol-level activities"),
  2064. OPT_WITH_ARG("--device|-d",
  2065. set_devices, NULL, NULL,
  2066. "Enable only devices matching pattern (default: all)"),
  2067. OPT_WITHOUT_ARG("--disable-rejecting",
  2068. opt_set_bool, &opt_disable_pool,
  2069. "Automatically disable pools that continually reject shares"),
  2070. #ifdef USE_LIBMICROHTTPD
  2071. OPT_WITH_ARG("--http-port",
  2072. opt_set_intval, opt_show_intval, &httpsrv_port,
  2073. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  2074. #endif
  2075. OPT_WITH_ARG("--expiry",
  2076. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  2077. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  2078. OPT_WITH_ARG("-E",
  2079. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  2080. opt_hidden),
  2081. OPT_WITH_ARG("--expiry-lp",
  2082. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  2083. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  2084. OPT_WITHOUT_ARG("--failover-only",
  2085. opt_set_bool, &opt_fail_only,
  2086. "Don't leak work to backup pools when primary pool is lagging"),
  2087. OPT_WITH_ARG("--failover-switch-delay",
  2088. set_int_1_to_65535, opt_show_intval, &opt_fail_switch_delay,
  2089. "Delay in seconds before switching back to a failed pool"),
  2090. #ifdef USE_FPGA
  2091. OPT_WITHOUT_ARG("--force-dev-init",
  2092. opt_set_bool, &opt_force_dev_init,
  2093. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  2094. #endif
  2095. #if BLKMAKER_VERSION > 1
  2096. OPT_WITH_ARG("--generate-to",
  2097. set_generate_addr, NULL, NULL,
  2098. "Set an address to generate to for solo mining"),
  2099. 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",
  2100. set_generate_addr, NULL, NULL,
  2101. opt_hidden),
  2102. #endif
  2103. #ifdef HAVE_OPENCL
  2104. OPT_WITH_ARG("--gpu-dyninterval",
  2105. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  2106. opt_hidden),
  2107. OPT_WITH_ARG("--gpu-platform",
  2108. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  2109. "Select OpenCL platform ID to use for GPU mining"),
  2110. OPT_WITH_ARG("--gpu-threads|-g",
  2111. set_gpu_threads, opt_show_intval, &opt_g_threads,
  2112. opt_hidden),
  2113. #ifdef HAVE_ADL
  2114. OPT_WITH_ARG("--gpu-engine",
  2115. set_gpu_engine, NULL, NULL,
  2116. opt_hidden),
  2117. OPT_WITH_ARG("--gpu-fan",
  2118. set_gpu_fan, NULL, NULL,
  2119. opt_hidden),
  2120. OPT_WITH_ARG("--gpu-map",
  2121. set_gpu_map, NULL, NULL,
  2122. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  2123. OPT_WITH_ARG("--gpu-memclock",
  2124. set_gpu_memclock, NULL, NULL,
  2125. opt_hidden),
  2126. OPT_WITH_ARG("--gpu-memdiff",
  2127. set_gpu_memdiff, NULL, NULL,
  2128. opt_hidden),
  2129. OPT_WITH_ARG("--gpu-powertune",
  2130. set_gpu_powertune, NULL, NULL,
  2131. opt_hidden),
  2132. OPT_WITHOUT_ARG("--gpu-reorder",
  2133. opt_set_bool, &opt_reorder,
  2134. "Attempt to reorder GPU devices according to PCI Bus ID"),
  2135. OPT_WITH_ARG("--gpu-vddc",
  2136. set_gpu_vddc, NULL, NULL,
  2137. opt_hidden),
  2138. #endif
  2139. #ifdef USE_SCRYPT
  2140. OPT_WITH_ARG("--lookup-gap",
  2141. set_lookup_gap, NULL, NULL,
  2142. opt_hidden),
  2143. #endif
  2144. OPT_WITH_ARG("--intensity|-I",
  2145. set_intensity, NULL, NULL,
  2146. opt_hidden),
  2147. #endif
  2148. #if defined(HAVE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  2149. OPT_WITH_ARG("--kernel-path",
  2150. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2151. "Specify a path to where bitstream and kernel files are"),
  2152. OPT_WITH_ARG("-K",
  2153. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2154. opt_hidden),
  2155. #endif
  2156. #ifdef HAVE_OPENCL
  2157. OPT_WITH_ARG("--kernel|-k",
  2158. set_kernel, NULL, NULL,
  2159. opt_hidden),
  2160. #endif
  2161. #ifdef USE_ICARUS
  2162. OPT_WITH_ARG("--icarus-options",
  2163. set_icarus_options, NULL, NULL,
  2164. opt_hidden),
  2165. OPT_WITH_ARG("--icarus-timing",
  2166. set_icarus_timing, NULL, NULL,
  2167. opt_hidden),
  2168. #endif
  2169. #ifdef USE_AVALON
  2170. OPT_WITH_ARG("--avalon-options",
  2171. set_avalon_options, NULL, NULL,
  2172. opt_hidden),
  2173. #endif
  2174. #ifdef USE_KLONDIKE
  2175. OPT_WITH_ARG("--klondike-options",
  2176. set_klondike_options, NULL, NULL,
  2177. "Set klondike options clock:temptarget"),
  2178. #endif
  2179. OPT_WITHOUT_ARG("--load-balance",
  2180. set_loadbalance, &pool_strategy,
  2181. "Change multipool strategy from failover to quota based balance"),
  2182. OPT_WITH_ARG("--log|-l",
  2183. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  2184. "Interval in seconds between log output"),
  2185. OPT_WITH_ARG("--log-file|-L",
  2186. set_log_file, NULL, NULL,
  2187. "Append log file for output messages"),
  2188. OPT_WITH_ARG("--logfile",
  2189. set_log_file, NULL, NULL,
  2190. opt_hidden),
  2191. OPT_WITHOUT_ARG("--log-microseconds",
  2192. opt_set_bool, &opt_log_microseconds,
  2193. "Include microseconds in log output"),
  2194. #if defined(unix) || defined(__APPLE__)
  2195. OPT_WITH_ARG("--monitor|-m",
  2196. opt_set_charp, NULL, &opt_stderr_cmd,
  2197. "Use custom pipe cmd for output messages"),
  2198. #endif // defined(unix)
  2199. OPT_WITHOUT_ARG("--net-delay",
  2200. opt_set_bool, &opt_delaynet,
  2201. "Impose small delays in networking to avoid overloading slow routers"),
  2202. OPT_WITHOUT_ARG("--no-adl",
  2203. opt_set_bool, &opt_noadl,
  2204. #ifdef HAVE_ADL
  2205. "Disable the ATI display library used for monitoring and setting GPU parameters"
  2206. #else
  2207. opt_hidden
  2208. #endif
  2209. ),
  2210. OPT_WITHOUT_ARG("--no-gbt",
  2211. opt_set_invbool, &want_gbt,
  2212. "Disable getblocktemplate support"),
  2213. OPT_WITHOUT_ARG("--no-getwork",
  2214. opt_set_invbool, &want_getwork,
  2215. "Disable getwork support"),
  2216. OPT_WITHOUT_ARG("--no-hotplug",
  2217. #ifdef HAVE_BFG_HOTPLUG
  2218. opt_set_invbool, &opt_hotplug,
  2219. "Disable hotplug detection"
  2220. #else
  2221. set_null, &opt_hotplug,
  2222. opt_hidden
  2223. #endif
  2224. ),
  2225. OPT_WITHOUT_ARG("--no-local-bitcoin",
  2226. #if BLKMAKER_VERSION > 1
  2227. opt_set_invbool, &opt_load_bitcoin_conf,
  2228. "Disable adding pools for local bitcoin RPC servers"),
  2229. #else
  2230. set_null, NULL, opt_hidden),
  2231. #endif
  2232. OPT_WITHOUT_ARG("--no-longpoll",
  2233. opt_set_invbool, &want_longpoll,
  2234. "Disable X-Long-Polling support"),
  2235. OPT_WITHOUT_ARG("--no-pool-disable",
  2236. opt_set_invbool, &opt_disable_pool,
  2237. opt_hidden),
  2238. OPT_WITHOUT_ARG("--no-client-reconnect",
  2239. opt_set_invbool, &opt_disable_client_reconnect,
  2240. opt_hidden),
  2241. OPT_WITHOUT_ARG("--no-pool-redirect",
  2242. disable_pool_redirect, NULL,
  2243. "Ignore pool requests to redirect to another server"),
  2244. OPT_WITHOUT_ARG("--no-restart",
  2245. opt_set_invbool, &opt_restart,
  2246. "Do not attempt to restart devices that hang"
  2247. ),
  2248. OPT_WITHOUT_ARG("--no-show-processors",
  2249. opt_set_invbool, &opt_show_procs,
  2250. opt_hidden),
  2251. OPT_WITHOUT_ARG("--no-show-procs",
  2252. opt_set_invbool, &opt_show_procs,
  2253. opt_hidden),
  2254. OPT_WITHOUT_ARG("--no-stratum",
  2255. opt_set_invbool, &want_stratum,
  2256. "Disable Stratum detection"),
  2257. OPT_WITHOUT_ARG("--no-submit-stale",
  2258. opt_set_invbool, &opt_submit_stale,
  2259. "Don't submit shares if they are detected as stale"),
  2260. #ifdef HAVE_OPENCL
  2261. OPT_WITHOUT_ARG("--no-opencl-binaries",
  2262. set_no_opencl_binaries, NULL,
  2263. opt_hidden),
  2264. #endif
  2265. OPT_WITHOUT_ARG("--no-unicode",
  2266. #ifdef USE_UNICODE
  2267. opt_set_invbool, &use_unicode,
  2268. "Don't use Unicode characters in TUI"
  2269. #else
  2270. set_null, &use_unicode,
  2271. opt_hidden
  2272. #endif
  2273. ),
  2274. OPT_WITH_ARG("--noncelog",
  2275. set_noncelog, NULL, NULL,
  2276. "Create log of all nonces found"),
  2277. OPT_WITH_ARG("--pass|-p",
  2278. set_pass, NULL, NULL,
  2279. "Password for bitcoin JSON-RPC server"),
  2280. OPT_WITHOUT_ARG("--per-device-stats",
  2281. opt_set_bool, &want_per_device_stats,
  2282. "Force verbose mode and output per-device statistics"),
  2283. OPT_WITH_ARG("--userpass|-O",
  2284. set_userpass, NULL, NULL,
  2285. "Username:Password pair for bitcoin JSON-RPC server"),
  2286. OPT_WITH_ARG("--pool-goal",
  2287. set_pool_goal, NULL, NULL,
  2288. "Named goal for the previous-defined pool"),
  2289. OPT_WITH_ARG("--pool-priority",
  2290. set_pool_priority, NULL, NULL,
  2291. "Priority for just the previous-defined pool"),
  2292. OPT_WITH_ARG("--pool-proxy|-x",
  2293. set_pool_proxy, NULL, NULL,
  2294. "Proxy URI to use for connecting to just the previous-defined pool"),
  2295. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  2296. set_pool_force_rollntime, NULL, NULL,
  2297. opt_hidden),
  2298. OPT_WITHOUT_ARG("--protocol-dump|-P",
  2299. opt_set_bool, &opt_protocol,
  2300. "Verbose dump of protocol-level activities"),
  2301. OPT_WITH_ARG("--queue|-Q",
  2302. set_int_0_to_9999, opt_show_intval, &opt_queue,
  2303. "Minimum number of work items to have queued (0+)"),
  2304. OPT_WITHOUT_ARG("--quiet|-q",
  2305. opt_set_bool, &opt_quiet,
  2306. "Disable logging output, display status and errors"),
  2307. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  2308. opt_set_bool, &opt_quiet_work_updates,
  2309. opt_hidden),
  2310. OPT_WITH_ARG("--quit-summary",
  2311. set_quit_summary, NULL, NULL,
  2312. "Summary printed when you quit: none/devs/procs/detailed"),
  2313. OPT_WITH_ARG("--quota|-U",
  2314. set_quota, NULL, NULL,
  2315. "quota;URL combination for server with load-balance strategy quotas"),
  2316. OPT_WITHOUT_ARG("--real-quiet",
  2317. opt_set_bool, &opt_realquiet,
  2318. "Disable all output"),
  2319. OPT_WITH_ARG("--request-diff",
  2320. set_request_diff, opt_show_floatval, &request_pdiff,
  2321. "Request a specific difficulty from pools"),
  2322. OPT_WITH_ARG("--retries",
  2323. opt_set_intval, opt_show_intval, &opt_retries,
  2324. "Number of times to retry failed submissions before giving up (-1 means never)"),
  2325. OPT_WITH_ARG("--retry-pause",
  2326. set_null, NULL, NULL,
  2327. opt_hidden),
  2328. OPT_WITH_ARG("--rotate",
  2329. set_rotate, opt_show_intval, &opt_rotate_period,
  2330. "Change multipool strategy from failover to regularly rotate at N minutes"),
  2331. OPT_WITHOUT_ARG("--round-robin",
  2332. set_rr, &pool_strategy,
  2333. "Change multipool strategy from failover to round robin on failure"),
  2334. OPT_WITH_ARG("--scan|-S",
  2335. add_serial, NULL, NULL,
  2336. "Configure how to scan for mining devices"),
  2337. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  2338. add_serial, NULL, NULL,
  2339. opt_hidden),
  2340. OPT_WITH_ARG("--scan-time",
  2341. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2342. "Upper bound on time spent scanning current work, in seconds"),
  2343. OPT_WITH_ARG("-s",
  2344. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2345. opt_hidden),
  2346. OPT_WITH_ARG("--scantime",
  2347. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2348. opt_hidden),
  2349. OPT_WITH_ARG("--sched-start",
  2350. set_schedtime, NULL, &schedstart,
  2351. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  2352. OPT_WITH_ARG("--sched-stop",
  2353. set_schedtime, NULL, &schedstop,
  2354. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  2355. #ifdef USE_SCRYPT
  2356. OPT_WITHOUT_ARG("--scrypt",
  2357. set_malgo_scrypt, NULL,
  2358. "Use the scrypt algorithm for mining (non-bitcoin)"),
  2359. #endif
  2360. OPT_WITH_ARG("--set-device|--set",
  2361. opt_string_elist_add, NULL, &opt_set_device_list,
  2362. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  2363. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2364. OPT_WITH_ARG("--shaders",
  2365. set_shaders, NULL, NULL,
  2366. opt_hidden),
  2367. #endif
  2368. #ifdef HAVE_PWD_H
  2369. OPT_WITH_ARG("--setuid",
  2370. opt_set_charp, NULL, &opt_setuid,
  2371. "Username of an unprivileged user to run as"),
  2372. #endif
  2373. OPT_WITH_ARG("--sharelog",
  2374. set_sharelog, NULL, NULL,
  2375. "Append share log to file"),
  2376. OPT_WITH_ARG("--shares",
  2377. opt_set_floatval, NULL, &opt_shares,
  2378. "Quit after mining 2^32 * N hashes worth of shares (default: unlimited)"),
  2379. OPT_WITHOUT_ARG("--show-processors",
  2380. opt_set_bool, &opt_show_procs,
  2381. "Show per processor statistics in summary"),
  2382. OPT_WITHOUT_ARG("--show-procs",
  2383. opt_set_bool, &opt_show_procs,
  2384. opt_hidden),
  2385. OPT_WITH_ARG("--skip-security-checks",
  2386. set_int_0_to_9999, NULL, &opt_skip_checks,
  2387. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  2388. OPT_WITH_ARG("--socks-proxy",
  2389. opt_set_charp, NULL, &opt_socks_proxy,
  2390. "Set socks proxy (host:port)"),
  2391. #ifdef USE_LIBEVENT
  2392. OPT_WITH_ARG("--stratum-port",
  2393. opt_set_intval, opt_show_intval, &stratumsrv_port,
  2394. "Port number to listen on for stratum miners (-1 means disabled)"),
  2395. #endif
  2396. OPT_WITHOUT_ARG("--submit-stale",
  2397. opt_set_bool, &opt_submit_stale,
  2398. opt_hidden),
  2399. OPT_WITH_ARG("--submit-threads",
  2400. opt_set_intval, opt_show_intval, &opt_submit_threads,
  2401. "Minimum number of concurrent share submissions (default: 64)"),
  2402. #ifdef HAVE_SYSLOG_H
  2403. OPT_WITHOUT_ARG("--syslog",
  2404. opt_set_bool, &use_syslog,
  2405. "Use system log for output messages (default: standard error)"),
  2406. #endif
  2407. OPT_WITH_ARG("--temp-cutoff",
  2408. set_temp_cutoff, NULL, &opt_cutofftemp,
  2409. opt_hidden),
  2410. OPT_WITH_ARG("--temp-hysteresis",
  2411. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2412. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2413. #ifdef HAVE_ADL
  2414. OPT_WITH_ARG("--temp-overheat",
  2415. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2416. opt_hidden),
  2417. #endif
  2418. OPT_WITH_ARG("--temp-target",
  2419. set_temp_target, NULL, NULL,
  2420. opt_hidden),
  2421. OPT_WITHOUT_ARG("--text-only|-T",
  2422. opt_set_invbool, &use_curses,
  2423. #ifdef HAVE_CURSES
  2424. "Disable ncurses formatted screen output"
  2425. #else
  2426. opt_hidden
  2427. #endif
  2428. ),
  2429. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2430. OPT_WITH_ARG("--thread-concurrency",
  2431. set_thread_concurrency, NULL, NULL,
  2432. opt_hidden),
  2433. #endif
  2434. #ifdef USE_UNICODE
  2435. OPT_WITHOUT_ARG("--unicode",
  2436. opt_set_bool, &use_unicode,
  2437. "Use Unicode characters in TUI"),
  2438. #endif
  2439. OPT_WITH_ARG("--url|-o",
  2440. set_url, NULL, NULL,
  2441. "URL for bitcoin JSON-RPC server"),
  2442. OPT_WITH_ARG("--user|-u",
  2443. set_user, NULL, NULL,
  2444. "Username for bitcoin JSON-RPC server"),
  2445. #ifdef HAVE_OPENCL
  2446. OPT_WITH_ARG("--vectors|-v",
  2447. set_vector, NULL, NULL,
  2448. opt_hidden),
  2449. #endif
  2450. OPT_WITHOUT_ARG("--verbose",
  2451. opt_set_bool, &opt_log_output,
  2452. "Log verbose output to stderr as well as status output"),
  2453. OPT_WITHOUT_ARG("--verbose-work-updates|--verbose-work-update",
  2454. opt_set_invbool, &opt_quiet_work_updates,
  2455. opt_hidden),
  2456. OPT_WITHOUT_ARG("--weighed-stats",
  2457. opt_set_bool, &opt_weighed_stats,
  2458. "Display statistics weighed to difficulty 1"),
  2459. #ifdef HAVE_OPENCL
  2460. OPT_WITH_ARG("--worksize|-w",
  2461. set_worksize, NULL, NULL,
  2462. opt_hidden),
  2463. #endif
  2464. OPT_WITHOUT_ARG("--unittest",
  2465. opt_set_bool, &opt_unittest, opt_hidden),
  2466. OPT_WITH_ARG("--coinbase-check-addr",
  2467. set_cbcaddr, NULL, NULL,
  2468. "A list of address to check against in coinbase payout list received from the previous-defined pool, separated by ','"),
  2469. OPT_WITH_ARG("--cbcheck-addr|--cbc-addr|--cbcaddr",
  2470. set_cbcaddr, NULL, NULL,
  2471. opt_hidden),
  2472. OPT_WITH_ARG("--coinbase-check-total",
  2473. set_cbctotal, NULL, NULL,
  2474. "The least total payout amount expected in coinbase received from the previous-defined pool"),
  2475. OPT_WITH_ARG("--cbcheck-total|--cbc-total|--cbctotal",
  2476. set_cbctotal, NULL, NULL,
  2477. opt_hidden),
  2478. OPT_WITH_ARG("--coinbase-check-percent",
  2479. set_cbcperc, NULL, NULL,
  2480. "The least benefit percentage expected for the sum of addr(s) listed in --cbaddr argument for previous-defined pool"),
  2481. OPT_WITH_ARG("--cbcheck-percent|--cbc-percent|--cbcpercent|--cbcperc",
  2482. set_cbcperc, NULL, NULL,
  2483. opt_hidden),
  2484. OPT_WITHOUT_ARG("--worktime",
  2485. opt_set_bool, &opt_worktime,
  2486. "Display extra work time debug information"),
  2487. OPT_WITH_ARG("--pools",
  2488. opt_set_bool, NULL, NULL, opt_hidden),
  2489. OPT_ENDTABLE
  2490. };
  2491. static char *load_config(const char *arg, void __maybe_unused *unused);
  2492. static char *parse_config(json_t *config, bool fileconf, int * const fileconf_load_p)
  2493. {
  2494. static char err_buf[200];
  2495. struct opt_table *opt;
  2496. json_t *val;
  2497. if (fileconf && !*fileconf_load_p)
  2498. *fileconf_load_p = 1;
  2499. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2500. char *p, *name, *sp;
  2501. /* We don't handle subtables. */
  2502. assert(!(opt->type & OPT_SUBTABLE));
  2503. if (!opt->names)
  2504. continue;
  2505. /* Pull apart the option name(s). */
  2506. name = strdup(opt->names);
  2507. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2508. char *err = "Invalid value";
  2509. /* Ignore short options. */
  2510. if (p[1] != '-')
  2511. continue;
  2512. val = json_object_get(config, p+2);
  2513. if (!val)
  2514. continue;
  2515. if (opt->type & OPT_HASARG) {
  2516. if (json_is_string(val)) {
  2517. err = opt->cb_arg(json_string_value(val),
  2518. opt->u.arg);
  2519. } else if (json_is_number(val)) {
  2520. char buf[256], *p, *q;
  2521. snprintf(buf, 256, "%f", json_number_value(val));
  2522. if ( (p = strchr(buf, '.')) ) {
  2523. // Trim /\.0*$/ to work properly with integer-only arguments
  2524. q = p;
  2525. while (*(++q) == '0') {}
  2526. if (*q == '\0')
  2527. *p = '\0';
  2528. }
  2529. err = opt->cb_arg(buf, opt->u.arg);
  2530. } else if (json_is_array(val)) {
  2531. int n, size = json_array_size(val);
  2532. err = NULL;
  2533. for (n = 0; n < size && !err; n++) {
  2534. if (json_is_string(json_array_get(val, n)))
  2535. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2536. else if (json_is_object(json_array_get(val, n)))
  2537. err = parse_config(json_array_get(val, n), false, fileconf_load_p);
  2538. }
  2539. }
  2540. } else if (opt->type & OPT_NOARG) {
  2541. if (json_is_true(val))
  2542. err = opt->cb(opt->u.arg);
  2543. else if (json_is_boolean(val)) {
  2544. if (opt->cb == (void*)opt_set_bool)
  2545. err = opt_set_invbool(opt->u.arg);
  2546. else if (opt->cb == (void*)opt_set_invbool)
  2547. err = opt_set_bool(opt->u.arg);
  2548. }
  2549. }
  2550. if (err) {
  2551. /* Allow invalid values to be in configuration
  2552. * file, just skipping over them provided the
  2553. * JSON is still valid after that. */
  2554. if (fileconf) {
  2555. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2556. *fileconf_load_p = -1;
  2557. } else {
  2558. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2559. p, err);
  2560. return err_buf;
  2561. }
  2562. }
  2563. }
  2564. free(name);
  2565. }
  2566. val = json_object_get(config, JSON_INCLUDE_CONF);
  2567. if (val && json_is_string(val))
  2568. return load_config(json_string_value(val), NULL);
  2569. return NULL;
  2570. }
  2571. struct bfg_loaded_configfile *bfg_loaded_configfiles;
  2572. static char *load_config(const char *arg, void __maybe_unused *unused)
  2573. {
  2574. json_error_t err;
  2575. json_t *config;
  2576. char *json_error;
  2577. size_t siz;
  2578. struct bfg_loaded_configfile *cfginfo;
  2579. cfginfo = malloc(sizeof(*cfginfo));
  2580. *cfginfo = (struct bfg_loaded_configfile){
  2581. .filename = strdup(arg),
  2582. };
  2583. LL_APPEND(bfg_loaded_configfiles, cfginfo);
  2584. if (++include_count > JSON_MAX_DEPTH)
  2585. return JSON_MAX_DEPTH_ERR;
  2586. #if JANSSON_MAJOR_VERSION > 1
  2587. config = json_load_file(arg, 0, &err);
  2588. #else
  2589. config = json_load_file(arg, &err);
  2590. #endif
  2591. if (!json_is_object(config)) {
  2592. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2593. json_error = malloc(siz);
  2594. if (!json_error)
  2595. quit(1, "Malloc failure in json error");
  2596. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2597. return json_error;
  2598. }
  2599. config_loaded = true;
  2600. /* Parse the config now, so we can override it. That can keep pointers
  2601. * so don't free config object. */
  2602. return parse_config(config, true, &cfginfo->fileconf_load);
  2603. }
  2604. static
  2605. bool _load_default_configs(const char * const filepath, void * __maybe_unused userp)
  2606. {
  2607. bool * const found_defcfg_p = userp;
  2608. *found_defcfg_p = true;
  2609. load_config(filepath, NULL);
  2610. // Regardless of status of loading the config file, we should continue loading other defaults
  2611. return false;
  2612. }
  2613. static void load_default_config(void)
  2614. {
  2615. bool found_defcfg = false;
  2616. appdata_file_call("BFGMiner", def_conf, _load_default_configs, &found_defcfg);
  2617. if (!found_defcfg)
  2618. {
  2619. // No BFGMiner config, try Cgminer's...
  2620. appdata_file_call("cgminer", "cgminer.conf", _load_default_configs, &found_defcfg);
  2621. }
  2622. }
  2623. extern const char *opt_argv0;
  2624. static char *opt_verusage_and_exit(const char *extra)
  2625. {
  2626. puts(packagename);
  2627. printf(" Lowlevel:%s\n", BFG_LOWLLIST);
  2628. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2629. printf(" Algorithms:%s\n", BFG_ALGOLIST);
  2630. printf(" Options:%s\n", BFG_OPTLIST);
  2631. printf("%s", opt_usage(opt_argv0, extra));
  2632. fflush(stdout);
  2633. exit(0);
  2634. }
  2635. /* These options are parsed before anything else */
  2636. static struct opt_table opt_early_table[] = {
  2637. // Default config is loaded in command line order, like a regular config
  2638. OPT_EARLY_WITH_ARG("--config|-c|--default-config",
  2639. set_bool_ignore_arg, NULL, &config_loaded,
  2640. opt_hidden),
  2641. OPT_EARLY_WITHOUT_ARG("--no-config|--no-default-config",
  2642. opt_set_bool, &config_loaded,
  2643. "Inhibit loading default config file"),
  2644. OPT_ENDTABLE
  2645. };
  2646. /* These options are available from commandline only */
  2647. static struct opt_table opt_cmdline_table[] = {
  2648. OPT_WITH_ARG("--config|-c",
  2649. load_config, NULL, NULL,
  2650. "Load a JSON-format configuration file\n"
  2651. "See example.conf for an example configuration."),
  2652. OPT_EARLY_WITHOUT_ARG("--no-config",
  2653. opt_set_bool, &config_loaded,
  2654. opt_hidden),
  2655. OPT_EARLY_WITHOUT_ARG("--no-default-config",
  2656. opt_set_bool, &config_loaded,
  2657. "Inhibit loading default config file"),
  2658. OPT_WITHOUT_ARG("--default-config",
  2659. load_default_config, NULL,
  2660. "Always load the default config file"),
  2661. OPT_WITHOUT_ARG("--help|-h",
  2662. opt_verusage_and_exit, NULL,
  2663. "Print this message"),
  2664. #ifdef HAVE_OPENCL
  2665. OPT_WITHOUT_ARG("--ndevs|-n",
  2666. print_ndevs_and_exit, &nDevs,
  2667. opt_hidden),
  2668. #endif
  2669. OPT_WITHOUT_ARG("--version|-V",
  2670. opt_version_and_exit, packagename,
  2671. "Display version and exit"),
  2672. OPT_ENDTABLE
  2673. };
  2674. static bool jobj_binary(const json_t *obj, const char *key,
  2675. void *buf, size_t buflen, bool required)
  2676. {
  2677. const char *hexstr;
  2678. json_t *tmp;
  2679. tmp = json_object_get(obj, key);
  2680. if (unlikely(!tmp)) {
  2681. if (unlikely(required))
  2682. applog(LOG_ERR, "JSON key '%s' not found", key);
  2683. return false;
  2684. }
  2685. hexstr = json_string_value(tmp);
  2686. if (unlikely(!hexstr)) {
  2687. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2688. return false;
  2689. }
  2690. if (!hex2bin(buf, hexstr, buflen))
  2691. return false;
  2692. return true;
  2693. }
  2694. static void calc_midstate(struct work *work)
  2695. {
  2696. union {
  2697. unsigned char c[64];
  2698. uint32_t i[16];
  2699. } data;
  2700. swap32yes(&data.i[0], work->data, 16);
  2701. sha256_ctx ctx;
  2702. sha256_init(&ctx);
  2703. sha256_update(&ctx, data.c, 64);
  2704. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2705. swap32tole(work->midstate, work->midstate, 8);
  2706. }
  2707. static
  2708. struct bfg_tmpl_ref *tmpl_makeref(blktemplate_t * const tmpl)
  2709. {
  2710. struct bfg_tmpl_ref * const tr = malloc(sizeof(*tr));
  2711. *tr = (struct bfg_tmpl_ref){
  2712. .tmpl = tmpl,
  2713. .refcount = 1,
  2714. };
  2715. mutex_init(&tr->mutex);
  2716. return tr;
  2717. }
  2718. static
  2719. void tmpl_incref(struct bfg_tmpl_ref * const tr)
  2720. {
  2721. mutex_lock(&tr->mutex);
  2722. ++tr->refcount;
  2723. mutex_unlock(&tr->mutex);
  2724. }
  2725. void tmpl_decref(struct bfg_tmpl_ref * const tr)
  2726. {
  2727. mutex_lock(&tr->mutex);
  2728. bool free_tmpl = !--tr->refcount;
  2729. mutex_unlock(&tr->mutex);
  2730. if (free_tmpl)
  2731. {
  2732. blktmpl_free(tr->tmpl);
  2733. mutex_destroy(&tr->mutex);
  2734. free(tr);
  2735. }
  2736. }
  2737. static struct work *make_work(void)
  2738. {
  2739. struct work *work = calloc(1, sizeof(struct work));
  2740. if (unlikely(!work))
  2741. quit(1, "Failed to calloc work in make_work");
  2742. cg_wlock(&control_lock);
  2743. work->id = total_work++;
  2744. cg_wunlock(&control_lock);
  2745. return work;
  2746. }
  2747. /* This is the central place all work that is about to be retired should be
  2748. * cleaned to remove any dynamically allocated arrays within the struct */
  2749. void clean_work(struct work *work)
  2750. {
  2751. free(work->job_id);
  2752. bytes_free(&work->nonce2);
  2753. free(work->nonce1);
  2754. if (work->device_data_free_func)
  2755. work->device_data_free_func(work);
  2756. if (work->tr)
  2757. tmpl_decref(work->tr);
  2758. memset(work, 0, sizeof(struct work));
  2759. }
  2760. /* All dynamically allocated work structs should be freed here to not leak any
  2761. * ram from arrays allocated within the work struct */
  2762. void free_work(struct work *work)
  2763. {
  2764. clean_work(work);
  2765. free(work);
  2766. }
  2767. 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";
  2768. #define workpadding_bin bfg_workpadding_bin
  2769. static const size_t block_info_str_sz = 3 /* ... */ + 16 /* block hash segment */ + 1;
  2770. static
  2771. void block_info_str(char * const out, const struct block_info * const blkinfo)
  2772. {
  2773. unsigned char hash_swap[32];
  2774. swap256(hash_swap, blkinfo->prevblkhash);
  2775. swap32tole(hash_swap, hash_swap, 32 / 4);
  2776. memset(out, '.', 3);
  2777. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2778. if (blkinfo->height > 0 && blkinfo->height < 1000000)
  2779. {
  2780. bin2hex(&out[3], &hash_swap[0x1c], 4);
  2781. snprintf(&out[11], block_info_str_sz-11, " #%6u", blkinfo->height);
  2782. }
  2783. else
  2784. bin2hex(&out[3], &hash_swap[0x18], 8);
  2785. }
  2786. #ifdef HAVE_CURSES
  2787. static void update_block_display(void);
  2788. #endif
  2789. // Must only be called with ch_lock held!
  2790. static
  2791. void __update_block_title(struct mining_goal_info * const goal)
  2792. {
  2793. struct blockchain_info * const blkchain = goal->blkchain;
  2794. if (!goal->current_goal_detail)
  2795. goal->current_goal_detail = malloc(block_info_str_sz);
  2796. block_info_str(goal->current_goal_detail, blkchain->currentblk);
  2797. #ifdef HAVE_CURSES
  2798. update_block_display();
  2799. #endif
  2800. }
  2801. static struct block_info *block_exists(const struct blockchain_info *, const void *);
  2802. static
  2803. void have_block_height(struct mining_goal_info * const goal, const void * const prevblkhash, uint32_t blkheight)
  2804. {
  2805. struct blockchain_info * const blkchain = goal->blkchain;
  2806. struct block_info * const blkinfo = block_exists(blkchain, prevblkhash);
  2807. if ((!blkinfo) || blkinfo->height)
  2808. return;
  2809. uint32_t block_id = ((uint32_t*)prevblkhash)[0];
  2810. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2811. cg_wlock(&ch_lock);
  2812. blkinfo->height = blkheight;
  2813. if (blkinfo == blkchain->currentblk)
  2814. {
  2815. blkchain->currentblk_subsidy = 5000000000LL >> (blkheight / 210000);
  2816. __update_block_title(goal);
  2817. }
  2818. cg_wunlock(&ch_lock);
  2819. }
  2820. static
  2821. void pool_set_opaque(struct pool *pool, bool opaque)
  2822. {
  2823. if (pool->swork.opaque == opaque)
  2824. return;
  2825. pool->swork.opaque = opaque;
  2826. if (opaque)
  2827. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2828. pool->pool_no);
  2829. else
  2830. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2831. pool->pool_no);
  2832. }
  2833. bool pool_may_redirect_to(struct pool * const pool, const char * const uri)
  2834. {
  2835. if (uri_get_param_bool(pool->rpc_url, "redirect", false))
  2836. return true;
  2837. return match_domains(pool->rpc_url, strlen(pool->rpc_url), uri, strlen(uri));
  2838. }
  2839. void pool_check_coinbase(struct pool * const pool, const uint8_t * const cbtxn, const size_t cbtxnsz)
  2840. {
  2841. if (uri_get_param_bool(pool->rpc_url, "skipcbcheck", false))
  2842. {}
  2843. else
  2844. if (!check_coinbase(cbtxn, cbtxnsz, &pool->cb_param))
  2845. {
  2846. if (pool->enabled == POOL_ENABLED)
  2847. {
  2848. applog(LOG_ERR, "Pool %d misbehaving (%s), disabling!", pool->pool_no, "coinbase check");
  2849. disable_pool(pool, POOL_MISBEHAVING);
  2850. }
  2851. }
  2852. else
  2853. if (pool->enabled == POOL_MISBEHAVING)
  2854. {
  2855. applog(LOG_NOTICE, "Pool %d no longer misbehaving, re-enabling!", pool->pool_no);
  2856. enable_pool(pool);
  2857. }
  2858. }
  2859. 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)
  2860. {
  2861. const int offsets = max(ntime_roll, 60);
  2862. *nrl = (struct ntime_roll_limits){
  2863. .min = ntime_base,
  2864. .max = ntime_base + ntime_roll,
  2865. .tv_ref = *tvp_ref,
  2866. .minoff = -offsets,
  2867. .maxoff = offsets,
  2868. };
  2869. }
  2870. void work_set_simple_ntime_roll_limit(struct work * const work, const int ntime_roll, const struct timeval * const tvp_ref)
  2871. {
  2872. set_simple_ntime_roll_limit(&work->ntime_roll_limits, upk_u32be(work->data, 0x44), ntime_roll, tvp_ref);
  2873. }
  2874. int work_ntime_range(struct work * const work, const struct timeval * const tvp_earliest, const struct timeval * const tvp_latest, const int desired_roll)
  2875. {
  2876. const struct ntime_roll_limits * const nrl = &work->ntime_roll_limits;
  2877. const uint32_t ref_ntime = work_get_ntime(work);
  2878. const int earliest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_earliest);
  2879. const int latest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_latest);
  2880. // minimum ntime is the latest possible result (add a second to spare) adjusted for minimum offset (or fixed minimum ntime)
  2881. uint32_t min_ntime = max(nrl->min, ref_ntime + latest_elapsed+1 + nrl->minoff);
  2882. // maximum ntime is the earliest possible result adjusted for maximum offset (or fixed maximum ntime)
  2883. uint32_t max_ntime = min(nrl->max, ref_ntime + earliest_elapsed + nrl->maxoff);
  2884. if (max_ntime < min_ntime)
  2885. return -1;
  2886. if (max_ntime - min_ntime > desired_roll)
  2887. {
  2888. // Adjust min_ntime upward for accuracy, when possible
  2889. const int mid_elapsed = ((latest_elapsed - earliest_elapsed) / 2) + earliest_elapsed;
  2890. uint32_t ideal_ntime = ref_ntime + mid_elapsed;
  2891. if (ideal_ntime > min_ntime)
  2892. min_ntime = min(ideal_ntime, max_ntime - desired_roll);
  2893. }
  2894. work_set_ntime(work, min_ntime);
  2895. return max_ntime - min_ntime;
  2896. }
  2897. #if BLKMAKER_VERSION > 1
  2898. static
  2899. bool goal_has_at_least_one_getcbaddr(const struct mining_goal_info * const goal)
  2900. {
  2901. for (int i = 0; i < total_pools; ++i)
  2902. {
  2903. struct pool * const pool = pools[i];
  2904. if (uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2905. return true;
  2906. }
  2907. return false;
  2908. }
  2909. static
  2910. void refresh_bitcoind_address(struct mining_goal_info * const goal, const bool fresh)
  2911. {
  2912. struct blockchain_info * const blkchain = goal->blkchain;
  2913. if (!goal_has_at_least_one_getcbaddr(goal))
  2914. return;
  2915. char getcbaddr_req[60];
  2916. CURL *curl = NULL;
  2917. json_t *json, *j2;
  2918. const char *s, *s2;
  2919. bytes_t newscript = BYTES_INIT;
  2920. snprintf(getcbaddr_req, sizeof(getcbaddr_req), "{\"method\":\"get%saddress\",\"id\":0,\"params\":[\"BFGMiner\"]}", fresh ? "new" : "account");
  2921. for (int i = 0; i < total_pools; ++i)
  2922. {
  2923. struct pool * const pool = pools[i];
  2924. if (!uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2925. continue;
  2926. if (pool->goal != goal)
  2927. continue;
  2928. applog(LOG_DEBUG, "Refreshing coinbase address from pool %d", pool->pool_no);
  2929. if (!curl)
  2930. {
  2931. curl = curl_easy_init();
  2932. if (unlikely(!curl))
  2933. {
  2934. applogfail(LOG_ERR, "curl_easy_init");
  2935. break;
  2936. }
  2937. }
  2938. json = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, getcbaddr_req, false, false, NULL, pool, true);
  2939. if (unlikely((!json) || !json_is_null( (j2 = json_object_get(json, "error")) )))
  2940. {
  2941. const char *estrc;
  2942. char *estr = NULL;
  2943. if (!(json && j2))
  2944. estrc = NULL;
  2945. else
  2946. {
  2947. estrc = json_string_value(j2);
  2948. if (!estrc)
  2949. estrc = estr = json_dumps_ANY(j2, JSON_ENSURE_ASCII | JSON_SORT_KEYS);
  2950. }
  2951. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, estrc);
  2952. free(estr);
  2953. continue;
  2954. }
  2955. s = bfg_json_obj_string(json, "result", NULL);
  2956. if (unlikely(!s))
  2957. {
  2958. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, "(return value was not a String)");
  2959. continue;
  2960. }
  2961. s2 = set_b58addr(s, &newscript);
  2962. if (unlikely(s2))
  2963. {
  2964. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 's', pool->pool_no, s2);
  2965. continue;
  2966. }
  2967. if (goal->generation_script)
  2968. {
  2969. if (bytes_eq(&newscript, goal->generation_script))
  2970. {
  2971. applog(LOG_DEBUG, "Pool %d returned coinbase address already in use (%s)", pool->pool_no, s2);
  2972. break;
  2973. }
  2974. }
  2975. else
  2976. {
  2977. goal->generation_script = malloc(sizeof(*goal->generation_script));
  2978. bytes_init(goal->generation_script);
  2979. }
  2980. bytes_assimilate(goal->generation_script, &newscript);
  2981. coinbase_script_block_id = blkchain->currentblk->block_id;
  2982. applog(LOG_NOTICE, "Now using coinbase address %s, provided by pool %d", s, pool->pool_no);
  2983. break;
  2984. }
  2985. bytes_free(&newscript);
  2986. if (curl)
  2987. curl_easy_cleanup(curl);
  2988. }
  2989. #endif
  2990. #define GBT_XNONCESZ (sizeof(uint32_t))
  2991. #if BLKMAKER_VERSION > 4
  2992. #define blkmk_append_coinbase_safe(tmpl, append, appendsz) \
  2993. blkmk_append_coinbase_safe2(tmpl, append, appendsz, GBT_XNONCESZ, false)
  2994. #endif
  2995. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  2996. {
  2997. json_t *res_val = json_object_get(val, "result");
  2998. json_t *tmp_val;
  2999. bool ret = false;
  3000. struct timeval tv_now;
  3001. if (unlikely(detect_algo == 1)) {
  3002. json_t *tmp = json_object_get(res_val, "algorithm");
  3003. const char *v = tmp ? json_string_value(tmp) : "";
  3004. if (strncasecmp(v, "scrypt", 6))
  3005. detect_algo = 2;
  3006. }
  3007. timer_set_now(&tv_now);
  3008. if (work->tr)
  3009. {
  3010. blktemplate_t * const tmpl = work->tr->tmpl;
  3011. const char *err = blktmpl_add_jansson(tmpl, res_val, tv_now.tv_sec);
  3012. if (err) {
  3013. applog(LOG_ERR, "blktmpl error: %s", err);
  3014. return false;
  3015. }
  3016. work->rolltime = blkmk_time_left(tmpl, tv_now.tv_sec);
  3017. #if BLKMAKER_VERSION > 1
  3018. struct mining_goal_info * const goal = pool->goal;
  3019. const uint32_t tmpl_block_id = ((uint32_t*)tmpl->prevblk)[0];
  3020. if ((!tmpl->cbtxn) && coinbase_script_block_id != tmpl_block_id)
  3021. refresh_bitcoind_address(goal, false);
  3022. if (goal->generation_script)
  3023. {
  3024. bool newcb;
  3025. #if BLKMAKER_VERSION > 2
  3026. blkmk_init_generation2(tmpl, bytes_buf(goal->generation_script), bytes_len(goal->generation_script), &newcb);
  3027. #else
  3028. newcb = !tmpl->cbtxn;
  3029. blkmk_init_generation(tmpl, bytes_buf(goal->generation_script), bytes_len(goal->generation_script));
  3030. #endif
  3031. if (newcb)
  3032. {
  3033. ssize_t ae = blkmk_append_coinbase_safe(tmpl, &template_nonce, sizeof(template_nonce));
  3034. if (ae < (ssize_t)sizeof(template_nonce))
  3035. 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);
  3036. ++template_nonce;
  3037. }
  3038. }
  3039. #endif
  3040. #if BLKMAKER_VERSION > 0
  3041. {
  3042. ssize_t ae = blkmk_append_coinbase_safe(tmpl, opt_coinbase_sig, 101);
  3043. static bool appenderr = false;
  3044. if (ae <= 0) {
  3045. if (opt_coinbase_sig) {
  3046. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  3047. appenderr = true;
  3048. }
  3049. } else if (ae >= 3 || opt_coinbase_sig) {
  3050. const char *cbappend = opt_coinbase_sig;
  3051. const char full[] = PACKAGE " " VERSION;
  3052. char *need_free = NULL;
  3053. if (!cbappend) {
  3054. if ((size_t)ae >= sizeof(full) - 1)
  3055. cbappend = full;
  3056. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  3057. {
  3058. const char *pos = strchr(full, '-');
  3059. size_t sz = (pos - full);
  3060. if (pos && ae > sz)
  3061. {
  3062. cbappend = need_free = malloc(sz + 1);
  3063. memcpy(need_free, full, sz);
  3064. need_free[sz] = '\0';
  3065. }
  3066. else
  3067. cbappend = PACKAGE;
  3068. }
  3069. else
  3070. cbappend = "BFG";
  3071. }
  3072. size_t cbappendsz = strlen(cbappend);
  3073. static bool truncatewarning = false;
  3074. if (cbappendsz <= (size_t)ae) {
  3075. if (cbappendsz < (size_t)ae)
  3076. // If we have space, include the trailing \0
  3077. ++cbappendsz;
  3078. ae = cbappendsz;
  3079. truncatewarning = false;
  3080. } else {
  3081. char *tmp = malloc(ae + 1);
  3082. memcpy(tmp, opt_coinbase_sig, ae);
  3083. tmp[ae] = '\0';
  3084. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  3085. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  3086. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  3087. free(tmp);
  3088. truncatewarning = true;
  3089. }
  3090. ae = blkmk_append_coinbase_safe(tmpl, cbappend, ae);
  3091. free(need_free);
  3092. if (ae <= 0) {
  3093. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  3094. appenderr = true;
  3095. } else
  3096. appenderr = false;
  3097. }
  3098. }
  3099. #endif
  3100. if (blkmk_get_data(tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  3101. return false;
  3102. swap32yes(work->data, work->data, 80 / 4);
  3103. memcpy(&work->data[80], workpadding_bin, 48);
  3104. work->ntime_roll_limits = (struct ntime_roll_limits){
  3105. .min = tmpl->mintime,
  3106. .max = tmpl->maxtime,
  3107. .tv_ref = tv_now,
  3108. .minoff = tmpl->mintimeoff,
  3109. .maxoff = tmpl->maxtimeoff,
  3110. };
  3111. const struct blktmpl_longpoll_req *lp;
  3112. if ((lp = blktmpl_get_longpoll(tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  3113. free(pool->lp_id);
  3114. pool->lp_id = strdup(lp->id);
  3115. #if 0 /* This just doesn't work :( */
  3116. curl_socket_t sock = pool->lp_socket;
  3117. if (sock != CURL_SOCKET_BAD) {
  3118. pool->lp_socket = CURL_SOCKET_BAD;
  3119. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  3120. shutdown(sock, SHUT_RDWR);
  3121. }
  3122. #endif
  3123. }
  3124. }
  3125. else
  3126. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  3127. applog(LOG_ERR, "JSON inval data");
  3128. return false;
  3129. }
  3130. else
  3131. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  3132. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  3133. // Calculate it ourselves
  3134. applog(LOG_DEBUG, "Calculating midstate locally");
  3135. calc_midstate(work);
  3136. }
  3137. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  3138. applog(LOG_ERR, "JSON inval target");
  3139. return false;
  3140. }
  3141. if (work->tr)
  3142. {
  3143. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  3144. {
  3145. int p = (sizeof(work->target) - 1) - i;
  3146. unsigned char c = work->target[i];
  3147. work->target[i] = work->target[p];
  3148. work->target[p] = c;
  3149. }
  3150. }
  3151. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  3152. struct mining_goal_info * const goal = pool->goal;
  3153. uint32_t blkheight = json_number_value(tmp_val);
  3154. const void * const prevblkhash = &work->data[4];
  3155. have_block_height(goal, prevblkhash, blkheight);
  3156. }
  3157. memset(work->hash, 0, sizeof(work->hash));
  3158. work->tv_staged = tv_now;
  3159. #if BLKMAKER_VERSION > 4
  3160. if (work->tr)
  3161. {
  3162. blktemplate_t * const tmpl = work->tr->tmpl;
  3163. uint8_t buf[80];
  3164. int16_t expire;
  3165. uint8_t *cbtxn;
  3166. size_t cbtxnsz;
  3167. size_t cbextranonceoffset;
  3168. int branchcount;
  3169. libblkmaker_hash_t *branches;
  3170. if (blkmk_get_mdata(tmpl, buf, sizeof(buf), tv_now.tv_sec, &expire, &cbtxn, &cbtxnsz, &cbextranonceoffset, &branchcount, &branches, GBT_XNONCESZ, false))
  3171. {
  3172. struct stratum_work * const swork = &pool->swork;
  3173. const size_t branchdatasz = branchcount * 0x20;
  3174. pool_check_coinbase(pool, cbtxn, cbtxnsz);
  3175. cg_wlock(&pool->data_lock);
  3176. swork->tr = work->tr;
  3177. bytes_assimilate_raw(&swork->coinbase, cbtxn, cbtxnsz, cbtxnsz);
  3178. swork->nonce2_offset = cbextranonceoffset;
  3179. bytes_assimilate_raw(&swork->merkle_bin, branches, branchdatasz, branchdatasz);
  3180. swork->merkles = branchcount;
  3181. memcpy(swork->header1, &buf[0], 36);
  3182. swork->ntime = le32toh(*(uint32_t *)(&buf[68]));
  3183. swork->tv_received = tv_now;
  3184. memcpy(swork->diffbits, &buf[72], 4);
  3185. memcpy(swork->target, work->target, sizeof(swork->target));
  3186. free(swork->job_id);
  3187. swork->job_id = NULL;
  3188. swork->clean = true;
  3189. swork->work_restart_id = pool->work_restart_id;
  3190. // FIXME: Do something with expire
  3191. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  3192. pool->nonce2 = 0;
  3193. cg_wunlock(&pool->data_lock);
  3194. }
  3195. else
  3196. applog(LOG_DEBUG, "blkmk_get_mdata failed for pool %u", pool->pool_no);
  3197. }
  3198. #endif // BLKMAKER_VERSION > 4
  3199. pool_set_opaque(pool, !work->tr);
  3200. ret = true;
  3201. return ret;
  3202. }
  3203. /* Returns whether the pool supports local work generation or not. */
  3204. static bool pool_localgen(struct pool *pool)
  3205. {
  3206. return (pool->last_work_copy || pool->has_stratum);
  3207. }
  3208. int dev_from_id(int thr_id)
  3209. {
  3210. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  3211. return cgpu->device_id;
  3212. }
  3213. /* Create an exponentially decaying average over the opt_log_interval */
  3214. void decay_time(double *f, double fadd, double fsecs)
  3215. {
  3216. double ftotal, fprop;
  3217. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  3218. ftotal = 1.0 + fprop;
  3219. *f += (fadd * fprop);
  3220. *f /= ftotal;
  3221. }
  3222. static int __total_staged(void)
  3223. {
  3224. return HASH_COUNT(staged_work);
  3225. }
  3226. static int total_staged(void)
  3227. {
  3228. int ret;
  3229. mutex_lock(stgd_lock);
  3230. ret = __total_staged();
  3231. mutex_unlock(stgd_lock);
  3232. return ret;
  3233. }
  3234. #ifdef HAVE_CURSES
  3235. WINDOW *mainwin, *statuswin, *logwin;
  3236. #endif
  3237. double total_secs = 1.0;
  3238. #ifdef HAVE_CURSES
  3239. static char statusline[256];
  3240. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  3241. static int statusy;
  3242. static int devsummaryYOffset;
  3243. static int total_lines;
  3244. #endif
  3245. #ifdef HAVE_OPENCL
  3246. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  3247. #endif
  3248. struct cgpu_info *cpus;
  3249. bool _bfg_console_cancel_disabled;
  3250. int _bfg_console_prev_cancelstate;
  3251. #ifdef HAVE_CURSES
  3252. #define lock_curses() bfg_console_lock()
  3253. #define unlock_curses() bfg_console_unlock()
  3254. static bool curses_active_locked(void)
  3255. {
  3256. bool ret;
  3257. lock_curses();
  3258. ret = curses_active;
  3259. if (!ret)
  3260. unlock_curses();
  3261. return ret;
  3262. }
  3263. // Cancellable getch
  3264. int my_cancellable_getch(void)
  3265. {
  3266. // This only works because the macro only hits direct getch() calls
  3267. typedef int (*real_getch_t)(void);
  3268. const real_getch_t real_getch = __real_getch;
  3269. int type, rv;
  3270. bool sct;
  3271. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  3272. rv = real_getch();
  3273. if (sct)
  3274. pthread_setcanceltype(type, &type);
  3275. return rv;
  3276. }
  3277. #ifdef PDCURSES
  3278. static
  3279. int bfg_wresize(WINDOW *win, int lines, int columns)
  3280. {
  3281. int rv = wresize(win, lines, columns);
  3282. int x, y;
  3283. getyx(win, y, x);
  3284. if (unlikely(y >= lines || x >= columns))
  3285. {
  3286. if (y >= lines)
  3287. y = lines - 1;
  3288. if (x >= columns)
  3289. x = columns - 1;
  3290. wmove(win, y, x);
  3291. }
  3292. return rv;
  3293. }
  3294. #else
  3295. # define bfg_wresize wresize
  3296. #endif
  3297. #endif
  3298. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  3299. {
  3300. va_list ap;
  3301. size_t presz = strlen(buf);
  3302. va_start(ap, fmt);
  3303. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  3304. va_end(ap);
  3305. }
  3306. double stats_elapsed(struct cgminer_stats *stats)
  3307. {
  3308. struct timeval now;
  3309. double elapsed;
  3310. if (stats->start_tv.tv_sec == 0)
  3311. elapsed = total_secs;
  3312. else {
  3313. cgtime(&now);
  3314. elapsed = tdiff(&now, &stats->start_tv);
  3315. }
  3316. if (elapsed < 1.0)
  3317. elapsed = 1.0;
  3318. return elapsed;
  3319. }
  3320. bool drv_ready(struct cgpu_info *cgpu)
  3321. {
  3322. switch (cgpu->status) {
  3323. case LIFE_INIT:
  3324. case LIFE_DEAD2:
  3325. return false;
  3326. default:
  3327. return true;
  3328. }
  3329. }
  3330. double cgpu_utility(struct cgpu_info *cgpu)
  3331. {
  3332. double dev_runtime = cgpu_runtime(cgpu);
  3333. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  3334. }
  3335. #define suffix_string(val, buf, bufsiz, sigdigits) do{ \
  3336. _Static_assert(sigdigits == 0, "suffix_string only supported with sigdigits==0"); \
  3337. format_unit3(buf, bufsiz, FUP_DIFF, "", H2B_SHORTV, val, -1); \
  3338. }while(0)
  3339. static float
  3340. utility_to_hashrate(double utility)
  3341. {
  3342. return utility * 0x4444444;
  3343. }
  3344. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  3345. static const int _unitbase = 4;
  3346. static
  3347. void pick_unit(float hashrate, unsigned char *unit)
  3348. {
  3349. unsigned char i;
  3350. if (hashrate == 0 || !isfinite(hashrate))
  3351. {
  3352. if (*unit < _unitbase)
  3353. *unit = _unitbase;
  3354. return;
  3355. }
  3356. hashrate *= 1e12;
  3357. for (i = 0; i < *unit; ++i)
  3358. hashrate /= 1e3;
  3359. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  3360. while (hashrate >= 999.95)
  3361. {
  3362. hashrate /= 1e3;
  3363. if (likely(_unitchar[*unit] != '?'))
  3364. ++*unit;
  3365. }
  3366. }
  3367. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  3368. enum h2bs_fmt {
  3369. H2B_NOUNIT, // "xxx.x"
  3370. H2B_SHORT, // "xxx.xMH/s"
  3371. H2B_SPACED, // "xxx.x MH/s"
  3372. H2B_SHORTV, // Like H2B_SHORT, but omit space for base unit
  3373. };
  3374. enum bfu_floatprec {
  3375. FUP_INTEGER,
  3376. FUP_HASHES,
  3377. FUP_BTC,
  3378. FUP_DIFF,
  3379. };
  3380. static
  3381. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  3382. {
  3383. char *s = buf;
  3384. unsigned char prec, i, unit;
  3385. int rv = 0;
  3386. if (unitin == -1)
  3387. {
  3388. unit = 0;
  3389. hashrate_pick_unit(hashrate, &unit);
  3390. }
  3391. else
  3392. unit = unitin;
  3393. hashrate *= 1e12;
  3394. for (i = 0; i < unit; ++i)
  3395. hashrate /= 1000;
  3396. switch (fprec)
  3397. {
  3398. case FUP_HASHES:
  3399. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  3400. if (hashrate >= 99.995 || unit < 6)
  3401. prec = 1;
  3402. else
  3403. prec = 2;
  3404. _SNP("%5.*f", prec, hashrate);
  3405. break;
  3406. case FUP_INTEGER:
  3407. _SNP("%3d", (int)hashrate);
  3408. break;
  3409. case FUP_BTC:
  3410. if (hashrate >= 99.995)
  3411. prec = 0;
  3412. else
  3413. prec = 2;
  3414. _SNP("%5.*f", prec, hashrate);
  3415. break;
  3416. case FUP_DIFF:
  3417. if (unit > _unitbase)
  3418. _SNP("%.3g", hashrate);
  3419. else
  3420. _SNP("%u", (unsigned int)hashrate);
  3421. }
  3422. if (fmt != H2B_NOUNIT)
  3423. {
  3424. char uc[3] = {_unitchar[unit], '\0'};
  3425. switch (fmt) {
  3426. case H2B_SPACED:
  3427. _SNP(" ");
  3428. default:
  3429. break;
  3430. case H2B_SHORTV:
  3431. if (isspace(uc[0]))
  3432. uc[0] = '\0';
  3433. }
  3434. if (uc[0] == '\xb5')
  3435. // Convert to UTF-8
  3436. snprintf(uc, sizeof(uc), "%s", U8_MICRO);
  3437. _SNP("%s%s", uc, measurement);
  3438. }
  3439. return rv;
  3440. }
  3441. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  3442. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  3443. static
  3444. 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)
  3445. {
  3446. unsigned char unit = 0;
  3447. bool allzero = true;
  3448. int i;
  3449. size_t delimsz = 0;
  3450. char *buf = buflist[0];
  3451. size_t bufsz = bufszlist[0];
  3452. size_t itemwidth = (floatprec ? 5 : 3);
  3453. if (!isarray)
  3454. delimsz = strlen(delim);
  3455. for (i = 0; i < count; ++i)
  3456. if (numbers[i] != 0)
  3457. {
  3458. pick_unit(numbers[i], &unit);
  3459. allzero = false;
  3460. }
  3461. if (allzero)
  3462. unit = _unitbase;
  3463. --count;
  3464. for (i = 0; i < count; ++i)
  3465. {
  3466. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  3467. if (isarray)
  3468. {
  3469. buf = buflist[i + 1];
  3470. bufsz = bufszlist[i + 1];
  3471. }
  3472. else
  3473. {
  3474. buf += itemwidth;
  3475. bufsz -= itemwidth;
  3476. if (delimsz > bufsz)
  3477. delimsz = bufsz;
  3478. memcpy(buf, delim, delimsz);
  3479. buf += delimsz;
  3480. bufsz -= delimsz;
  3481. }
  3482. }
  3483. // Last entry has the unit
  3484. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  3485. return buflist[0];
  3486. }
  3487. #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)
  3488. #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)
  3489. static
  3490. int percentf3(char * const buf, size_t sz, double p, const double t)
  3491. {
  3492. char *s = buf;
  3493. int rv = 0;
  3494. if (!p)
  3495. _SNP("none");
  3496. else
  3497. if (t <= p)
  3498. _SNP("100%%");
  3499. else
  3500. {
  3501. p /= t;
  3502. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  3503. _SNP(".%02.0f%%", p * 10000); // ".01%"
  3504. else
  3505. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  3506. _SNP("%.1f%%", p * 100); // "9.1%"
  3507. else
  3508. _SNP("%3.0f%%", p * 100); // " 99%"
  3509. }
  3510. return rv;
  3511. }
  3512. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  3513. static
  3514. void test_decimal_width()
  3515. {
  3516. // The pipe character at end of each line should perfectly line up
  3517. char printbuf[512];
  3518. char testbuf1[64];
  3519. char testbuf2[64];
  3520. char testbuf3[64];
  3521. char testbuf4[64];
  3522. double testn;
  3523. int width;
  3524. int saved;
  3525. // Hotspots around 0.1 and 0.01
  3526. saved = -1;
  3527. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  3528. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  3529. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  3530. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  3531. if (unlikely((saved != -1) && (width != saved))) {
  3532. ++unittest_failures;
  3533. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  3534. applog(LOG_ERR, "%s", printbuf);
  3535. }
  3536. saved = width;
  3537. }
  3538. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  3539. saved = -1;
  3540. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  3541. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3542. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3543. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3544. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  3545. width = utf8_strlen(printbuf);
  3546. if (unlikely((saved != -1) && (width != saved))) {
  3547. ++unittest_failures;
  3548. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  3549. applog(LOG_ERR, "%s", printbuf);
  3550. }
  3551. saved = width;
  3552. }
  3553. // Hotspot around unit transition boundary in pick_unit
  3554. saved = -1;
  3555. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  3556. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3557. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3558. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3559. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  3560. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  3561. width = utf8_strlen(printbuf);
  3562. if (unlikely((saved != -1) && (width != saved))) {
  3563. ++unittest_failures;
  3564. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  3565. applog(LOG_ERR, "%s", printbuf);
  3566. }
  3567. saved = width;
  3568. }
  3569. }
  3570. #ifdef HAVE_CURSES
  3571. static void adj_width(int var, int *length);
  3572. #endif
  3573. #ifdef HAVE_CURSES
  3574. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  3575. static
  3576. 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)
  3577. {
  3578. char rejpcbuf[6];
  3579. char bnbuf[6];
  3580. adj_width(accepted, &awidth);
  3581. adj_width(rejected, &rwidth);
  3582. adj_width(stale, &swidth);
  3583. adj_width(hwerrs, &hwwidth);
  3584. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3585. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  3586. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  3587. cHr, aHr, uHr,
  3588. awidth, accepted,
  3589. rwidth, rejected,
  3590. swidth, stale,
  3591. rejpcbuf,
  3592. hwwidth, hwerrs,
  3593. bnbuf
  3594. );
  3595. }
  3596. static
  3597. const char *pool_proto_str(const struct pool * const pool)
  3598. {
  3599. if (pool->idle)
  3600. return "Dead ";
  3601. if (pool->has_stratum)
  3602. return "Strtm";
  3603. if (pool->lp_url && pool->proto != pool->lp_proto)
  3604. return "Mixed";
  3605. switch (pool->proto)
  3606. {
  3607. case PLP_GETBLOCKTEMPLATE:
  3608. return " GBT ";
  3609. case PLP_GETWORK:
  3610. return "GWork";
  3611. default:
  3612. return "Alive";
  3613. }
  3614. }
  3615. #endif
  3616. static inline
  3617. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  3618. {
  3619. if (!(use_unicode && have_unicode_degrees))
  3620. maybe_unicode = false;
  3621. if (temp && *temp > 0.)
  3622. if (maybe_unicode)
  3623. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  3624. else
  3625. snprintf(buf, bufsz, "%4.1fC", *temp);
  3626. else
  3627. {
  3628. if (temp)
  3629. snprintf(buf, bufsz, " ");
  3630. if (maybe_unicode)
  3631. tailsprintf(buf, bufsz, " ");
  3632. }
  3633. tailsprintf(buf, bufsz, " | ");
  3634. }
  3635. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  3636. {
  3637. #ifndef HAVE_CURSES
  3638. assert(for_curses == false);
  3639. #endif
  3640. struct device_drv *drv = cgpu->drv;
  3641. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  3642. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[max(ALLOC_H2B_SHORT, ALLOC_H2B_SPACED)+3+1];
  3643. char rejpcbuf[6];
  3644. char bnbuf[6];
  3645. double dev_runtime;
  3646. if (!opt_show_procs)
  3647. cgpu = cgpu->device;
  3648. dev_runtime = cgpu_runtime(cgpu);
  3649. double rolling, mhashes;
  3650. int accepted, rejected, stale;
  3651. double waccepted;
  3652. double wnotaccepted;
  3653. int hwerrs;
  3654. double bad_diff1, good_diff1;
  3655. rolling = mhashes = waccepted = wnotaccepted = 0;
  3656. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  3657. {
  3658. struct cgpu_info *slave = cgpu;
  3659. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  3660. {
  3661. slave->utility = slave->accepted / dev_runtime * 60;
  3662. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  3663. rolling += slave->rolling;
  3664. mhashes += slave->total_mhashes;
  3665. if (opt_weighed_stats)
  3666. {
  3667. accepted += slave->diff_accepted;
  3668. rejected += slave->diff_rejected;
  3669. stale += slave->diff_stale;
  3670. }
  3671. else
  3672. {
  3673. accepted += slave->accepted;
  3674. rejected += slave->rejected;
  3675. stale += slave->stale;
  3676. }
  3677. waccepted += slave->diff_accepted;
  3678. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  3679. hwerrs += slave->hw_errors;
  3680. bad_diff1 += slave->bad_diff1;
  3681. good_diff1 += slave->diff1;
  3682. if (opt_show_procs)
  3683. break;
  3684. }
  3685. }
  3686. double wtotal = (waccepted + wnotaccepted);
  3687. multi_format_unit_array2(
  3688. ((char*[]){cHr, aHr, uHr}),
  3689. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  3690. true, "h/s", hashrate_style,
  3691. 3,
  3692. 1e6*rolling,
  3693. 1e6*mhashes / dev_runtime,
  3694. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  3695. // Processor representation
  3696. #ifdef HAVE_CURSES
  3697. if (for_curses)
  3698. {
  3699. if (opt_show_procs)
  3700. snprintf(buf, bufsz, " %*s: ", -(5 + max_lpdigits), cgpu->proc_repr);
  3701. else
  3702. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  3703. }
  3704. else
  3705. #endif
  3706. snprintf(buf, bufsz, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  3707. if (include_serial_in_statline && cgpu->dev_serial)
  3708. tailsprintf(buf, bufsz, "[serial=%s] ", cgpu->dev_serial);
  3709. if (unlikely(cgpu->status == LIFE_INIT))
  3710. {
  3711. tailsprintf(buf, bufsz, "Initializing...");
  3712. return;
  3713. }
  3714. {
  3715. const size_t bufln = strlen(buf);
  3716. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3717. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3718. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3719. else
  3720. {
  3721. float temp = cgpu->temp;
  3722. if (!opt_show_procs)
  3723. {
  3724. // Find the highest temperature of all processors
  3725. struct cgpu_info *proc = cgpu;
  3726. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3727. if (proc->temp > temp)
  3728. temp = proc->temp;
  3729. }
  3730. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3731. }
  3732. }
  3733. #ifdef HAVE_CURSES
  3734. if (for_curses)
  3735. {
  3736. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3737. const char *cHrStats;
  3738. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3739. bool all_dead = true, all_off = true, all_rdrv = true;
  3740. struct cgpu_info *proc = cgpu;
  3741. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3742. {
  3743. switch (cHrStatsI) {
  3744. default:
  3745. if (proc->status == LIFE_WAIT)
  3746. cHrStatsI = 5;
  3747. case 5:
  3748. if (proc->deven == DEV_RECOVER_ERR)
  3749. cHrStatsI = 4;
  3750. case 4:
  3751. if (proc->deven == DEV_RECOVER)
  3752. cHrStatsI = 3;
  3753. case 3:
  3754. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3755. {
  3756. cHrStatsI = 1;
  3757. all_off = false;
  3758. }
  3759. else
  3760. {
  3761. if (likely(proc->deven == DEV_ENABLED))
  3762. all_off = false;
  3763. if (proc->deven != DEV_RECOVER_DRV)
  3764. all_rdrv = false;
  3765. }
  3766. case 1:
  3767. break;
  3768. }
  3769. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3770. all_dead = false;
  3771. if (opt_show_procs)
  3772. break;
  3773. }
  3774. if (unlikely(all_dead))
  3775. cHrStatsI = 0;
  3776. else
  3777. if (unlikely(all_off))
  3778. cHrStatsI = 2;
  3779. cHrStats = cHrStatsOpt[cHrStatsI];
  3780. if (cHrStatsI == 2 && all_rdrv)
  3781. cHrStats = " RST ";
  3782. format_statline(buf, bufsz,
  3783. cHrStats,
  3784. aHr, uHr,
  3785. accepted, rejected, stale,
  3786. wnotaccepted, waccepted,
  3787. hwerrs,
  3788. bad_diff1, bad_diff1 + good_diff1);
  3789. }
  3790. else
  3791. #endif
  3792. {
  3793. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3794. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3795. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3796. opt_log_interval,
  3797. cHr, aHr, uHr,
  3798. accepted,
  3799. rejected,
  3800. stale,
  3801. rejpcbuf,
  3802. hwerrs,
  3803. bnbuf
  3804. );
  3805. }
  3806. }
  3807. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3808. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3809. static void text_print_status(int thr_id)
  3810. {
  3811. struct cgpu_info *cgpu;
  3812. char logline[256];
  3813. cgpu = get_thr_cgpu(thr_id);
  3814. if (cgpu) {
  3815. get_statline(logline, sizeof(logline), cgpu);
  3816. printf("\n%s\r", logline);
  3817. fflush(stdout);
  3818. }
  3819. }
  3820. #ifdef HAVE_CURSES
  3821. static int attr_bad = A_BOLD;
  3822. #ifdef WIN32
  3823. #define swprintf snwprintf
  3824. #endif
  3825. static
  3826. void bfg_waddstr(WINDOW *win, const char *s)
  3827. {
  3828. const char *p = s;
  3829. int32_t w;
  3830. int wlen;
  3831. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3832. while (true)
  3833. {
  3834. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3835. {
  3836. // Printable ASCII
  3837. ++p;
  3838. }
  3839. if (p != s)
  3840. waddnstr(win, s, p - s);
  3841. w = utf8_decode(p, &wlen);
  3842. s = p += wlen;
  3843. switch(w)
  3844. {
  3845. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3846. case '\0':
  3847. return;
  3848. case 0xb5: // micro symbol
  3849. w = unicode_micro;
  3850. goto default_addch;
  3851. case 0xf000: // "bad" off
  3852. wattroff(win, attr_bad);
  3853. break;
  3854. case 0xf001: // "bad" on
  3855. wattron(win, attr_bad);
  3856. break;
  3857. #ifdef USE_UNICODE
  3858. case '|':
  3859. wadd_wch(win, WACS_VLINE);
  3860. break;
  3861. #endif
  3862. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3863. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3864. if (!use_unicode)
  3865. {
  3866. waddch(win, '-');
  3867. break;
  3868. }
  3869. #ifdef USE_UNICODE
  3870. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3871. break;
  3872. #endif
  3873. case 0x2022:
  3874. if (w > WCHAR_MAX || !iswprint(w))
  3875. w = '*';
  3876. default:
  3877. default_addch:
  3878. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3879. {
  3880. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3881. if (iswprint(REPLACEMENT_CHAR))
  3882. w = REPLACEMENT_CHAR;
  3883. else
  3884. #endif
  3885. w = '?';
  3886. }
  3887. {
  3888. #ifdef USE_UNICODE
  3889. wchar_t wbuf[0x10];
  3890. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3891. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3892. waddnwstr(win, wbuf, wbuflen);
  3893. #else
  3894. wprintw(win, "%lc", (wint_t)w);
  3895. #endif
  3896. }
  3897. }
  3898. }
  3899. }
  3900. static inline
  3901. void bfg_hline(WINDOW *win, int y)
  3902. {
  3903. int maxx, __maybe_unused maxy;
  3904. getmaxyx(win, maxy, maxx);
  3905. #ifdef USE_UNICODE
  3906. if (use_unicode)
  3907. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3908. else
  3909. #endif
  3910. mvwhline(win, y, 0, '-', maxx);
  3911. }
  3912. static
  3913. int bfg_win_linelen(WINDOW * const win)
  3914. {
  3915. int maxx;
  3916. int __maybe_unused y;
  3917. getmaxyx(win, y, maxx);
  3918. return maxx;
  3919. }
  3920. // Spaces until end of line, using current attributes (ie, not completely clear)
  3921. static
  3922. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3923. {
  3924. int x, maxx;
  3925. int __maybe_unused y;
  3926. getmaxyx(win, y, maxx);
  3927. getyx(win, y, x);
  3928. const int space_count = (maxx - x) - offset;
  3929. // Check for negative - terminal too narrow
  3930. if (space_count <= 0)
  3931. return;
  3932. char buf[space_count];
  3933. memset(buf, ' ', space_count);
  3934. waddnstr(win, buf, space_count);
  3935. }
  3936. static int menu_attr = A_REVERSE;
  3937. #define CURBUFSIZ 256
  3938. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3939. char tmp42[CURBUFSIZ]; \
  3940. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3941. wmove(win, y, x); \
  3942. bfg_waddstr(win, tmp42); \
  3943. } while (0)
  3944. #define cg_wprintw(win, fmt, ...) do { \
  3945. char tmp42[CURBUFSIZ]; \
  3946. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3947. bfg_waddstr(win, tmp42); \
  3948. } while (0)
  3949. static
  3950. void update_block_display_line(const int blky, struct mining_goal_info *goal)
  3951. {
  3952. struct blockchain_info * const blkchain = goal->blkchain;
  3953. struct block_info * const blkinfo = blkchain->currentblk;
  3954. double income;
  3955. char incomestr[ALLOC_H2B_SHORT+6+1];
  3956. if (blkinfo->height)
  3957. {
  3958. income = goal->diff_accepted * 3600 * blkchain->currentblk_subsidy / total_secs / goal->current_diff;
  3959. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  3960. }
  3961. else
  3962. strcpy(incomestr, "?");
  3963. int linelen = bfg_win_linelen(statuswin);
  3964. wmove(statuswin, blky, 0);
  3965. bfg_waddstr(statuswin, " Block");
  3966. if (!goal->is_default)
  3967. linelen -= strlen(goal->name) + 1;
  3968. linelen -= 6; // " Block"
  3969. if (blkinfo->height && blkinfo->height < 1000000)
  3970. {
  3971. cg_wprintw(statuswin, " #%6u", blkinfo->height);
  3972. linelen -= 8;
  3973. }
  3974. bfg_waddstr(statuswin, ":");
  3975. if (linelen > 55)
  3976. bfg_waddstr(statuswin, " ");
  3977. if (linelen >= 65)
  3978. bfg_waddstr(statuswin, "...");
  3979. {
  3980. char hexpbh[0x11];
  3981. if (!(blkinfo->height && blkinfo->height < 1000000))
  3982. {
  3983. bin2hex(hexpbh, &blkinfo->prevblkhash[4], 4);
  3984. bfg_waddstr(statuswin, hexpbh);
  3985. }
  3986. bin2hex(hexpbh, &blkinfo->prevblkhash[0], 4);
  3987. bfg_waddstr(statuswin, hexpbh);
  3988. }
  3989. if (linelen >= 55)
  3990. bfg_waddstr(statuswin, " ");
  3991. cg_wprintw(statuswin, " Diff:%s", goal->current_diff_str);
  3992. if (linelen >= 69)
  3993. bfg_waddstr(statuswin, " ");
  3994. cg_wprintw(statuswin, "(%s) ", goal->net_hashrate);
  3995. if (linelen >= 62)
  3996. {
  3997. if (linelen >= 69)
  3998. bfg_waddstr(statuswin, " ");
  3999. bfg_waddstr(statuswin, "Started:");
  4000. }
  4001. else
  4002. bfg_waddstr(statuswin, "S:");
  4003. if (linelen >= 69)
  4004. bfg_waddstr(statuswin, " ");
  4005. bfg_waddstr(statuswin, blkchain->currentblk_first_seen_time_str);
  4006. if (linelen >= 69)
  4007. bfg_waddstr(statuswin, " ");
  4008. cg_wprintw(statuswin, " I:%s", incomestr);
  4009. if (!goal->is_default)
  4010. cg_wprintw(statuswin, " %s", goal->name);
  4011. wclrtoeol(statuswin);
  4012. }
  4013. static bool pool_actively_in_use(const struct pool *, const struct pool *);
  4014. static
  4015. void update_block_display(void)
  4016. {
  4017. struct mining_goal_info *goal, *tmpgoal;
  4018. int blky = 3, i, total_found_goals = 0;
  4019. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  4020. {
  4021. for (i = 0; i < total_pools; ++i)
  4022. {
  4023. struct pool * const pool = pools[i];
  4024. if (pool->goal == goal && pool_actively_in_use(pool, NULL))
  4025. break;
  4026. }
  4027. if (i >= total_pools)
  4028. // no pools using this goal, so it's probably stale anyway
  4029. continue;
  4030. update_block_display_line(blky++, goal);
  4031. ++total_found_goals;
  4032. }
  4033. if (total_found_goals != active_goals)
  4034. {
  4035. active_goals = total_found_goals;
  4036. devcursor = 7 + active_goals;
  4037. switch_logsize();
  4038. }
  4039. }
  4040. static bool pool_unworkable(const struct pool *);
  4041. /* Must be called with curses mutex lock held and curses_active */
  4042. static void curses_print_status(const int ts)
  4043. {
  4044. struct pool *pool = currentpool;
  4045. struct timeval now, tv;
  4046. float efficiency;
  4047. int logdiv;
  4048. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  4049. wattron(statuswin, attr_title);
  4050. const int linelen = bfg_win_linelen(statuswin);
  4051. int titlelen = 1 + strlen(PACKAGE) + 1 + strlen(VERSION) + 3 + 21 + 3 + 19;
  4052. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " ");
  4053. if (titlelen + 17 < linelen)
  4054. cg_wprintw(statuswin, "version ");
  4055. cg_wprintw(statuswin, VERSION " - ");
  4056. if (titlelen + 9 < linelen)
  4057. cg_wprintw(statuswin, "Started: ");
  4058. else
  4059. if (titlelen + 7 <= linelen)
  4060. cg_wprintw(statuswin, "Start: ");
  4061. cg_wprintw(statuswin, "%s", datestamp);
  4062. timer_set_now(&now);
  4063. {
  4064. unsigned int days, hours;
  4065. div_t d;
  4066. timersub(&now, &miner_started, &tv);
  4067. d = div(tv.tv_sec, 86400);
  4068. days = d.quot;
  4069. d = div(d.rem, 3600);
  4070. hours = d.quot;
  4071. d = div(d.rem, 60);
  4072. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  4073. , days
  4074. , (days == 1) ? ' ' : 's'
  4075. , hours
  4076. , d.quot
  4077. , d.rem
  4078. );
  4079. }
  4080. bfg_wspctoeol(statuswin, 0);
  4081. wattroff(statuswin, attr_title);
  4082. wattron(statuswin, menu_attr);
  4083. wmove(statuswin, 1, 0);
  4084. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  4085. bfg_wspctoeol(statuswin, 14);
  4086. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  4087. wattroff(statuswin, menu_attr);
  4088. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && enabled_pools > 1) {
  4089. char poolinfo[20], poolinfo2[20];
  4090. int poolinfooff = 0, poolinfo2off, workable_pools = 0;
  4091. double lowdiff = DBL_MAX, highdiff = -1;
  4092. struct pool *lowdiff_pool = pools[0], *highdiff_pool = pools[0];
  4093. time_t oldest_work_restart = time(NULL) + 1;
  4094. struct pool *oldest_work_restart_pool = pools[0];
  4095. for (int i = 0; i < total_pools; ++i)
  4096. {
  4097. if (pool_unworkable(pools[i]))
  4098. continue;
  4099. // NOTE: Only set pool var when it's workable; if only one is, it gets used by single-pool code
  4100. pool = pools[i];
  4101. ++workable_pools;
  4102. if (poolinfooff < sizeof(poolinfo))
  4103. poolinfooff += snprintf(&poolinfo[poolinfooff], sizeof(poolinfo) - poolinfooff, "%u,", pool->pool_no);
  4104. struct cgminer_pool_stats * const pool_stats = &pool->cgminer_pool_stats;
  4105. if (pool_stats->last_diff < lowdiff)
  4106. {
  4107. lowdiff = pool_stats->last_diff;
  4108. lowdiff_pool = pool;
  4109. }
  4110. if (pool_stats->last_diff > highdiff)
  4111. {
  4112. highdiff = pool_stats->last_diff;
  4113. highdiff_pool = pool;
  4114. }
  4115. if (oldest_work_restart >= pool->work_restart_time)
  4116. {
  4117. oldest_work_restart = pool->work_restart_time;
  4118. oldest_work_restart_pool = pool;
  4119. }
  4120. }
  4121. if (unlikely(!workable_pools))
  4122. goto no_workable_pools;
  4123. if (workable_pools == 1)
  4124. goto one_workable_pool;
  4125. poolinfo2off = snprintf(poolinfo2, sizeof(poolinfo2), "%u (", workable_pools);
  4126. if (poolinfooff > sizeof(poolinfo2) - poolinfo2off - 1)
  4127. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s...)", (int)(sizeof(poolinfo2) - poolinfo2off - 5), poolinfo);
  4128. else
  4129. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s)%*s", (int)(poolinfooff - 1), poolinfo, (int)(sizeof(poolinfo2)), "");
  4130. cg_mvwprintw(statuswin, 2, 0, " Pools: %s Diff:%s%s%s %c LU:%s",
  4131. poolinfo2,
  4132. lowdiff_pool->diff,
  4133. (lowdiff == highdiff) ? "" : "-",
  4134. (lowdiff == highdiff) ? "" : highdiff_pool->diff,
  4135. pool->goal->have_longpoll ? '+' : '-',
  4136. oldest_work_restart_pool->work_restart_timestamp);
  4137. }
  4138. else
  4139. if (pool_unworkable(pool))
  4140. {
  4141. no_workable_pools: ;
  4142. wattron(statuswin, attr_bad);
  4143. cg_mvwprintw(statuswin, 2, 0, " (all pools are dead) ");
  4144. wattroff(statuswin, attr_bad);
  4145. }
  4146. else
  4147. {
  4148. one_workable_pool: ;
  4149. char pooladdr[19];
  4150. {
  4151. const char *rawaddr = pool->sockaddr_url;
  4152. BFGINIT(rawaddr, pool->rpc_url);
  4153. size_t pooladdrlen = strlen(rawaddr);
  4154. if (pooladdrlen > 20)
  4155. snprintf(pooladdr, sizeof(pooladdr), "...%s", &rawaddr[pooladdrlen - (sizeof(pooladdr) - 4)]);
  4156. else
  4157. snprintf(pooladdr, sizeof(pooladdr), "%*s", -(int)(sizeof(pooladdr) - 1), rawaddr);
  4158. }
  4159. cg_mvwprintw(statuswin, 2, 0, " Pool%2u: %s Diff:%s %c%s LU:%s User:%s",
  4160. pool->pool_no, pooladdr, pool->diff,
  4161. pool->goal->have_longpoll ? '+' : '-', pool_proto_str(pool),
  4162. pool->work_restart_timestamp,
  4163. pool->rpc_user);
  4164. }
  4165. wclrtoeol(statuswin);
  4166. char bwstr[(ALLOC_H2B_SHORT*2)+3+1];
  4167. cg_mvwprintw(statuswin, devcursor - 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f BS:%s",
  4168. ts,
  4169. total_go + total_ro,
  4170. new_blocks,
  4171. total_submitting,
  4172. multi_format_unit2(bwstr, sizeof(bwstr),
  4173. false, "B/s", H2B_SHORT, "/", 2,
  4174. (float)(total_bytes_rcvd / total_secs),
  4175. (float)(total_bytes_sent / total_secs)),
  4176. efficiency,
  4177. best_share);
  4178. wclrtoeol(statuswin);
  4179. mvwaddstr(statuswin, devcursor - 3, 0, " ");
  4180. bfg_waddstr(statuswin, statusline);
  4181. wclrtoeol(statuswin);
  4182. int devdiv = devcursor - 2;
  4183. logdiv = statusy - 1;
  4184. bfg_hline(statuswin, devdiv);
  4185. bfg_hline(statuswin, logdiv);
  4186. #ifdef USE_UNICODE
  4187. if (use_unicode)
  4188. {
  4189. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  4190. if (opt_show_procs && !opt_compact)
  4191. offset += max_lpdigits; // proc letter(s)
  4192. if (have_unicode_degrees)
  4193. ++offset; // degrees symbol
  4194. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4195. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4196. offset += 24; // hashrates etc
  4197. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4198. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4199. }
  4200. #endif
  4201. }
  4202. static void adj_width(int var, int *length)
  4203. {
  4204. if ((int)(log10(var) + 1) > *length)
  4205. (*length)++;
  4206. }
  4207. static int dev_width;
  4208. static void curses_print_devstatus(struct cgpu_info *cgpu)
  4209. {
  4210. char logline[256];
  4211. int ypos;
  4212. if (opt_compact)
  4213. return;
  4214. /* Check this isn't out of the window size */
  4215. if (opt_show_procs)
  4216. ypos = cgpu->cgminer_id;
  4217. else
  4218. {
  4219. if (cgpu->proc_id)
  4220. return;
  4221. ypos = cgpu->device_line_id;
  4222. }
  4223. ypos += devsummaryYOffset;
  4224. if (ypos < 0)
  4225. return;
  4226. ypos += devcursor - 1;
  4227. if (ypos >= statusy - 1)
  4228. return;
  4229. if (wmove(statuswin, ypos, 0) == ERR)
  4230. return;
  4231. get_statline2(logline, sizeof(logline), cgpu, true);
  4232. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  4233. wattron(statuswin, A_REVERSE);
  4234. bfg_waddstr(statuswin, logline);
  4235. wattroff(statuswin, A_REVERSE);
  4236. wclrtoeol(statuswin);
  4237. }
  4238. static
  4239. void _refresh_devstatus(const bool already_have_lock) {
  4240. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  4241. int i;
  4242. if (unlikely(!total_devices))
  4243. {
  4244. const int ypos = devcursor - 1;
  4245. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  4246. {
  4247. wattron(statuswin, attr_bad);
  4248. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  4249. wclrtoeol(statuswin);
  4250. wattroff(statuswin, attr_bad);
  4251. }
  4252. }
  4253. for (i = 0; i < total_devices; i++)
  4254. curses_print_devstatus(get_devices(i));
  4255. touchwin(statuswin);
  4256. wrefresh(statuswin);
  4257. if (!already_have_lock)
  4258. unlock_curses();
  4259. }
  4260. }
  4261. #define refresh_devstatus() _refresh_devstatus(false)
  4262. #endif
  4263. static void print_status(int thr_id)
  4264. {
  4265. if (!curses_active)
  4266. text_print_status(thr_id);
  4267. }
  4268. #ifdef HAVE_CURSES
  4269. static
  4270. bool set_statusy(int maxy)
  4271. {
  4272. if (loginput_size)
  4273. {
  4274. maxy -= loginput_size;
  4275. if (maxy < 0)
  4276. maxy = 0;
  4277. }
  4278. if (logstart < maxy)
  4279. maxy = logstart;
  4280. if (statusy == maxy)
  4281. return false;
  4282. statusy = maxy;
  4283. logcursor = statusy;
  4284. return true;
  4285. }
  4286. /* Check for window resize. Called with curses mutex locked */
  4287. static inline void change_logwinsize(void)
  4288. {
  4289. int x, y, logx, logy;
  4290. getmaxyx(mainwin, y, x);
  4291. if (x < 80 || y < 25)
  4292. return;
  4293. if (y > statusy + 2 && statusy < logstart) {
  4294. set_statusy(y - 2);
  4295. mvwin(logwin, logcursor, 0);
  4296. bfg_wresize(statuswin, statusy, x);
  4297. }
  4298. y -= logcursor;
  4299. getmaxyx(logwin, logy, logx);
  4300. /* Detect screen size change */
  4301. if (x != logx || y != logy)
  4302. bfg_wresize(logwin, y, x);
  4303. }
  4304. static void check_winsizes(void)
  4305. {
  4306. if (!use_curses)
  4307. return;
  4308. if (curses_active_locked()) {
  4309. int y, x;
  4310. x = getmaxx(statuswin);
  4311. if (set_statusy(LINES - 2))
  4312. {
  4313. erase();
  4314. bfg_wresize(statuswin, statusy, x);
  4315. getmaxyx(mainwin, y, x);
  4316. y -= logcursor;
  4317. bfg_wresize(logwin, y, x);
  4318. mvwin(logwin, logcursor, 0);
  4319. }
  4320. unlock_curses();
  4321. }
  4322. }
  4323. static int device_line_id_count;
  4324. static void switch_logsize(void)
  4325. {
  4326. if (curses_active_locked()) {
  4327. if (opt_compact) {
  4328. logstart = devcursor - 1;
  4329. logcursor = logstart + 1;
  4330. } else {
  4331. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  4332. logstart = devcursor + total_lines;
  4333. logcursor = logstart;
  4334. }
  4335. unlock_curses();
  4336. }
  4337. check_winsizes();
  4338. update_block_display();
  4339. }
  4340. /* For mandatory printing when mutex is already locked */
  4341. void _wlog(const char *str)
  4342. {
  4343. static bool newline;
  4344. size_t end = strlen(str) - 1;
  4345. if (newline)
  4346. bfg_waddstr(logwin, "\n");
  4347. if (str[end] == '\n')
  4348. {
  4349. char *s;
  4350. newline = true;
  4351. s = alloca(end + 1);
  4352. memcpy(s, str, end);
  4353. s[end] = '\0';
  4354. str = s;
  4355. }
  4356. else
  4357. newline = false;
  4358. bfg_waddstr(logwin, str);
  4359. }
  4360. /* Mandatory printing */
  4361. void _wlogprint(const char *str)
  4362. {
  4363. if (curses_active_locked()) {
  4364. _wlog(str);
  4365. unlock_curses();
  4366. }
  4367. }
  4368. #endif
  4369. #ifdef HAVE_CURSES
  4370. bool _log_curses_only(int prio, const char *datetime, const char *str)
  4371. {
  4372. bool high_prio;
  4373. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  4374. if (curses_active)
  4375. {
  4376. if (!loginput_size || high_prio) {
  4377. wlog(" %s %s\n", datetime, str);
  4378. if (high_prio) {
  4379. touchwin(logwin);
  4380. wrefresh(logwin);
  4381. }
  4382. }
  4383. return true;
  4384. }
  4385. return false;
  4386. }
  4387. void clear_logwin(void)
  4388. {
  4389. if (curses_active_locked()) {
  4390. wclear(logwin);
  4391. unlock_curses();
  4392. }
  4393. }
  4394. void logwin_update(void)
  4395. {
  4396. if (curses_active_locked()) {
  4397. touchwin(logwin);
  4398. wrefresh(logwin);
  4399. unlock_curses();
  4400. }
  4401. }
  4402. #endif
  4403. void enable_pool(struct pool * const pool)
  4404. {
  4405. if (pool->enabled != POOL_ENABLED) {
  4406. mutex_lock(&lp_lock);
  4407. enabled_pools++;
  4408. pool->enabled = POOL_ENABLED;
  4409. pthread_cond_broadcast(&lp_cond);
  4410. mutex_unlock(&lp_lock);
  4411. if (pool->prio < current_pool()->prio)
  4412. switch_pools(pool);
  4413. }
  4414. }
  4415. void disable_pool(struct pool * const pool, const enum pool_enable enable_status)
  4416. {
  4417. if (pool->enabled == POOL_DISABLED)
  4418. /* had been manually disabled before */
  4419. return;
  4420. if (pool->enabled != POOL_ENABLED)
  4421. {
  4422. /* has been programmatically disabled already, just change to the new status directly */
  4423. pool->enabled = enable_status;
  4424. return;
  4425. }
  4426. /* Fall into the lock area */
  4427. mutex_lock(&lp_lock);
  4428. --enabled_pools;
  4429. pool->enabled = enable_status;
  4430. mutex_unlock(&lp_lock);
  4431. if (pool == current_pool())
  4432. switch_pools(NULL);
  4433. }
  4434. static
  4435. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  4436. struct cgpu_info *cgpu;
  4437. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  4438. const unsigned char *hashpart = &work->hash[0x1c - malgo->ui_skip_hash_bytes];
  4439. char shrdiffdisp[ALLOC_H2B_SHORTV];
  4440. const double tgtdiff = work->work_difficulty;
  4441. char tgtdiffdisp[ALLOC_H2B_SHORTV];
  4442. char where[20];
  4443. cgpu = get_thr_cgpu(work->thr_id);
  4444. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  4445. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  4446. if (total_pools > 1)
  4447. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  4448. else
  4449. where[0] = '\0';
  4450. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  4451. disp,
  4452. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  4453. cgpu->proc_repr,
  4454. where,
  4455. shrdiffdisp, tgtdiffdisp,
  4456. reason,
  4457. resubmit ? "(resubmit)" : "",
  4458. worktime
  4459. );
  4460. }
  4461. static bool test_work_current(struct work *);
  4462. static void _submit_work_async(struct work *);
  4463. static
  4464. void maybe_local_submit(const struct work *work)
  4465. {
  4466. #if BLKMAKER_VERSION > 3
  4467. if (unlikely(work->block && work->tr))
  4468. {
  4469. // This is a block with a full template (GBT)
  4470. // Regardless of the result, submit to local bitcoind(s) as well
  4471. struct work *work_cp;
  4472. for (int i = 0; i < total_pools; ++i)
  4473. {
  4474. if (!uri_get_param_bool(pools[i]->rpc_url, "allblocks", false))
  4475. continue;
  4476. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  4477. work_cp = copy_work(work);
  4478. work_cp->pool = pools[i];
  4479. work_cp->do_foreign_submit = true;
  4480. _submit_work_async(work_cp);
  4481. }
  4482. }
  4483. #endif
  4484. }
  4485. static
  4486. json_t *extract_reject_reason_j(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4487. {
  4488. if (json_is_string(res))
  4489. return res;
  4490. if ( (res = json_object_get(val, "reject-reason")) )
  4491. return res;
  4492. if (work->stratum && err && json_is_array(err) && json_array_size(err) >= 2 && (res = json_array_get(err, 1)) && json_is_string(res))
  4493. return res;
  4494. return NULL;
  4495. }
  4496. static
  4497. const char *extract_reject_reason(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4498. {
  4499. json_t * const j = extract_reject_reason_j(val, res, err, work);
  4500. return j ? json_string_value(j) : NULL;
  4501. }
  4502. static
  4503. int put_in_parens(char * const buf, const size_t bufsz, const char * const s)
  4504. {
  4505. if (!s)
  4506. {
  4507. if (bufsz)
  4508. buf[0] = '\0';
  4509. return 0;
  4510. }
  4511. int p = snprintf(buf, bufsz, " (%s", s);
  4512. if (p >= bufsz - 1)
  4513. p = bufsz - 2;
  4514. strcpy(&buf[p], ")");
  4515. return p + 1;
  4516. }
  4517. /* Theoretically threads could race when modifying accepted and
  4518. * rejected values but the chance of two submits completing at the
  4519. * same time is zero so there is no point adding extra locking */
  4520. static void
  4521. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  4522. /*char *hashshow,*/ bool resubmit, char *worktime)
  4523. {
  4524. struct pool *pool = work->pool;
  4525. struct cgpu_info *cgpu;
  4526. cgpu = get_thr_cgpu(work->thr_id);
  4527. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  4528. struct mining_goal_info * const goal = pool->goal;
  4529. mutex_lock(&stats_lock);
  4530. cgpu->accepted++;
  4531. total_accepted++;
  4532. pool->accepted++;
  4533. cgpu->diff_accepted += work->work_difficulty;
  4534. total_diff_accepted += work->work_difficulty;
  4535. pool->diff_accepted += work->work_difficulty;
  4536. goal->diff_accepted += work->work_difficulty;
  4537. mutex_unlock(&stats_lock);
  4538. pool->seq_rejects = 0;
  4539. cgpu->last_share_pool = pool->pool_no;
  4540. cgpu->last_share_pool_time = time(NULL);
  4541. cgpu->last_share_diff = work->work_difficulty;
  4542. pool->last_share_time = cgpu->last_share_pool_time;
  4543. pool->last_share_diff = work->work_difficulty;
  4544. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  4545. if (!QUIET) {
  4546. share_result_msg(work, "Accepted", "", resubmit, worktime);
  4547. }
  4548. sharelog("accept", work);
  4549. if (opt_shares && total_diff_accepted >= opt_shares) {
  4550. applog(LOG_WARNING, "Successfully mined %g accepted shares as requested and exiting.", opt_shares);
  4551. kill_work();
  4552. return;
  4553. }
  4554. /* Detect if a pool that has been temporarily disabled for
  4555. * continually rejecting shares has started accepting shares.
  4556. * This will only happen with the work returned from a
  4557. * longpoll */
  4558. if (unlikely(pool->enabled == POOL_REJECTING)) {
  4559. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  4560. enable_pool(pool);
  4561. }
  4562. if (unlikely(work->block)) {
  4563. // Force moving on to this new block :)
  4564. struct work fakework;
  4565. memset(&fakework, 0, sizeof(fakework));
  4566. fakework.pool = work->pool;
  4567. // Copy block version, bits, and time from share
  4568. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  4569. memcpy(&fakework.data[68], &work->data[68], 8);
  4570. // Set prevblock to winning hash (swap32'd)
  4571. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  4572. test_work_current(&fakework);
  4573. }
  4574. }
  4575. else
  4576. if (!hash_target_check(work->hash, work->target))
  4577. {
  4578. // This was submitted despite failing the proper target
  4579. // Quietly ignore the reject
  4580. char reason[32];
  4581. put_in_parens(reason, sizeof(reason), extract_reject_reason(val, res, err, work));
  4582. applog(LOG_DEBUG, "Share above target rejected%s by pool %u as expected, ignoring", reason, pool->pool_no);
  4583. } else {
  4584. mutex_lock(&stats_lock);
  4585. cgpu->rejected++;
  4586. total_rejected++;
  4587. pool->rejected++;
  4588. cgpu->diff_rejected += work->work_difficulty;
  4589. total_diff_rejected += work->work_difficulty;
  4590. pool->diff_rejected += work->work_difficulty;
  4591. pool->seq_rejects++;
  4592. mutex_unlock(&stats_lock);
  4593. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  4594. if (!QUIET) {
  4595. char disposition[36] = "reject";
  4596. char reason[32];
  4597. const char *reasontmp = extract_reject_reason(val, res, err, work);
  4598. int n = put_in_parens(reason, sizeof(reason), reasontmp);
  4599. if (reason[0])
  4600. snprintf(&disposition[6], sizeof(disposition) - 6, ":%.*s", n - 3, &reason[2]);
  4601. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  4602. sharelog(disposition, work);
  4603. }
  4604. /* Once we have more than a nominal amount of sequential rejects,
  4605. * at least 10 and more than 3 mins at the current utility,
  4606. * disable the pool because some pool error is likely to have
  4607. * ensued. Do not do this if we know the share just happened to
  4608. * be stale due to networking delays.
  4609. */
  4610. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  4611. double utility = total_accepted / total_secs * 60;
  4612. if (pool->seq_rejects > utility * 3) {
  4613. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  4614. pool->pool_no, pool->seq_rejects);
  4615. disable_pool(pool, POOL_REJECTING);
  4616. pool->seq_rejects = 0;
  4617. }
  4618. }
  4619. }
  4620. maybe_local_submit(work);
  4621. }
  4622. static char *submit_upstream_work_request(struct work *work)
  4623. {
  4624. char *hexstr = NULL;
  4625. char *s, *sd;
  4626. struct pool *pool = work->pool;
  4627. if (work->tr)
  4628. {
  4629. blktemplate_t * const tmpl = work->tr->tmpl;
  4630. json_t *req;
  4631. unsigned char data[80];
  4632. swap32yes(data, work->data, 80 / 4);
  4633. #if BLKMAKER_VERSION > 3
  4634. if (work->do_foreign_submit)
  4635. req = blkmk_submit_foreign_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4636. else
  4637. #endif
  4638. req = blkmk_submit_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4639. s = json_dumps(req, 0);
  4640. json_decref(req);
  4641. sd = malloc(161);
  4642. bin2hex(sd, data, 80);
  4643. } else {
  4644. /* build hex string */
  4645. hexstr = malloc((sizeof(work->data) * 2) + 1);
  4646. bin2hex(hexstr, work->data, sizeof(work->data));
  4647. /* build JSON-RPC request */
  4648. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  4649. s = realloc_strcat(s, hexstr);
  4650. s = realloc_strcat(s, "\" ], \"id\":1}");
  4651. free(hexstr);
  4652. sd = s;
  4653. }
  4654. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  4655. if (work->tr)
  4656. free(sd);
  4657. else
  4658. s = realloc_strcat(s, "\n");
  4659. return s;
  4660. }
  4661. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  4662. json_t *res, *err;
  4663. bool rc = false;
  4664. int thr_id = work->thr_id;
  4665. struct pool *pool = work->pool;
  4666. struct timeval tv_submit_reply;
  4667. time_t ts_submit_reply;
  4668. char worktime[200] = "";
  4669. cgtime(&tv_submit_reply);
  4670. ts_submit_reply = time(NULL);
  4671. if (unlikely(!val)) {
  4672. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  4673. if (!pool_tset(pool, &pool->submit_fail)) {
  4674. total_ro++;
  4675. pool->remotefail_occasions++;
  4676. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  4677. }
  4678. goto out;
  4679. } else if (pool_tclear(pool, &pool->submit_fail))
  4680. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4681. res = json_object_get(val, "result");
  4682. err = json_object_get(val, "error");
  4683. if (!QUIET) {
  4684. if (opt_worktime) {
  4685. char workclone[20];
  4686. struct tm _tm;
  4687. struct tm *tm, tm_getwork, tm_submit_reply;
  4688. tm = &_tm;
  4689. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  4690. (struct timeval *)&(work->tv_getwork));
  4691. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  4692. (struct timeval *)&(work->tv_getwork_reply));
  4693. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  4694. (struct timeval *)&(work->tv_work_start));
  4695. double work_to_submit = tdiff(ptv_submit,
  4696. (struct timeval *)&(work->tv_work_found));
  4697. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  4698. int diffplaces = 3;
  4699. localtime_r(&work->ts_getwork, tm);
  4700. memcpy(&tm_getwork, tm, sizeof(struct tm));
  4701. localtime_r(&ts_submit_reply, tm);
  4702. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  4703. if (work->clone) {
  4704. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  4705. tdiff((struct timeval *)&(work->tv_cloned),
  4706. (struct timeval *)&(work->tv_getwork_reply)));
  4707. }
  4708. else
  4709. strcpy(workclone, "O");
  4710. if (work->work_difficulty < 1)
  4711. diffplaces = 6;
  4712. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  4713. const uint8_t * const prevblkhash = &work->data[4];
  4714. snprintf(worktime, sizeof(worktime),
  4715. " <-%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",
  4716. (unsigned long)be32toh(((uint32_t *)prevblkhash)[7 - malgo->worktime_skip_prevblk_u32]),
  4717. (unsigned long)be32toh(((uint32_t *)prevblkhash)[6 - malgo->worktime_skip_prevblk_u32]),
  4718. work->getwork_mode, diffplaces, work->work_difficulty,
  4719. tm_getwork.tm_hour, tm_getwork.tm_min,
  4720. tm_getwork.tm_sec, getwork_time, workclone,
  4721. getwork_to_work, work_time, work_to_submit, submit_time,
  4722. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  4723. tm_submit_reply.tm_sec);
  4724. }
  4725. }
  4726. share_result(val, res, err, work, resubmit, worktime);
  4727. if (!opt_realquiet)
  4728. print_status(thr_id);
  4729. if (!want_per_device_stats) {
  4730. char logline[256];
  4731. struct cgpu_info *cgpu;
  4732. cgpu = get_thr_cgpu(thr_id);
  4733. get_statline(logline, sizeof(logline), cgpu);
  4734. applog(LOG_INFO, "%s", logline);
  4735. }
  4736. json_decref(val);
  4737. rc = true;
  4738. out:
  4739. return rc;
  4740. }
  4741. /* Specifies whether we can use this pool for work or not. */
  4742. static bool pool_unworkable(const struct pool * const pool)
  4743. {
  4744. if (pool->idle)
  4745. return true;
  4746. if (pool->enabled != POOL_ENABLED)
  4747. return true;
  4748. if (pool->has_stratum && !pool->stratum_active)
  4749. return true;
  4750. return false;
  4751. }
  4752. static
  4753. bool pool_actively_desired(const struct pool * const pool, const struct pool *cp)
  4754. {
  4755. if (pool->enabled != POOL_ENABLED)
  4756. return false;
  4757. if (pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE)
  4758. return true;
  4759. if (!cp)
  4760. cp = current_pool();
  4761. return (pool == cp);
  4762. }
  4763. static
  4764. bool pool_actively_in_use(const struct pool * const pool, const struct pool *cp)
  4765. {
  4766. return (!pool_unworkable(pool)) && pool_actively_desired(pool, cp);
  4767. }
  4768. static
  4769. bool pool_supports_block_change_notification(struct pool * const pool)
  4770. {
  4771. return pool->has_stratum || pool->lp_url;
  4772. }
  4773. static
  4774. bool pool_has_active_block_change_notification(struct pool * const pool)
  4775. {
  4776. return pool->stratum_active || pool->lp_active;
  4777. }
  4778. static struct pool *_select_longpoll_pool(struct pool *, bool(*)(struct pool *));
  4779. #define select_longpoll_pool(pool) _select_longpoll_pool(pool, pool_supports_block_change_notification)
  4780. #define pool_active_lp_pool(pool) _select_longpoll_pool(pool, pool_has_active_block_change_notification)
  4781. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  4782. * rolling average per 10 minutes and if pools start getting more, it biases
  4783. * away from them to distribute work evenly. The share count is reset to the
  4784. * rolling average every 10 minutes to not send all work to one pool after it
  4785. * has been disabled/out for an extended period. */
  4786. static
  4787. struct pool *select_balanced(struct pool *cp, struct mining_algorithm * const malgo)
  4788. {
  4789. int i, lowest = cp->shares;
  4790. struct pool *ret = cp, *failover_pool = NULL;
  4791. for (i = 0; i < total_pools; i++) {
  4792. struct pool *pool = pools[i];
  4793. if (malgo && pool->goal->malgo != malgo)
  4794. continue;
  4795. if (pool_unworkable(pool))
  4796. continue;
  4797. if (pool->failover_only)
  4798. {
  4799. BFGINIT(failover_pool, pool);
  4800. continue;
  4801. }
  4802. if (pool->shares < lowest) {
  4803. lowest = pool->shares;
  4804. ret = pool;
  4805. }
  4806. }
  4807. if (malgo && ret->goal->malgo != malgo)
  4808. // Yes, we want failover_pool even if it's NULL
  4809. ret = failover_pool;
  4810. else
  4811. if (pool_unworkable(ret) && failover_pool)
  4812. ret = failover_pool;
  4813. if (ret)
  4814. ++ret->shares;
  4815. return ret;
  4816. }
  4817. static struct pool *priority_pool(int choice);
  4818. static
  4819. struct pool *select_loadbalance(struct mining_algorithm * const malgo)
  4820. {
  4821. static int rotating_pool = 0;
  4822. struct pool *pool;
  4823. bool avail = false;
  4824. int tested, i, rpsave;
  4825. for (i = 0; i < total_pools; i++) {
  4826. struct pool *tp = pools[i];
  4827. if (tp->quota_used < tp->quota_gcd) {
  4828. avail = true;
  4829. break;
  4830. }
  4831. }
  4832. /* There are no pools with quota, so reset them. */
  4833. if (!avail) {
  4834. for (i = 0; i < total_pools; i++)
  4835. {
  4836. struct pool * const tp = pools[i];
  4837. tp->quota_used -= tp->quota_gcd;
  4838. }
  4839. if (++rotating_pool >= total_pools)
  4840. rotating_pool = 0;
  4841. }
  4842. /* Try to find the first pool in the rotation that is usable */
  4843. // Look for the lowest integer quota_used / quota_gcd in case we are imbalanced by algorithm demands
  4844. struct pool *pool_lowest = NULL;
  4845. int lowest = INT_MAX;
  4846. rpsave = rotating_pool;
  4847. for (tested = 0; tested < total_pools; ++tested)
  4848. {
  4849. pool = pools[rotating_pool];
  4850. if (malgo && pool->goal->malgo != malgo)
  4851. goto continue_tested;
  4852. if (pool->quota_used < pool->quota_gcd)
  4853. {
  4854. ++pool->quota_used;
  4855. if (!pool_unworkable(pool))
  4856. goto out;
  4857. /* Failover-only flag for load-balance means distribute
  4858. * unused quota to priority pool 0. */
  4859. if (opt_fail_only)
  4860. priority_pool(0)->quota_used--;
  4861. }
  4862. if (malgo)
  4863. {
  4864. const int count = pool->quota_used / pool->quota_gcd;
  4865. if (count < lowest)
  4866. {
  4867. pool_lowest = pool;
  4868. lowest = count;
  4869. }
  4870. }
  4871. continue_tested: ;
  4872. if (++rotating_pool >= total_pools)
  4873. rotating_pool = 0;
  4874. }
  4875. // Even if pool_lowest is NULL, we want to return that to indicate failure
  4876. // Note it isn't possible to get here if !malgo
  4877. pool = pool_lowest;
  4878. out: ;
  4879. // Restore rotating_pool static, so malgo searches don't affect the usual load balancing
  4880. if (malgo)
  4881. rotating_pool = rpsave;
  4882. return pool;
  4883. }
  4884. static bool pool_unusable(struct pool *pool);
  4885. static
  4886. struct pool *select_failover(struct mining_algorithm * const malgo)
  4887. {
  4888. int i;
  4889. for (i = 0; i < total_pools; i++) {
  4890. struct pool *tp = priority_pool(i);
  4891. if (malgo && tp->goal->malgo != malgo)
  4892. continue;
  4893. if (!pool_unusable(tp)) {
  4894. return tp;
  4895. }
  4896. }
  4897. return NULL;
  4898. }
  4899. static bool pool_active(struct pool *, bool pinging);
  4900. static void pool_died(struct pool *);
  4901. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  4902. * it has any quota left. */
  4903. static inline struct pool *select_pool(bool lagging, struct mining_algorithm * const malgo)
  4904. {
  4905. struct pool *pool = NULL, *cp;
  4906. retry:
  4907. cp = current_pool();
  4908. if (pool_strategy == POOL_BALANCE) {
  4909. pool = select_balanced(cp, malgo);
  4910. if ((!pool) || pool_unworkable(pool))
  4911. goto simple_failover;
  4912. goto out;
  4913. }
  4914. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  4915. if (malgo && cp->goal->malgo != malgo)
  4916. goto simple_failover;
  4917. pool = cp;
  4918. goto out;
  4919. } else
  4920. pool = select_loadbalance(malgo);
  4921. simple_failover:
  4922. /* If there are no alive pools with quota, choose according to
  4923. * priority. */
  4924. if (!pool) {
  4925. pool = select_failover(malgo);
  4926. }
  4927. /* If still nothing is usable, use the current pool */
  4928. if (!pool)
  4929. {
  4930. if (malgo && cp->goal->malgo != malgo)
  4931. {
  4932. applog(LOG_DEBUG, "Failed to select pool for specific mining algorithm");
  4933. return NULL;
  4934. }
  4935. pool = cp;
  4936. }
  4937. out:
  4938. if (!pool_actively_in_use(pool, cp))
  4939. {
  4940. if (!pool_active(pool, false))
  4941. {
  4942. pool_died(pool);
  4943. goto retry;
  4944. }
  4945. pool_tclear(pool, &pool->idle);
  4946. }
  4947. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  4948. return pool;
  4949. }
  4950. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  4951. double target_diff(const unsigned char *target)
  4952. {
  4953. double targ = 0;
  4954. signed int i;
  4955. for (i = 31; i >= 0; --i)
  4956. targ = (targ * 0x100) + target[i];
  4957. return DIFFEXACTONE / (targ ?: 1);
  4958. }
  4959. /*
  4960. * Calculate the work share difficulty
  4961. */
  4962. static void calc_diff(struct work *work, int known)
  4963. {
  4964. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  4965. double difficulty;
  4966. if (!known) {
  4967. work->work_difficulty = target_diff(work->target);
  4968. } else
  4969. work->work_difficulty = known;
  4970. difficulty = work->work_difficulty;
  4971. pool_stats->last_diff = difficulty;
  4972. suffix_string(difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  4973. if (difficulty == pool_stats->min_diff)
  4974. pool_stats->min_diff_count++;
  4975. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  4976. pool_stats->min_diff = difficulty;
  4977. pool_stats->min_diff_count = 1;
  4978. }
  4979. if (difficulty == pool_stats->max_diff)
  4980. pool_stats->max_diff_count++;
  4981. else if (difficulty > pool_stats->max_diff) {
  4982. pool_stats->max_diff = difficulty;
  4983. pool_stats->max_diff_count = 1;
  4984. }
  4985. }
  4986. static void gen_stratum_work(struct pool *, struct work *);
  4987. static void pool_update_work_restart_time(struct pool *);
  4988. static void restart_threads(void);
  4989. static uint32_t benchmark_blkhdr[20];
  4990. static const int benchmark_update_interval = 1;
  4991. static
  4992. void *benchmark_intense_work_update_thread(void *userp)
  4993. {
  4994. pthread_detach(pthread_self());
  4995. RenameThread("benchmark-intense");
  4996. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4997. struct pool * const pool = userp;
  4998. struct stratum_work * const swork = &pool->swork;
  4999. uint8_t * const blkhdr = swork->header1;
  5000. while (true)
  5001. {
  5002. sleep(benchmark_update_interval);
  5003. cg_wlock(&pool->data_lock);
  5004. for (int i = 36; --i >= 0; )
  5005. if (++blkhdr[i])
  5006. break;
  5007. cg_wunlock(&pool->data_lock);
  5008. struct work *work = make_work();
  5009. gen_stratum_work(pool, work);
  5010. pool->swork.work_restart_id = ++pool->work_restart_id;
  5011. pool_update_work_restart_time(pool);
  5012. test_work_current(work);
  5013. free_work(work);
  5014. restart_threads();
  5015. }
  5016. return NULL;
  5017. }
  5018. static
  5019. void setup_benchmark_pool()
  5020. {
  5021. struct pool *pool;
  5022. want_longpoll = false;
  5023. // Temporarily disable opt_benchmark to avoid auto-removal
  5024. opt_benchmark = false;
  5025. pool = add_pool();
  5026. opt_benchmark = true;
  5027. pool->rpc_url = malloc(255);
  5028. strcpy(pool->rpc_url, "Benchmark");
  5029. pool_set_uri(pool, pool->rpc_url);
  5030. pool->rpc_user = pool->rpc_url;
  5031. pool->rpc_pass = pool->rpc_url;
  5032. enable_pool(pool);
  5033. pool->idle = false;
  5034. successful_connect = true;
  5035. {
  5036. uint32_t * const blkhdr = benchmark_blkhdr;
  5037. blkhdr[2] = htobe32(1);
  5038. blkhdr[17] = htobe32(0x7fffffff); // timestamp
  5039. blkhdr[18] = htobe32(0x1700ffff); // "bits"
  5040. }
  5041. {
  5042. struct stratum_work * const swork = &pool->swork;
  5043. const int branchcount = 15; // 1 MB block
  5044. const size_t branchdatasz = branchcount * 0x20;
  5045. const size_t coinbase_sz = (opt_benchmark_intense ? 250 : 6) * 1024;
  5046. bytes_resize(&swork->coinbase, coinbase_sz);
  5047. memset(bytes_buf(&swork->coinbase), '\xff', coinbase_sz);
  5048. swork->nonce2_offset = 0;
  5049. bytes_resize(&swork->merkle_bin, branchdatasz);
  5050. memset(bytes_buf(&swork->merkle_bin), '\xff', branchdatasz);
  5051. swork->merkles = branchcount;
  5052. swork->header1[0] = '\xff';
  5053. memset(&swork->header1[1], '\0', 34);
  5054. swork->header1[35] = '\x01';
  5055. swork->ntime = 0x7fffffff;
  5056. timer_unset(&swork->tv_received);
  5057. memcpy(swork->diffbits, "\x17\0\xff\xff", 4);
  5058. const struct mining_goal_info * const goal = get_mining_goal("default");
  5059. const struct mining_algorithm * const malgo = goal->malgo;
  5060. set_target_to_pdiff(swork->target, malgo->reasonable_low_nonce_diff);
  5061. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  5062. pool->nonce2 = 0;
  5063. }
  5064. if (opt_benchmark_intense)
  5065. {
  5066. pthread_t pth;
  5067. if (unlikely(pthread_create(&pth, NULL, benchmark_intense_work_update_thread, pool)))
  5068. applog(LOG_WARNING, "Failed to start benchmark intense work update thread");
  5069. }
  5070. }
  5071. void get_benchmark_work(struct work *work, bool use_swork)
  5072. {
  5073. if (use_swork)
  5074. {
  5075. struct timeval tv_now;
  5076. timer_set_now(&tv_now);
  5077. gen_stratum_work(pools[0], work);
  5078. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  5079. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  5080. return;
  5081. }
  5082. struct pool * const pool = pools[0];
  5083. uint32_t * const blkhdr = benchmark_blkhdr;
  5084. for (int i = 16; i >= 0; --i)
  5085. if (++blkhdr[i])
  5086. break;
  5087. memcpy(&work->data[ 0], blkhdr, 80);
  5088. memcpy(&work->data[80], workpadding_bin, 48);
  5089. char hex[161];
  5090. bin2hex(hex, work->data, 80);
  5091. applog(LOG_DEBUG, "Generated benchmark header %s", hex);
  5092. calc_midstate(work);
  5093. memcpy(work->target, pool->swork.target, sizeof(work->target));
  5094. work->mandatory = true;
  5095. work->pool = pools[0];
  5096. cgtime(&work->tv_getwork);
  5097. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  5098. copy_time(&work->tv_staged, &work->tv_getwork);
  5099. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  5100. calc_diff(work, 0);
  5101. work_set_simple_ntime_roll_limit(work, 60, &work->tv_getwork);
  5102. }
  5103. static void wake_gws(void);
  5104. static void update_last_work(struct work *work)
  5105. {
  5106. if (!work->tr)
  5107. // Only save GBT jobs, since rollntime isn't coordinated well yet
  5108. return;
  5109. struct pool *pool = work->pool;
  5110. mutex_lock(&pool->last_work_lock);
  5111. if (pool->last_work_copy)
  5112. free_work(pool->last_work_copy);
  5113. pool->last_work_copy = copy_work(work);
  5114. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  5115. mutex_unlock(&pool->last_work_lock);
  5116. }
  5117. static
  5118. void gbt_req_target(json_t *req)
  5119. {
  5120. json_t *j;
  5121. json_t *n;
  5122. if (!request_target_str)
  5123. return;
  5124. j = json_object_get(req, "params");
  5125. if (!j)
  5126. {
  5127. n = json_array();
  5128. if (!n)
  5129. return;
  5130. if (json_object_set_new(req, "params", n))
  5131. goto erradd;
  5132. j = n;
  5133. }
  5134. n = json_array_get(j, 0);
  5135. if (!n)
  5136. {
  5137. n = json_object();
  5138. if (!n)
  5139. return;
  5140. if (json_array_append_new(j, n))
  5141. goto erradd;
  5142. }
  5143. j = n;
  5144. n = json_string(request_target_str);
  5145. if (!n)
  5146. return;
  5147. if (json_object_set_new(j, "target", n))
  5148. goto erradd;
  5149. return;
  5150. erradd:
  5151. json_decref(n);
  5152. }
  5153. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe, struct pool * const pool)
  5154. {
  5155. char *rpc_req;
  5156. clean_work(work);
  5157. switch (proto) {
  5158. case PLP_GETWORK:
  5159. work->getwork_mode = GETWORK_MODE_POOL;
  5160. return strdup(getwork_req);
  5161. case PLP_GETBLOCKTEMPLATE:
  5162. work->getwork_mode = GETWORK_MODE_GBT;
  5163. blktemplate_t * const tmpl = blktmpl_create();
  5164. if (!tmpl)
  5165. goto gbtfail2;
  5166. work->tr = tmpl_makeref(tmpl);
  5167. gbt_capabilities_t caps = blktmpl_addcaps(tmpl);
  5168. if (!caps)
  5169. goto gbtfail;
  5170. caps |= GBT_LONGPOLL;
  5171. #if BLKMAKER_VERSION > 1
  5172. const struct mining_goal_info * const goal = pool->goal;
  5173. if (goal->generation_script || goal_has_at_least_one_getcbaddr(goal))
  5174. caps |= GBT_CBVALUE;
  5175. #endif
  5176. json_t *req = blktmpl_request_jansson(caps, lpid);
  5177. if (!req)
  5178. goto gbtfail;
  5179. if (probe)
  5180. gbt_req_target(req);
  5181. rpc_req = json_dumps(req, 0);
  5182. if (!rpc_req)
  5183. goto gbtfail;
  5184. json_decref(req);
  5185. return rpc_req;
  5186. default:
  5187. return NULL;
  5188. }
  5189. return NULL;
  5190. gbtfail:
  5191. tmpl_decref(work->tr);
  5192. work->tr = NULL;
  5193. gbtfail2:
  5194. return NULL;
  5195. }
  5196. #define prepare_rpc_req(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, false, pool)
  5197. #define prepare_rpc_req_probe(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, true, pool)
  5198. static const char *pool_protocol_name(enum pool_protocol proto)
  5199. {
  5200. switch (proto) {
  5201. case PLP_GETBLOCKTEMPLATE:
  5202. return "getblocktemplate";
  5203. case PLP_GETWORK:
  5204. return "getwork";
  5205. default:
  5206. return "UNKNOWN";
  5207. }
  5208. }
  5209. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  5210. {
  5211. switch (proto) {
  5212. case PLP_GETBLOCKTEMPLATE:
  5213. if (want_getwork)
  5214. return PLP_GETWORK;
  5215. default:
  5216. return PLP_NONE;
  5217. }
  5218. }
  5219. static bool get_upstream_work(struct work *work, CURL *curl)
  5220. {
  5221. struct pool *pool = work->pool;
  5222. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  5223. struct timeval tv_elapsed;
  5224. json_t *val = NULL;
  5225. bool rc = false;
  5226. char *url;
  5227. enum pool_protocol proto;
  5228. char *rpc_req;
  5229. if (pool->proto == PLP_NONE)
  5230. pool->proto = PLP_GETBLOCKTEMPLATE;
  5231. tryagain:
  5232. rpc_req = prepare_rpc_req(work, pool->proto, NULL, pool);
  5233. work->pool = pool;
  5234. if (!rpc_req)
  5235. return false;
  5236. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  5237. url = pool->rpc_url;
  5238. cgtime(&work->tv_getwork);
  5239. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  5240. false, &work->rolltime, pool, false);
  5241. pool_stats->getwork_attempts++;
  5242. free(rpc_req);
  5243. if (likely(val)) {
  5244. rc = work_decode(pool, work, val);
  5245. if (unlikely(!rc))
  5246. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  5247. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  5248. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  5249. pool->proto = proto;
  5250. goto tryagain;
  5251. } else
  5252. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  5253. cgtime(&work->tv_getwork_reply);
  5254. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  5255. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  5256. pool_stats->getwork_wait_rolling /= 1.63;
  5257. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  5258. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  5259. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  5260. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  5261. }
  5262. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  5263. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  5264. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  5265. }
  5266. pool_stats->getwork_calls++;
  5267. work->pool = pool;
  5268. work->longpoll = false;
  5269. calc_diff(work, 0);
  5270. total_getworks++;
  5271. pool->getwork_requested++;
  5272. if (rc)
  5273. update_last_work(work);
  5274. if (likely(val))
  5275. json_decref(val);
  5276. return rc;
  5277. }
  5278. #ifdef HAVE_CURSES
  5279. static void disable_curses(void)
  5280. {
  5281. if (curses_active_locked()) {
  5282. use_curses = false;
  5283. curses_active = false;
  5284. leaveok(logwin, false);
  5285. leaveok(statuswin, false);
  5286. leaveok(mainwin, false);
  5287. nocbreak();
  5288. echo();
  5289. delwin(logwin);
  5290. delwin(statuswin);
  5291. delwin(mainwin);
  5292. endwin();
  5293. #ifdef WIN32
  5294. // Move the cursor to after curses output.
  5295. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  5296. CONSOLE_SCREEN_BUFFER_INFO csbi;
  5297. COORD coord;
  5298. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  5299. coord.X = 0;
  5300. coord.Y = csbi.dwSize.Y - 1;
  5301. SetConsoleCursorPosition(hout, coord);
  5302. }
  5303. #endif
  5304. unlock_curses();
  5305. }
  5306. }
  5307. #endif
  5308. static void __kill_work(void)
  5309. {
  5310. struct cgpu_info *cgpu;
  5311. struct thr_info *thr;
  5312. int i;
  5313. if (!successful_connect)
  5314. return;
  5315. applog(LOG_INFO, "Received kill message");
  5316. shutting_down = true;
  5317. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  5318. notifier_wake(submit_waiting_notifier);
  5319. #ifdef USE_LIBMICROHTTPD
  5320. httpsrv_stop();
  5321. #endif
  5322. applog(LOG_DEBUG, "Killing off watchpool thread");
  5323. /* Kill the watchpool thread */
  5324. thr = &control_thr[watchpool_thr_id];
  5325. thr_info_cancel(thr);
  5326. applog(LOG_DEBUG, "Killing off watchdog thread");
  5327. /* Kill the watchdog thread */
  5328. thr = &control_thr[watchdog_thr_id];
  5329. thr_info_cancel(thr);
  5330. applog(LOG_DEBUG, "Shutting down mining threads");
  5331. for (i = 0; i < mining_threads; i++) {
  5332. thr = get_thread(i);
  5333. if (!thr)
  5334. continue;
  5335. cgpu = thr->cgpu;
  5336. if (!cgpu)
  5337. continue;
  5338. if (!cgpu->threads)
  5339. continue;
  5340. cgpu->shutdown = true;
  5341. thr->work_restart = true;
  5342. notifier_wake(thr->notifier);
  5343. notifier_wake(thr->work_restart_notifier);
  5344. }
  5345. sleep(1);
  5346. applog(LOG_DEBUG, "Killing off mining threads");
  5347. /* Kill the mining threads*/
  5348. for (i = 0; i < mining_threads; i++) {
  5349. thr = get_thread(i);
  5350. if (!thr)
  5351. continue;
  5352. cgpu = thr->cgpu;
  5353. if (cgpu->threads)
  5354. {
  5355. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  5356. thr_info_cancel(thr);
  5357. }
  5358. cgpu->status = LIFE_DEAD2;
  5359. }
  5360. /* Stop the others */
  5361. applog(LOG_DEBUG, "Killing off API thread");
  5362. thr = &control_thr[api_thr_id];
  5363. thr_info_cancel(thr);
  5364. }
  5365. /* This should be the common exit path */
  5366. void kill_work(void)
  5367. {
  5368. __kill_work();
  5369. quit(0, "Shutdown signal received.");
  5370. }
  5371. static
  5372. #ifdef WIN32
  5373. #ifndef _WIN64
  5374. const
  5375. #endif
  5376. #endif
  5377. char **initial_args;
  5378. void _bfg_clean_up(bool);
  5379. void app_restart(void)
  5380. {
  5381. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  5382. __kill_work();
  5383. _bfg_clean_up(true);
  5384. #if defined(unix) || defined(__APPLE__)
  5385. if (forkpid > 0) {
  5386. kill(forkpid, SIGTERM);
  5387. forkpid = 0;
  5388. }
  5389. #endif
  5390. execv(initial_args[0], initial_args);
  5391. applog(LOG_WARNING, "Failed to restart application");
  5392. }
  5393. static void sighandler(int __maybe_unused sig)
  5394. {
  5395. /* Restore signal handlers so we can still quit if kill_work fails */
  5396. sigaction(SIGTERM, &termhandler, NULL);
  5397. sigaction(SIGINT, &inthandler, NULL);
  5398. kill_work();
  5399. }
  5400. static void start_longpoll(void);
  5401. static void stop_longpoll(void);
  5402. /* Called with pool_lock held. Recruit an extra curl if none are available for
  5403. * this pool. */
  5404. static void recruit_curl(struct pool *pool)
  5405. {
  5406. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  5407. if (unlikely(!ce))
  5408. quit(1, "Failed to calloc in recruit_curl");
  5409. ce->curl = curl_easy_init();
  5410. if (unlikely(!ce->curl))
  5411. quit(1, "Failed to init in recruit_curl");
  5412. LL_PREPEND(pool->curllist, ce);
  5413. pool->curls++;
  5414. }
  5415. /* Grab an available curl if there is one. If not, then recruit extra curls
  5416. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  5417. * and there are already 5 curls in circulation. Limit total number to the
  5418. * number of mining threads per pool as well to prevent blasting a pool during
  5419. * network delays/outages. */
  5420. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  5421. {
  5422. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  5423. bool recruited = false;
  5424. struct curl_ent *ce;
  5425. mutex_lock(&pool->pool_lock);
  5426. retry:
  5427. if (!pool->curls) {
  5428. recruit_curl(pool);
  5429. recruited = true;
  5430. } else if (!pool->curllist) {
  5431. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  5432. if (!blocking) {
  5433. mutex_unlock(&pool->pool_lock);
  5434. return NULL;
  5435. }
  5436. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  5437. goto retry;
  5438. } else {
  5439. recruit_curl(pool);
  5440. recruited = true;
  5441. }
  5442. }
  5443. ce = pool->curllist;
  5444. LL_DELETE(pool->curllist, ce);
  5445. mutex_unlock(&pool->pool_lock);
  5446. if (recruited)
  5447. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  5448. return ce;
  5449. }
  5450. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  5451. {
  5452. return pop_curl_entry3(pool, blocking ? 1 : 0);
  5453. }
  5454. __maybe_unused
  5455. static struct curl_ent *pop_curl_entry(struct pool *pool)
  5456. {
  5457. return pop_curl_entry3(pool, 1);
  5458. }
  5459. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  5460. {
  5461. mutex_lock(&pool->pool_lock);
  5462. if (!ce || !ce->curl)
  5463. quithere(1, "Attempted to add NULL");
  5464. LL_PREPEND(pool->curllist, ce);
  5465. cgtime(&ce->tv);
  5466. pthread_cond_broadcast(&pool->cr_cond);
  5467. mutex_unlock(&pool->pool_lock);
  5468. }
  5469. bool stale_work(struct work *work, bool share);
  5470. static inline bool should_roll(struct work *work)
  5471. {
  5472. struct timeval now;
  5473. time_t expiry;
  5474. if (!pool_actively_in_use(work->pool, NULL))
  5475. return false;
  5476. if (stale_work(work, false))
  5477. return false;
  5478. if (work->rolltime > opt_scantime)
  5479. expiry = work->rolltime;
  5480. else
  5481. expiry = opt_scantime;
  5482. expiry = expiry * 2 / 3;
  5483. /* We shouldn't roll if we're unlikely to get one shares' duration
  5484. * work out of doing so */
  5485. cgtime(&now);
  5486. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  5487. return false;
  5488. return true;
  5489. }
  5490. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  5491. * reject blocks as invalid. */
  5492. static inline bool can_roll(struct work *work)
  5493. {
  5494. if (work->stratum)
  5495. return false;
  5496. if (!(work->pool && !work->clone))
  5497. return false;
  5498. if (work->tr)
  5499. {
  5500. if (stale_work(work, false))
  5501. return false;
  5502. return blkmk_work_left(work->tr->tmpl);
  5503. }
  5504. return (work->rolltime &&
  5505. work->rolls < 7000 && !stale_work(work, false));
  5506. }
  5507. static void roll_work(struct work *work)
  5508. {
  5509. if (work->tr)
  5510. {
  5511. struct timeval tv_now;
  5512. cgtime(&tv_now);
  5513. if (blkmk_get_data(work->tr->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  5514. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  5515. swap32yes(work->data, work->data, 80 / 4);
  5516. calc_midstate(work);
  5517. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  5518. } else {
  5519. uint32_t *work_ntime;
  5520. uint32_t ntime;
  5521. work_ntime = (uint32_t *)(work->data + 68);
  5522. ntime = be32toh(*work_ntime);
  5523. ntime++;
  5524. *work_ntime = htobe32(ntime);
  5525. work_set_simple_ntime_roll_limit(work, 0, &work->ntime_roll_limits.tv_ref);
  5526. applog(LOG_DEBUG, "Successfully rolled time header in work");
  5527. }
  5528. local_work++;
  5529. work->rolls++;
  5530. work->blk.nonce = 0;
  5531. /* This is now a different work item so it needs a different ID for the
  5532. * hashtable */
  5533. work->id = total_work++;
  5534. }
  5535. /* Duplicates any dynamically allocated arrays within the work struct to
  5536. * prevent a copied work struct from freeing ram belonging to another struct */
  5537. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  5538. {
  5539. int id = work->id;
  5540. clean_work(work);
  5541. memcpy(work, base_work, sizeof(struct work));
  5542. /* Keep the unique new id assigned during make_work to prevent copied
  5543. * work from having the same id. */
  5544. work->id = id;
  5545. if (base_work->job_id)
  5546. work->job_id = strdup(base_work->job_id);
  5547. if (base_work->nonce1)
  5548. work->nonce1 = strdup(base_work->nonce1);
  5549. bytes_cpy(&work->nonce2, &base_work->nonce2);
  5550. if (base_work->tr)
  5551. tmpl_incref(base_work->tr);
  5552. if (noffset)
  5553. {
  5554. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  5555. uint32_t ntime = be32toh(*work_ntime);
  5556. ntime += noffset;
  5557. *work_ntime = htobe32(ntime);
  5558. }
  5559. if (work->device_data_dup_func)
  5560. work->device_data = work->device_data_dup_func(work);
  5561. }
  5562. /* Generates a copy of an existing work struct, creating fresh heap allocations
  5563. * for all dynamically allocated arrays within the struct. noffset is used for
  5564. * when a driver has internally rolled the ntime, noffset is a relative value.
  5565. * The macro copy_work() calls this function with an noffset of 0. */
  5566. struct work *copy_work_noffset(const struct work *base_work, int noffset)
  5567. {
  5568. struct work *work = make_work();
  5569. _copy_work(work, base_work, noffset);
  5570. return work;
  5571. }
  5572. void __copy_work(struct work *work, const struct work *base_work)
  5573. {
  5574. _copy_work(work, base_work, 0);
  5575. }
  5576. static struct work *make_clone(struct work *work)
  5577. {
  5578. struct work *work_clone = copy_work(work);
  5579. work_clone->clone = true;
  5580. cgtime((struct timeval *)&(work_clone->tv_cloned));
  5581. work_clone->longpoll = false;
  5582. work_clone->mandatory = false;
  5583. /* Make cloned work appear slightly older to bias towards keeping the
  5584. * master work item which can be further rolled */
  5585. work_clone->tv_staged.tv_sec -= 1;
  5586. return work_clone;
  5587. }
  5588. static void stage_work(struct work *work);
  5589. static bool clone_available(void)
  5590. {
  5591. struct work *work_clone = NULL, *work, *tmp;
  5592. bool cloned = false;
  5593. mutex_lock(stgd_lock);
  5594. if (!staged_rollable)
  5595. goto out_unlock;
  5596. HASH_ITER(hh, staged_work, work, tmp) {
  5597. if (can_roll(work) && should_roll(work)) {
  5598. roll_work(work);
  5599. work_clone = make_clone(work);
  5600. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  5601. roll_work(work);
  5602. cloned = true;
  5603. break;
  5604. }
  5605. }
  5606. out_unlock:
  5607. mutex_unlock(stgd_lock);
  5608. if (cloned) {
  5609. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  5610. stage_work(work_clone);
  5611. }
  5612. return cloned;
  5613. }
  5614. static void pool_died(struct pool *pool)
  5615. {
  5616. mutex_lock(&lp_lock);
  5617. if (!pool_tset(pool, &pool->idle)) {
  5618. cgtime(&pool->tv_idle);
  5619. pthread_cond_broadcast(&lp_cond);
  5620. mutex_unlock(&lp_lock);
  5621. if (pool == current_pool()) {
  5622. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  5623. switch_pools(NULL);
  5624. } else
  5625. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  5626. }
  5627. else
  5628. mutex_unlock(&lp_lock);
  5629. }
  5630. bool stale_work(struct work *work, bool share)
  5631. {
  5632. unsigned work_expiry;
  5633. struct pool *pool;
  5634. uint32_t block_id;
  5635. unsigned getwork_delay;
  5636. block_id = ((uint32_t*)work->data)[1];
  5637. pool = work->pool;
  5638. struct mining_goal_info * const goal = pool->goal;
  5639. struct blockchain_info * const blkchain = goal->blkchain;
  5640. /* Technically the rolltime should be correct but some pools
  5641. * advertise a broken expire= that is lower than a meaningful
  5642. * scantime */
  5643. if (work->rolltime >= opt_scantime || work->tr)
  5644. work_expiry = work->rolltime;
  5645. else
  5646. work_expiry = opt_expiry;
  5647. unsigned max_expiry = (goal->have_longpoll ? opt_expiry_lp : opt_expiry);
  5648. if (work_expiry > max_expiry)
  5649. work_expiry = max_expiry;
  5650. if (share) {
  5651. /* If the share isn't on this pool's latest block, it's stale */
  5652. if (pool->block_id && pool->block_id != block_id)
  5653. {
  5654. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  5655. return true;
  5656. }
  5657. /* If the pool doesn't want old shares, then any found in work before
  5658. * the most recent longpoll is stale */
  5659. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  5660. {
  5661. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5662. return true;
  5663. }
  5664. } else {
  5665. /* If this work isn't for the latest Bitcoin block, it's stale */
  5666. /* But only care about the current pool if failover-only */
  5667. if (enabled_pools <= 1 || opt_fail_only) {
  5668. if (pool->block_id && block_id != pool->block_id)
  5669. {
  5670. 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);
  5671. return true;
  5672. }
  5673. } else {
  5674. if (block_id != blkchain->currentblk->block_id)
  5675. {
  5676. 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);
  5677. return true;
  5678. }
  5679. }
  5680. /* If the pool has asked us to restart since this work, it's stale */
  5681. if (work->work_restart_id != pool->work_restart_id)
  5682. {
  5683. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5684. return true;
  5685. }
  5686. if (pool->has_stratum && work->job_id) {
  5687. bool same_job;
  5688. if (!pool->stratum_active || !pool->stratum_notify) {
  5689. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  5690. return true;
  5691. }
  5692. same_job = true;
  5693. cg_rlock(&pool->data_lock);
  5694. if (strcmp(work->job_id, pool->swork.job_id))
  5695. same_job = false;
  5696. cg_runlock(&pool->data_lock);
  5697. if (!same_job) {
  5698. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  5699. return true;
  5700. }
  5701. }
  5702. /* Factor in the average getwork delay of this pool, rounding it up to
  5703. * the nearest second */
  5704. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  5705. if (unlikely(work_expiry <= getwork_delay + 5))
  5706. work_expiry = 5;
  5707. else
  5708. work_expiry -= getwork_delay;
  5709. }
  5710. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  5711. if (elapsed_since_staged > work_expiry) {
  5712. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  5713. return true;
  5714. }
  5715. /* If the user only wants strict failover, any work from a pool other than
  5716. * the current one is always considered stale */
  5717. if (opt_fail_only && !share && !work->mandatory && !pool_actively_in_use(pool, NULL))
  5718. {
  5719. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  5720. return true;
  5721. }
  5722. return false;
  5723. }
  5724. double share_diff(const struct work *work)
  5725. {
  5726. double ret;
  5727. bool new_best = false;
  5728. ret = target_diff(work->hash);
  5729. cg_wlock(&control_lock);
  5730. if (unlikely(ret > best_diff)) {
  5731. new_best = true;
  5732. best_diff = ret;
  5733. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5734. }
  5735. if (unlikely(ret > work->pool->best_diff))
  5736. work->pool->best_diff = ret;
  5737. cg_wunlock(&control_lock);
  5738. if (unlikely(new_best))
  5739. applog(LOG_INFO, "New best share: %s", best_share);
  5740. return ret;
  5741. }
  5742. static
  5743. void work_check_for_block(struct work * const work)
  5744. {
  5745. struct pool * const pool = work->pool;
  5746. struct mining_goal_info * const goal = pool->goal;
  5747. work->share_diff = share_diff(work);
  5748. if (unlikely(work->share_diff >= goal->current_diff)) {
  5749. work->block = true;
  5750. work->pool->solved++;
  5751. found_blocks++;
  5752. work->mandatory = true;
  5753. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  5754. }
  5755. }
  5756. static void submit_discard_share2(const char *reason, struct work *work)
  5757. {
  5758. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  5759. sharelog(reason, work);
  5760. mutex_lock(&stats_lock);
  5761. ++total_stale;
  5762. ++cgpu->stale;
  5763. ++(work->pool->stale_shares);
  5764. total_diff_stale += work->work_difficulty;
  5765. cgpu->diff_stale += work->work_difficulty;
  5766. work->pool->diff_stale += work->work_difficulty;
  5767. mutex_unlock(&stats_lock);
  5768. }
  5769. static void submit_discard_share(struct work *work)
  5770. {
  5771. submit_discard_share2("discard", work);
  5772. }
  5773. struct submit_work_state {
  5774. struct work *work;
  5775. bool resubmit;
  5776. struct curl_ent *ce;
  5777. int failures;
  5778. struct timeval tv_staleexpire;
  5779. char *s;
  5780. struct timeval tv_submit;
  5781. struct submit_work_state *next;
  5782. };
  5783. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  5784. {
  5785. long *p_timeout_us = userp;
  5786. const long max_ms = LONG_MAX / 1000;
  5787. if (max_ms < timeout_ms)
  5788. timeout_ms = max_ms;
  5789. *p_timeout_us = timeout_ms * 1000;
  5790. return 0;
  5791. }
  5792. static void sws_has_ce(struct submit_work_state *sws)
  5793. {
  5794. struct pool *pool = sws->work->pool;
  5795. sws->s = submit_upstream_work_request(sws->work);
  5796. cgtime(&sws->tv_submit);
  5797. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5798. }
  5799. static struct submit_work_state *begin_submission(struct work *work)
  5800. {
  5801. struct pool *pool;
  5802. struct submit_work_state *sws = NULL;
  5803. pool = work->pool;
  5804. sws = malloc(sizeof(*sws));
  5805. *sws = (struct submit_work_state){
  5806. .work = work,
  5807. };
  5808. work_check_for_block(work);
  5809. if (stale_work(work, true)) {
  5810. work->stale = true;
  5811. if (opt_submit_stale)
  5812. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  5813. else if (pool->submit_old)
  5814. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  5815. else {
  5816. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  5817. submit_discard_share(work);
  5818. goto out;
  5819. }
  5820. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5821. }
  5822. if (work->stratum) {
  5823. char *s;
  5824. s = malloc(1024);
  5825. sws->s = s;
  5826. } else {
  5827. /* submit solution to bitcoin via JSON-RPC */
  5828. sws->ce = pop_curl_entry2(pool, false);
  5829. if (sws->ce) {
  5830. sws_has_ce(sws);
  5831. } else {
  5832. sws->next = pool->sws_waiting_on_curl;
  5833. pool->sws_waiting_on_curl = sws;
  5834. if (sws->next)
  5835. applog(LOG_DEBUG, "submit_thread queuing submission");
  5836. else
  5837. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  5838. }
  5839. }
  5840. return sws;
  5841. out:
  5842. free(sws);
  5843. return NULL;
  5844. }
  5845. static bool retry_submission(struct submit_work_state *sws)
  5846. {
  5847. struct work *work = sws->work;
  5848. struct pool *pool = work->pool;
  5849. sws->resubmit = true;
  5850. if ((!work->stale) && stale_work(work, true)) {
  5851. work->stale = true;
  5852. if (opt_submit_stale)
  5853. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  5854. else if (pool->submit_old)
  5855. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  5856. else {
  5857. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  5858. submit_discard_share(work);
  5859. return false;
  5860. }
  5861. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5862. }
  5863. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  5864. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  5865. submit_discard_share(work);
  5866. return false;
  5867. }
  5868. else if (work->stale) {
  5869. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  5870. {
  5871. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  5872. submit_discard_share(work);
  5873. return false;
  5874. }
  5875. }
  5876. /* pause, then restart work-request loop */
  5877. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  5878. cgtime(&sws->tv_submit);
  5879. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5880. return true;
  5881. }
  5882. static void free_sws(struct submit_work_state *sws)
  5883. {
  5884. free(sws->s);
  5885. free_work(sws->work);
  5886. free(sws);
  5887. }
  5888. static void *submit_work_thread(__maybe_unused void *userdata)
  5889. {
  5890. int wip = 0;
  5891. CURLM *curlm;
  5892. long curlm_timeout_us = -1;
  5893. struct timeval curlm_timer;
  5894. struct submit_work_state *sws, **swsp;
  5895. struct submit_work_state *write_sws = NULL;
  5896. unsigned tsreduce = 0;
  5897. pthread_detach(pthread_self());
  5898. RenameThread("submit_work");
  5899. applog(LOG_DEBUG, "Creating extra submit work thread");
  5900. curlm = curl_multi_init();
  5901. curlm_timeout_us = -1;
  5902. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  5903. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  5904. fd_set rfds, wfds, efds;
  5905. int maxfd;
  5906. struct timeval tv_timeout, tv_now;
  5907. int n;
  5908. CURLMsg *cm;
  5909. FD_ZERO(&rfds);
  5910. while (1) {
  5911. mutex_lock(&submitting_lock);
  5912. total_submitting -= tsreduce;
  5913. tsreduce = 0;
  5914. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  5915. notifier_read(submit_waiting_notifier);
  5916. }
  5917. // Receive any new submissions
  5918. while (submit_waiting) {
  5919. struct work *work = submit_waiting;
  5920. DL_DELETE(submit_waiting, work);
  5921. if ( (sws = begin_submission(work)) ) {
  5922. if (sws->ce)
  5923. curl_multi_add_handle(curlm, sws->ce->curl);
  5924. else if (sws->s) {
  5925. sws->next = write_sws;
  5926. write_sws = sws;
  5927. }
  5928. ++wip;
  5929. }
  5930. else {
  5931. --total_submitting;
  5932. free_work(work);
  5933. }
  5934. }
  5935. if (unlikely(shutting_down && !wip))
  5936. break;
  5937. mutex_unlock(&submitting_lock);
  5938. FD_ZERO(&rfds);
  5939. FD_ZERO(&wfds);
  5940. FD_ZERO(&efds);
  5941. tv_timeout.tv_sec = -1;
  5942. // Setup cURL with select
  5943. // Need to call perform to ensure the timeout gets updated
  5944. curl_multi_perform(curlm, &n);
  5945. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  5946. if (curlm_timeout_us >= 0)
  5947. {
  5948. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  5949. reduce_timeout_to(&tv_timeout, &curlm_timer);
  5950. }
  5951. // Setup waiting stratum submissions with select
  5952. for (sws = write_sws; sws; sws = sws->next)
  5953. {
  5954. struct pool *pool = sws->work->pool;
  5955. int fd = pool->sock;
  5956. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  5957. continue;
  5958. FD_SET(fd, &wfds);
  5959. set_maxfd(&maxfd, fd);
  5960. }
  5961. // Setup "submit waiting" notifier with select
  5962. FD_SET(submit_waiting_notifier[0], &rfds);
  5963. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  5964. // Wait for something interesting to happen :)
  5965. cgtime(&tv_now);
  5966. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  5967. FD_ZERO(&rfds);
  5968. continue;
  5969. }
  5970. // Handle any stratum ready-to-write results
  5971. for (swsp = &write_sws; (sws = *swsp); ) {
  5972. struct work *work = sws->work;
  5973. struct pool *pool = work->pool;
  5974. int fd = pool->sock;
  5975. bool sessionid_match;
  5976. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  5977. next_write_sws:
  5978. // TODO: Check if stale, possibly discard etc
  5979. swsp = &sws->next;
  5980. continue;
  5981. }
  5982. cg_rlock(&pool->data_lock);
  5983. // 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
  5984. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  5985. sessionid_match = (!pool->swork.nonce1) || !strcmp(work->nonce1, pool->swork.nonce1);
  5986. cg_runlock(&pool->data_lock);
  5987. if (!sessionid_match)
  5988. {
  5989. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  5990. submit_discard_share2("disconnect", work);
  5991. ++tsreduce;
  5992. next_write_sws_del:
  5993. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  5994. FD_CLR(fd, &wfds);
  5995. // Delete sws for this submission, since we're done with it
  5996. *swsp = sws->next;
  5997. free_sws(sws);
  5998. --wip;
  5999. continue;
  6000. }
  6001. char *s = sws->s;
  6002. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  6003. int sshare_id;
  6004. uint32_t nonce;
  6005. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  6006. char noncehex[9];
  6007. char ntimehex[9];
  6008. sshare->work = copy_work(work);
  6009. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  6010. nonce = *((uint32_t *)(work->data + 76));
  6011. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  6012. bin2hex(ntimehex, (void *)&work->data[68], 4);
  6013. mutex_lock(&sshare_lock);
  6014. /* Give the stratum share a unique id */
  6015. sshare_id =
  6016. sshare->id = swork_id++;
  6017. HASH_ADD_INT(stratum_shares, id, sshare);
  6018. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  6019. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  6020. mutex_unlock(&sshare_lock);
  6021. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  6022. if (likely(stratum_send(pool, s, strlen(s)))) {
  6023. if (pool_tclear(pool, &pool->submit_fail))
  6024. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  6025. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  6026. goto next_write_sws_del;
  6027. } else if (!pool_tset(pool, &pool->submit_fail)) {
  6028. // Undo stuff
  6029. mutex_lock(&sshare_lock);
  6030. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  6031. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  6032. if (sshare)
  6033. HASH_DEL(stratum_shares, sshare);
  6034. mutex_unlock(&sshare_lock);
  6035. if (sshare)
  6036. {
  6037. free_work(sshare->work);
  6038. free(sshare);
  6039. }
  6040. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  6041. total_ro++;
  6042. pool->remotefail_occasions++;
  6043. if (!sshare)
  6044. goto next_write_sws_del;
  6045. goto next_write_sws;
  6046. }
  6047. }
  6048. // Handle any cURL activities
  6049. curl_multi_perform(curlm, &n);
  6050. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  6051. if (cm->msg == CURLMSG_DONE)
  6052. {
  6053. bool finished;
  6054. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  6055. curl_multi_remove_handle(curlm, cm->easy_handle);
  6056. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  6057. if (!finished) {
  6058. if (retry_submission(sws))
  6059. curl_multi_add_handle(curlm, sws->ce->curl);
  6060. else
  6061. finished = true;
  6062. }
  6063. if (finished) {
  6064. --wip;
  6065. ++tsreduce;
  6066. struct pool *pool = sws->work->pool;
  6067. if (pool->sws_waiting_on_curl) {
  6068. pool->sws_waiting_on_curl->ce = sws->ce;
  6069. sws_has_ce(pool->sws_waiting_on_curl);
  6070. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  6071. curl_multi_add_handle(curlm, sws->ce->curl);
  6072. } else {
  6073. push_curl_entry(sws->ce, sws->work->pool);
  6074. }
  6075. free_sws(sws);
  6076. }
  6077. }
  6078. }
  6079. }
  6080. assert(!write_sws);
  6081. mutex_unlock(&submitting_lock);
  6082. curl_multi_cleanup(curlm);
  6083. applog(LOG_DEBUG, "submit_work thread exiting");
  6084. return NULL;
  6085. }
  6086. /* Find the pool that currently has the highest priority */
  6087. static struct pool *priority_pool(int choice)
  6088. {
  6089. struct pool *ret = NULL;
  6090. int i;
  6091. for (i = 0; i < total_pools; i++) {
  6092. struct pool *pool = pools[i];
  6093. if (pool->prio == choice) {
  6094. ret = pool;
  6095. break;
  6096. }
  6097. }
  6098. if (unlikely(!ret)) {
  6099. applog(LOG_ERR, "WTF No pool %d found!", choice);
  6100. return pools[choice];
  6101. }
  6102. return ret;
  6103. }
  6104. int prioritize_pools(char *param, int *pid)
  6105. {
  6106. char *ptr, *next;
  6107. int i, pr, prio = 0;
  6108. if (total_pools == 0) {
  6109. return MSG_NOPOOL;
  6110. }
  6111. if (param == NULL || *param == '\0') {
  6112. return MSG_MISPID;
  6113. }
  6114. bool pools_changed[total_pools];
  6115. int new_prio[total_pools];
  6116. for (i = 0; i < total_pools; ++i)
  6117. pools_changed[i] = false;
  6118. next = param;
  6119. while (next && *next) {
  6120. ptr = next;
  6121. next = strchr(ptr, ',');
  6122. if (next)
  6123. *(next++) = '\0';
  6124. i = atoi(ptr);
  6125. if (i < 0 || i >= total_pools) {
  6126. *pid = i;
  6127. return MSG_INVPID;
  6128. }
  6129. if (pools_changed[i]) {
  6130. *pid = i;
  6131. return MSG_DUPPID;
  6132. }
  6133. pools_changed[i] = true;
  6134. new_prio[i] = prio++;
  6135. }
  6136. // Only change them if no errors
  6137. for (i = 0; i < total_pools; i++) {
  6138. if (pools_changed[i])
  6139. pools[i]->prio = new_prio[i];
  6140. }
  6141. // In priority order, cycle through the unchanged pools and append them
  6142. for (pr = 0; pr < total_pools; pr++)
  6143. for (i = 0; i < total_pools; i++) {
  6144. if (!pools_changed[i] && pools[i]->prio == pr) {
  6145. pools[i]->prio = prio++;
  6146. pools_changed[i] = true;
  6147. break;
  6148. }
  6149. }
  6150. if (current_pool()->prio)
  6151. switch_pools(NULL);
  6152. return MSG_POOLPRIO;
  6153. }
  6154. void validate_pool_priorities(void)
  6155. {
  6156. // TODO: this should probably do some sort of logging
  6157. int i, j;
  6158. bool used[total_pools];
  6159. bool valid[total_pools];
  6160. for (i = 0; i < total_pools; i++)
  6161. used[i] = valid[i] = false;
  6162. for (i = 0; i < total_pools; i++) {
  6163. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  6164. if (!used[pools[i]->prio]) {
  6165. valid[i] = true;
  6166. used[pools[i]->prio] = true;
  6167. }
  6168. }
  6169. }
  6170. for (i = 0; i < total_pools; i++) {
  6171. if (!valid[i]) {
  6172. for (j = 0; j < total_pools; j++) {
  6173. if (!used[j]) {
  6174. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  6175. pools[i]->prio = j;
  6176. used[j] = true;
  6177. break;
  6178. }
  6179. }
  6180. }
  6181. }
  6182. }
  6183. static void clear_pool_work(struct pool *pool);
  6184. /* Specifies whether we can switch to this pool or not. */
  6185. static bool pool_unusable(struct pool *pool)
  6186. {
  6187. if (pool->idle)
  6188. return true;
  6189. if (pool->enabled != POOL_ENABLED)
  6190. return true;
  6191. return false;
  6192. }
  6193. void switch_pools(struct pool *selected)
  6194. {
  6195. struct pool *pool, *last_pool, *failover_pool = NULL;
  6196. int i, pool_no, next_pool;
  6197. if (selected)
  6198. enable_pool(selected);
  6199. cg_wlock(&control_lock);
  6200. last_pool = currentpool;
  6201. pool_no = currentpool->pool_no;
  6202. /* Switch selected to pool number 0 and move the rest down */
  6203. if (selected) {
  6204. if (selected->prio != 0) {
  6205. for (i = 0; i < total_pools; i++) {
  6206. pool = pools[i];
  6207. if (pool->prio < selected->prio)
  6208. pool->prio++;
  6209. }
  6210. selected->prio = 0;
  6211. }
  6212. }
  6213. switch (pool_strategy) {
  6214. /* All of these set to the master pool */
  6215. case POOL_BALANCE:
  6216. case POOL_FAILOVER:
  6217. case POOL_LOADBALANCE:
  6218. for (i = 0; i < total_pools; i++) {
  6219. pool = priority_pool(i);
  6220. if (pool_unusable(pool))
  6221. continue;
  6222. pool_no = pool->pool_no;
  6223. break;
  6224. }
  6225. break;
  6226. /* Both of these simply increment and cycle */
  6227. case POOL_ROUNDROBIN:
  6228. case POOL_ROTATE:
  6229. if (selected && !selected->idle) {
  6230. pool_no = selected->pool_no;
  6231. break;
  6232. }
  6233. next_pool = pool_no;
  6234. /* Select the next alive pool */
  6235. for (i = 1; i < total_pools; i++) {
  6236. next_pool++;
  6237. if (next_pool >= total_pools)
  6238. next_pool = 0;
  6239. pool = pools[next_pool];
  6240. if (pool_unusable(pool))
  6241. continue;
  6242. if (pool->failover_only)
  6243. {
  6244. BFGINIT(failover_pool, pool);
  6245. continue;
  6246. }
  6247. pool_no = next_pool;
  6248. break;
  6249. }
  6250. break;
  6251. default:
  6252. break;
  6253. }
  6254. pool = pools[pool_no];
  6255. if (pool_unusable(pool) && failover_pool)
  6256. pool = failover_pool;
  6257. currentpool = pool;
  6258. cg_wunlock(&control_lock);
  6259. mutex_lock(&lp_lock);
  6260. pthread_cond_broadcast(&lp_cond);
  6261. mutex_unlock(&lp_lock);
  6262. /* Set the lagging flag to avoid pool not providing work fast enough
  6263. * messages in failover only mode since we have to get all fresh work
  6264. * as in restart_threads */
  6265. if (opt_fail_only)
  6266. pool_tset(pool, &pool->lagging);
  6267. if (pool != last_pool)
  6268. {
  6269. pool->block_id = 0;
  6270. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  6271. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  6272. if (pool_localgen(pool) || opt_fail_only)
  6273. clear_pool_work(last_pool);
  6274. }
  6275. }
  6276. mutex_lock(&lp_lock);
  6277. pthread_cond_broadcast(&lp_cond);
  6278. mutex_unlock(&lp_lock);
  6279. #ifdef HAVE_CURSES
  6280. update_block_display();
  6281. #endif
  6282. }
  6283. static void discard_work(struct work *work)
  6284. {
  6285. if (!work->clone && !work->rolls && !work->mined) {
  6286. if (work->pool) {
  6287. work->pool->discarded_work++;
  6288. work->pool->quota_used--;
  6289. work->pool->works--;
  6290. }
  6291. total_discarded++;
  6292. applog(LOG_DEBUG, "Discarded work");
  6293. } else
  6294. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  6295. free_work(work);
  6296. }
  6297. static bool work_rollable(struct work *);
  6298. static
  6299. void unstage_work(struct work * const work)
  6300. {
  6301. HASH_DEL(staged_work, work);
  6302. --work_mining_algorithm(work)->staged;
  6303. if (work_rollable(work))
  6304. --staged_rollable;
  6305. staged_full = false;
  6306. }
  6307. static void wake_gws(void)
  6308. {
  6309. mutex_lock(stgd_lock);
  6310. pthread_cond_signal(&gws_cond);
  6311. mutex_unlock(stgd_lock);
  6312. }
  6313. static void discard_stale(void)
  6314. {
  6315. struct work *work, *tmp;
  6316. int stale = 0;
  6317. mutex_lock(stgd_lock);
  6318. HASH_ITER(hh, staged_work, work, tmp) {
  6319. if (stale_work(work, false)) {
  6320. unstage_work(work);
  6321. discard_work(work);
  6322. stale++;
  6323. }
  6324. }
  6325. pthread_cond_signal(&gws_cond);
  6326. mutex_unlock(stgd_lock);
  6327. if (stale)
  6328. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  6329. }
  6330. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  6331. {
  6332. bool rv;
  6333. struct timeval tv, orig;
  6334. ldiv_t d;
  6335. d = ldiv(ustime, 1000000);
  6336. tv = (struct timeval){
  6337. .tv_sec = d.quot,
  6338. .tv_usec = d.rem,
  6339. };
  6340. orig = work->tv_staged;
  6341. timersub(&orig, &tv, &work->tv_staged);
  6342. rv = stale_work(work, share);
  6343. work->tv_staged = orig;
  6344. return rv;
  6345. }
  6346. static
  6347. void pool_update_work_restart_time(struct pool * const pool)
  6348. {
  6349. pool->work_restart_time = time(NULL);
  6350. get_timestamp(pool->work_restart_timestamp, sizeof(pool->work_restart_timestamp), pool->work_restart_time);
  6351. }
  6352. static void restart_threads(void)
  6353. {
  6354. struct pool *cp = current_pool();
  6355. int i;
  6356. struct thr_info *thr;
  6357. /* Artificially set the lagging flag to avoid pool not providing work
  6358. * fast enough messages after every long poll */
  6359. pool_tset(cp, &cp->lagging);
  6360. /* Discard staged work that is now stale */
  6361. discard_stale();
  6362. rd_lock(&mining_thr_lock);
  6363. for (i = 0; i < mining_threads; i++)
  6364. {
  6365. thr = mining_thr[i];
  6366. thr->work_restart = true;
  6367. }
  6368. for (i = 0; i < mining_threads; i++)
  6369. {
  6370. thr = mining_thr[i];
  6371. notifier_wake(thr->work_restart_notifier);
  6372. }
  6373. rd_unlock(&mining_thr_lock);
  6374. }
  6375. void blkhashstr(char *rv, const unsigned char *hash)
  6376. {
  6377. unsigned char hash_swap[32];
  6378. swap256(hash_swap, hash);
  6379. swap32tole(hash_swap, hash_swap, 32 / 4);
  6380. bin2hex(rv, hash_swap, 32);
  6381. }
  6382. static
  6383. void set_curblock(struct mining_goal_info * const goal, struct block_info * const blkinfo)
  6384. {
  6385. struct blockchain_info * const blkchain = goal->blkchain;
  6386. blkchain->currentblk = blkinfo;
  6387. blkchain->currentblk_subsidy = 5000000000LL >> (blkinfo->height / 210000);
  6388. cg_wlock(&ch_lock);
  6389. __update_block_title(goal);
  6390. get_timestamp(blkchain->currentblk_first_seen_time_str, sizeof(blkchain->currentblk_first_seen_time_str), blkinfo->first_seen_time);
  6391. cg_wunlock(&ch_lock);
  6392. applog(LOG_INFO, "New block: %s diff %s (%s)", goal->current_goal_detail, goal->current_diff_str, goal->net_hashrate);
  6393. }
  6394. /* Search to see if this prevblkhash has been seen before */
  6395. static
  6396. struct block_info *block_exists(const struct blockchain_info * const blkchain, const void * const prevblkhash)
  6397. {
  6398. struct block_info *s;
  6399. rd_lock(&blk_lock);
  6400. HASH_FIND(hh, blkchain->blocks, prevblkhash, 0x20, s);
  6401. rd_unlock(&blk_lock);
  6402. return s;
  6403. }
  6404. static int block_sort(struct block_info * const blocka, struct block_info * const blockb)
  6405. {
  6406. return blocka->block_seen_order - blockb->block_seen_order;
  6407. }
  6408. static
  6409. void set_blockdiff(struct mining_goal_info * const goal, const struct work * const work)
  6410. {
  6411. unsigned char target[32];
  6412. double diff;
  6413. uint64_t diff64;
  6414. real_block_target(target, work->data);
  6415. diff = target_diff(target);
  6416. diff64 = diff;
  6417. suffix_string(diff64, goal->current_diff_str, sizeof(goal->current_diff_str), 0);
  6418. format_unit2(goal->net_hashrate, sizeof(goal->net_hashrate),
  6419. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  6420. if (unlikely(goal->current_diff != diff))
  6421. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", goal->current_diff_str, goal->net_hashrate);
  6422. goal->current_diff = diff;
  6423. }
  6424. static bool test_work_current(struct work *work)
  6425. {
  6426. bool ret = true;
  6427. if (work->mandatory)
  6428. return ret;
  6429. uint32_t block_id = ((uint32_t*)(work->data))[1];
  6430. const uint8_t * const prevblkhash = &work->data[4];
  6431. {
  6432. /* Hack to work around dud work sneaking into test */
  6433. bool dudwork = true;
  6434. for (int i = 8; i < 26; ++i)
  6435. if (work->data[i])
  6436. {
  6437. dudwork = false;
  6438. break;
  6439. }
  6440. if (dudwork)
  6441. goto out_free;
  6442. }
  6443. struct pool * const pool = work->pool;
  6444. struct mining_goal_info * const goal = pool->goal;
  6445. struct blockchain_info * const blkchain = goal->blkchain;
  6446. /* Search to see if this block exists yet and if not, consider it a
  6447. * new block and set the current block details to this one */
  6448. if (!block_exists(blkchain, prevblkhash))
  6449. {
  6450. struct block_info * const s = calloc(sizeof(struct block_info), 1);
  6451. int deleted_block = 0;
  6452. ret = false;
  6453. if (unlikely(!s))
  6454. quit (1, "test_work_current OOM");
  6455. memcpy(s->prevblkhash, prevblkhash, sizeof(s->prevblkhash));
  6456. s->block_id = block_id;
  6457. s->block_seen_order = new_blocks++;
  6458. s->first_seen_time = time(NULL);
  6459. wr_lock(&blk_lock);
  6460. /* Only keep the last hour's worth of blocks in memory since
  6461. * work from blocks before this is virtually impossible and we
  6462. * want to prevent memory usage from continually rising */
  6463. if (HASH_COUNT(blkchain->blocks) > 6)
  6464. {
  6465. struct block_info *oldblock;
  6466. HASH_SORT(blkchain->blocks, block_sort);
  6467. oldblock = blkchain->blocks;
  6468. deleted_block = oldblock->block_seen_order;
  6469. HASH_DEL(blkchain->blocks, oldblock);
  6470. free(oldblock);
  6471. }
  6472. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(s->prevblkhash), s);
  6473. set_blockdiff(goal, work);
  6474. wr_unlock(&blk_lock);
  6475. pool->block_id = block_id;
  6476. pool_update_work_restart_time(pool);
  6477. if (deleted_block)
  6478. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  6479. #if BLKMAKER_VERSION > 1
  6480. template_nonce = 0;
  6481. #endif
  6482. set_curblock(goal, s);
  6483. if (unlikely(new_blocks == 1))
  6484. goto out_free;
  6485. if (!work->stratum)
  6486. {
  6487. if (work->longpoll)
  6488. {
  6489. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  6490. pool->pool_no);
  6491. }
  6492. else
  6493. if (goal->have_longpoll)
  6494. applog(LOG_NOTICE, "New block detected on network before longpoll");
  6495. else
  6496. applog(LOG_NOTICE, "New block detected on network");
  6497. }
  6498. restart_threads();
  6499. }
  6500. else
  6501. {
  6502. bool restart = false;
  6503. if (unlikely(pool->block_id != block_id))
  6504. {
  6505. bool was_active = pool->block_id != 0;
  6506. pool->block_id = block_id;
  6507. pool_update_work_restart_time(pool);
  6508. if (!work->longpoll)
  6509. update_last_work(work);
  6510. if (was_active)
  6511. {
  6512. // Pool actively changed block
  6513. if (pool == current_pool())
  6514. restart = true;
  6515. if (block_id == blkchain->currentblk->block_id)
  6516. {
  6517. // Caught up, only announce if this pool is the one in use
  6518. if (restart)
  6519. applog(LOG_NOTICE, "%s %d caught up to new block",
  6520. work->longpoll ? "Longpoll from pool" : "Pool",
  6521. pool->pool_no);
  6522. }
  6523. else
  6524. {
  6525. // Switched to a block we know, but not the latest... why?
  6526. // This might detect pools trying to double-spend or 51%,
  6527. // but let's not make any accusations until it's had time
  6528. // in the real world.
  6529. char hexstr[65];
  6530. blkhashstr(hexstr, prevblkhash);
  6531. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  6532. work->longpoll ? "Longpoll from pool" : "Pool",
  6533. pool->pool_no,
  6534. hexstr);
  6535. }
  6536. }
  6537. }
  6538. if (work->longpoll)
  6539. {
  6540. struct pool * const cp = current_pool();
  6541. ++pool->work_restart_id;
  6542. if (work->tr && work->tr == pool->swork.tr)
  6543. pool->swork.work_restart_id = pool->work_restart_id;
  6544. update_last_work(work);
  6545. pool_update_work_restart_time(pool);
  6546. applog(
  6547. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  6548. "Longpoll from pool %d requested work update",
  6549. pool->pool_no);
  6550. if ((!restart) && pool == cp)
  6551. restart = true;
  6552. }
  6553. if (restart)
  6554. restart_threads();
  6555. }
  6556. work->longpoll = false;
  6557. out_free:
  6558. return ret;
  6559. }
  6560. static int tv_sort(struct work *worka, struct work *workb)
  6561. {
  6562. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  6563. }
  6564. static bool work_rollable(struct work *work)
  6565. {
  6566. return (!work->clone && work->rolltime);
  6567. }
  6568. static bool hash_push(struct work *work)
  6569. {
  6570. bool rc = true;
  6571. mutex_lock(stgd_lock);
  6572. if (work_rollable(work))
  6573. staged_rollable++;
  6574. ++work_mining_algorithm(work)->staged;
  6575. if (likely(!getq->frozen)) {
  6576. HASH_ADD_INT(staged_work, id, work);
  6577. HASH_SORT(staged_work, tv_sort);
  6578. } else
  6579. rc = false;
  6580. pthread_cond_broadcast(&getq->cond);
  6581. mutex_unlock(stgd_lock);
  6582. return rc;
  6583. }
  6584. static void stage_work(struct work *work)
  6585. {
  6586. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  6587. work->id, work->pool->pool_no);
  6588. work->work_restart_id = work->pool->work_restart_id;
  6589. work->pool->last_work_time = time(NULL);
  6590. cgtime(&work->pool->tv_last_work_time);
  6591. test_work_current(work);
  6592. work->pool->works++;
  6593. hash_push(work);
  6594. }
  6595. #ifdef HAVE_CURSES
  6596. int curses_int(const char *query)
  6597. {
  6598. int ret;
  6599. char *cvar;
  6600. cvar = curses_input(query);
  6601. if (unlikely(!cvar))
  6602. return -1;
  6603. ret = atoi(cvar);
  6604. free(cvar);
  6605. return ret;
  6606. }
  6607. #endif
  6608. #ifdef HAVE_CURSES
  6609. static bool input_pool(bool live);
  6610. #endif
  6611. #ifdef HAVE_CURSES
  6612. static void display_pool_summary(struct pool *pool)
  6613. {
  6614. double efficiency = 0.0;
  6615. char xfer[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+4+1], bw[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+6+1];
  6616. int pool_secs;
  6617. if (curses_active_locked()) {
  6618. wlog("Pool: %s Goal: %s\n", pool->rpc_url, pool->goal->name);
  6619. if (pool->solved)
  6620. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  6621. if (!pool->has_stratum)
  6622. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  6623. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  6624. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  6625. wlog(" Accepted shares: %d\n", pool->accepted);
  6626. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  6627. pool->rejected, pool->stale_shares,
  6628. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  6629. );
  6630. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  6631. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  6632. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  6633. wlog(" Network transfer: %s (%s)\n",
  6634. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  6635. (float)pool->cgminer_pool_stats.net_bytes_received,
  6636. (float)pool->cgminer_pool_stats.net_bytes_sent),
  6637. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  6638. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  6639. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  6640. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  6641. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  6642. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  6643. wlog(" Items worked on: %d\n", pool->works);
  6644. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  6645. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  6646. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  6647. unlock_curses();
  6648. }
  6649. }
  6650. #endif
  6651. /* We can't remove the memory used for this struct pool because there may
  6652. * still be work referencing it. We just remove it from the pools list */
  6653. void remove_pool(struct pool *pool)
  6654. {
  6655. int i, last_pool = total_pools - 1;
  6656. struct pool *other;
  6657. disable_pool(pool, POOL_DISABLED);
  6658. /* Boost priority of any lower prio than this one */
  6659. for (i = 0; i < total_pools; i++) {
  6660. other = pools[i];
  6661. if (other->prio > pool->prio)
  6662. other->prio--;
  6663. }
  6664. if (pool->pool_no < last_pool) {
  6665. /* Swap the last pool for this one */
  6666. (pools[last_pool])->pool_no = pool->pool_no;
  6667. pools[pool->pool_no] = pools[last_pool];
  6668. }
  6669. /* Give it an invalid number */
  6670. pool->pool_no = total_pools;
  6671. pool->removed = true;
  6672. pool->has_stratum = false;
  6673. total_pools--;
  6674. }
  6675. /* add a mutex if this needs to be thread safe in the future */
  6676. static struct JE {
  6677. char *buf;
  6678. struct JE *next;
  6679. } *jedata = NULL;
  6680. static void json_escape_free()
  6681. {
  6682. struct JE *jeptr = jedata;
  6683. struct JE *jenext;
  6684. jedata = NULL;
  6685. while (jeptr) {
  6686. jenext = jeptr->next;
  6687. free(jeptr->buf);
  6688. free(jeptr);
  6689. jeptr = jenext;
  6690. }
  6691. }
  6692. static
  6693. char *json_escape(const char *str)
  6694. {
  6695. struct JE *jeptr;
  6696. char *buf, *ptr;
  6697. /* 2x is the max, may as well just allocate that */
  6698. ptr = buf = malloc(strlen(str) * 2 + 1);
  6699. jeptr = malloc(sizeof(*jeptr));
  6700. jeptr->buf = buf;
  6701. jeptr->next = jedata;
  6702. jedata = jeptr;
  6703. while (*str) {
  6704. if (*str == '\\' || *str == '"')
  6705. *(ptr++) = '\\';
  6706. *(ptr++) = *(str++);
  6707. }
  6708. *ptr = '\0';
  6709. return buf;
  6710. }
  6711. static
  6712. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  6713. {
  6714. if (!elist)
  6715. return;
  6716. static struct string_elist *entry;
  6717. fprintf(fcfg, ",\n\"%s\" : [", configname);
  6718. bool first = true;
  6719. DL_FOREACH(elist, entry)
  6720. {
  6721. const char * const s = entry->string;
  6722. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  6723. first = false;
  6724. }
  6725. fprintf(fcfg, "\n]");
  6726. }
  6727. void write_config(FILE *fcfg)
  6728. {
  6729. int i;
  6730. /* Write pool values */
  6731. fputs("{\n\"pools\" : [", fcfg);
  6732. for(i = 0; i < total_pools; i++) {
  6733. struct pool *pool = pools[i];
  6734. if (pool->failover_only)
  6735. // Don't write failover-only (automatically added) pools to the config file for now
  6736. continue;
  6737. if (pool->quota != 1) {
  6738. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  6739. pool->quota,
  6740. json_escape(pool->rpc_url));
  6741. } else {
  6742. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  6743. json_escape(pool->rpc_url));
  6744. }
  6745. if (pool->rpc_proxy)
  6746. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  6747. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  6748. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  6749. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  6750. if (pool->force_rollntime)
  6751. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  6752. fprintf(fcfg, "\n\t}");
  6753. }
  6754. fputs("\n]\n", fcfg);
  6755. #ifdef HAVE_OPENCL
  6756. write_config_opencl(fcfg);
  6757. #endif
  6758. #ifdef WANT_CPUMINE
  6759. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  6760. #endif
  6761. /* Simple bool and int options */
  6762. struct opt_table *opt;
  6763. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  6764. char *p, *name = strdup(opt->names);
  6765. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  6766. if (p[1] != '-')
  6767. continue;
  6768. if (opt->type & OPT_NOARG &&
  6769. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  6770. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  6771. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  6772. if (opt->type & OPT_HASARG &&
  6773. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  6774. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  6775. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  6776. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  6777. opt->desc != opt_hidden &&
  6778. 0 <= *(int *)opt->u.arg)
  6779. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  6780. }
  6781. }
  6782. /* Special case options */
  6783. if (request_target_str)
  6784. {
  6785. if (request_pdiff == (long)request_pdiff)
  6786. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  6787. else
  6788. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  6789. }
  6790. fprintf(fcfg, ",\n\"shares\" : %g", opt_shares);
  6791. if (pool_strategy == POOL_BALANCE)
  6792. fputs(",\n\"balance\" : true", fcfg);
  6793. if (pool_strategy == POOL_LOADBALANCE)
  6794. fputs(",\n\"load-balance\" : true", fcfg);
  6795. if (pool_strategy == POOL_ROUNDROBIN)
  6796. fputs(",\n\"round-robin\" : true", fcfg);
  6797. if (pool_strategy == POOL_ROTATE)
  6798. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  6799. #if defined(unix) || defined(__APPLE__)
  6800. if (opt_stderr_cmd && *opt_stderr_cmd)
  6801. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  6802. #endif // defined(unix)
  6803. if (opt_kernel_path && *opt_kernel_path) {
  6804. char *kpath = strdup(opt_kernel_path);
  6805. if (kpath[strlen(kpath)-1] == '/')
  6806. kpath[strlen(kpath)-1] = 0;
  6807. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  6808. free(kpath);
  6809. }
  6810. if (schedstart.enable)
  6811. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  6812. if (schedstop.enable)
  6813. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  6814. if (opt_socks_proxy && *opt_socks_proxy)
  6815. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  6816. _write_config_string_elist(fcfg, "scan", scan_devices);
  6817. #ifdef USE_LIBMICROHTTPD
  6818. if (httpsrv_port != -1)
  6819. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  6820. #endif
  6821. #ifdef USE_LIBEVENT
  6822. if (stratumsrv_port != -1)
  6823. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  6824. #endif
  6825. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  6826. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  6827. if (opt_api_allow)
  6828. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  6829. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  6830. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  6831. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  6832. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  6833. if (*opt_api_mcast_des)
  6834. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  6835. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  6836. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  6837. if (opt_api_groups)
  6838. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  6839. fputs("\n}\n", fcfg);
  6840. json_escape_free();
  6841. }
  6842. void zero_bestshare(void)
  6843. {
  6844. int i;
  6845. best_diff = 0;
  6846. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  6847. for (i = 0; i < total_pools; i++) {
  6848. struct pool *pool = pools[i];
  6849. pool->best_diff = 0;
  6850. }
  6851. }
  6852. void zero_stats(void)
  6853. {
  6854. int i;
  6855. applog(LOG_DEBUG, "Zeroing stats");
  6856. cgtime(&total_tv_start);
  6857. miner_started = total_tv_start;
  6858. total_rolling = 0;
  6859. total_mhashes_done = 0;
  6860. total_getworks = 0;
  6861. total_accepted = 0;
  6862. total_rejected = 0;
  6863. hw_errors = 0;
  6864. total_stale = 0;
  6865. total_discarded = 0;
  6866. total_bytes_rcvd = total_bytes_sent = 0;
  6867. new_blocks = 0;
  6868. local_work = 0;
  6869. total_go = 0;
  6870. total_ro = 0;
  6871. total_secs = 1.0;
  6872. total_diff1 = 0;
  6873. total_bad_diff1 = 0;
  6874. found_blocks = 0;
  6875. total_diff_accepted = 0;
  6876. total_diff_rejected = 0;
  6877. total_diff_stale = 0;
  6878. #ifdef HAVE_CURSES
  6879. awidth = rwidth = swidth = hwwidth = 1;
  6880. #endif
  6881. struct mining_goal_info *goal, *tmpgoal;
  6882. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  6883. {
  6884. goal->diff_accepted = 0;
  6885. }
  6886. for (i = 0; i < total_pools; i++) {
  6887. struct pool *pool = pools[i];
  6888. pool->getwork_requested = 0;
  6889. pool->accepted = 0;
  6890. pool->rejected = 0;
  6891. pool->solved = 0;
  6892. pool->getwork_requested = 0;
  6893. pool->stale_shares = 0;
  6894. pool->discarded_work = 0;
  6895. pool->getfail_occasions = 0;
  6896. pool->remotefail_occasions = 0;
  6897. pool->last_share_time = 0;
  6898. pool->works = 0;
  6899. pool->diff1 = 0;
  6900. pool->diff_accepted = 0;
  6901. pool->diff_rejected = 0;
  6902. pool->diff_stale = 0;
  6903. pool->last_share_diff = 0;
  6904. pool->cgminer_stats.start_tv = total_tv_start;
  6905. pool->cgminer_stats.getwork_calls = 0;
  6906. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6907. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6908. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6909. pool->cgminer_pool_stats.getwork_calls = 0;
  6910. pool->cgminer_pool_stats.getwork_attempts = 0;
  6911. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6912. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  6913. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  6914. pool->cgminer_pool_stats.min_diff = 0;
  6915. pool->cgminer_pool_stats.max_diff = 0;
  6916. pool->cgminer_pool_stats.min_diff_count = 0;
  6917. pool->cgminer_pool_stats.max_diff_count = 0;
  6918. pool->cgminer_pool_stats.times_sent = 0;
  6919. pool->cgminer_pool_stats.bytes_sent = 0;
  6920. pool->cgminer_pool_stats.net_bytes_sent = 0;
  6921. pool->cgminer_pool_stats.times_received = 0;
  6922. pool->cgminer_pool_stats.bytes_received = 0;
  6923. pool->cgminer_pool_stats.net_bytes_received = 0;
  6924. }
  6925. zero_bestshare();
  6926. for (i = 0; i < total_devices; ++i) {
  6927. struct cgpu_info *cgpu = get_devices(i);
  6928. mutex_lock(&hash_lock);
  6929. cgpu->total_mhashes = 0;
  6930. cgpu->accepted = 0;
  6931. cgpu->rejected = 0;
  6932. cgpu->stale = 0;
  6933. cgpu->hw_errors = 0;
  6934. cgpu->utility = 0.0;
  6935. cgpu->utility_diff1 = 0;
  6936. cgpu->last_share_pool_time = 0;
  6937. cgpu->bad_diff1 = 0;
  6938. cgpu->diff1 = 0;
  6939. cgpu->diff_accepted = 0;
  6940. cgpu->diff_rejected = 0;
  6941. cgpu->diff_stale = 0;
  6942. cgpu->last_share_diff = 0;
  6943. cgpu->thread_fail_init_count = 0;
  6944. cgpu->thread_zero_hash_count = 0;
  6945. cgpu->thread_fail_queue_count = 0;
  6946. cgpu->dev_sick_idle_60_count = 0;
  6947. cgpu->dev_dead_idle_600_count = 0;
  6948. cgpu->dev_nostart_count = 0;
  6949. cgpu->dev_over_heat_count = 0;
  6950. cgpu->dev_thermal_cutoff_count = 0;
  6951. cgpu->dev_comms_error_count = 0;
  6952. cgpu->dev_throttle_count = 0;
  6953. cgpu->cgminer_stats.start_tv = total_tv_start;
  6954. cgpu->cgminer_stats.getwork_calls = 0;
  6955. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6956. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6957. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6958. mutex_unlock(&hash_lock);
  6959. if (cgpu->drv->zero_stats)
  6960. cgpu->drv->zero_stats(cgpu);
  6961. }
  6962. }
  6963. #ifdef HAVE_CURSES
  6964. static
  6965. void loginput_mode(const int size)
  6966. {
  6967. clear_logwin();
  6968. loginput_size = size;
  6969. check_winsizes();
  6970. }
  6971. static void display_pools(void)
  6972. {
  6973. struct pool *pool;
  6974. int selected, i, j;
  6975. char input;
  6976. loginput_mode(7 + total_pools);
  6977. immedok(logwin, true);
  6978. updated:
  6979. for (j = 0; j < total_pools; j++) {
  6980. for (i = 0; i < total_pools; i++) {
  6981. pool = pools[i];
  6982. if (pool->prio != j)
  6983. continue;
  6984. if (pool == current_pool())
  6985. wattron(logwin, A_BOLD);
  6986. if (pool->enabled != POOL_ENABLED || pool->failover_only)
  6987. wattron(logwin, A_DIM);
  6988. wlogprint("%d: ", pool->prio);
  6989. switch (pool->enabled) {
  6990. case POOL_ENABLED:
  6991. if (pool->failover_only)
  6992. wlogprint("Failover ");
  6993. else
  6994. wlogprint("Enabled ");
  6995. break;
  6996. case POOL_DISABLED:
  6997. wlogprint("Disabled ");
  6998. break;
  6999. case POOL_REJECTING:
  7000. wlogprint("Rejectin ");
  7001. break;
  7002. case POOL_MISBEHAVING:
  7003. wlogprint("Misbehav ");
  7004. break;
  7005. }
  7006. _wlogprint(pool_proto_str(pool));
  7007. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  7008. pool->quota,
  7009. pool->pool_no,
  7010. pool->rpc_url, pool->rpc_user);
  7011. wattroff(logwin, A_BOLD | A_DIM);
  7012. break; //for (i = 0; i < total_pools; i++)
  7013. }
  7014. }
  7015. retry:
  7016. wlogprint("\nCurrent pool management strategy: %s\n",
  7017. strategies[pool_strategy].s);
  7018. if (pool_strategy == POOL_ROTATE)
  7019. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  7020. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  7021. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  7022. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  7023. wlogprint("Or press any other key to continue\n");
  7024. logwin_update();
  7025. input = getch();
  7026. if (!strncasecmp(&input, "a", 1)) {
  7027. if (opt_benchmark)
  7028. {
  7029. wlogprint("Cannot add pools in benchmark mode");
  7030. goto retry;
  7031. }
  7032. input_pool(true);
  7033. goto updated;
  7034. } else if (!strncasecmp(&input, "r", 1)) {
  7035. if (total_pools <= 1) {
  7036. wlogprint("Cannot remove last pool");
  7037. goto retry;
  7038. }
  7039. selected = curses_int("Select pool number");
  7040. if (selected < 0 || selected >= total_pools) {
  7041. wlogprint("Invalid selection\n");
  7042. goto retry;
  7043. }
  7044. pool = pools[selected];
  7045. if (pool == current_pool())
  7046. switch_pools(NULL);
  7047. if (pool == current_pool()) {
  7048. wlogprint("Unable to remove pool due to activity\n");
  7049. goto retry;
  7050. }
  7051. remove_pool(pool);
  7052. goto updated;
  7053. } else if (!strncasecmp(&input, "s", 1)) {
  7054. selected = curses_int("Select pool number");
  7055. if (selected < 0 || selected >= total_pools) {
  7056. wlogprint("Invalid selection\n");
  7057. goto retry;
  7058. }
  7059. pool = pools[selected];
  7060. pool->failover_only = false;
  7061. switch_pools(pool);
  7062. goto updated;
  7063. } else if (!strncasecmp(&input, "d", 1)) {
  7064. if (enabled_pools <= 1) {
  7065. wlogprint("Cannot disable last pool");
  7066. goto retry;
  7067. }
  7068. selected = curses_int("Select pool number");
  7069. if (selected < 0 || selected >= total_pools) {
  7070. wlogprint("Invalid selection\n");
  7071. goto retry;
  7072. }
  7073. pool = pools[selected];
  7074. disable_pool(pool, POOL_DISABLED);
  7075. goto updated;
  7076. } else if (!strncasecmp(&input, "e", 1)) {
  7077. selected = curses_int("Select pool number");
  7078. if (selected < 0 || selected >= total_pools) {
  7079. wlogprint("Invalid selection\n");
  7080. goto retry;
  7081. }
  7082. pool = pools[selected];
  7083. pool->failover_only = false;
  7084. enable_pool(pool);
  7085. goto updated;
  7086. } else if (!strncasecmp(&input, "c", 1)) {
  7087. for (i = 0; i <= TOP_STRATEGY; i++)
  7088. wlogprint("%d: %s\n", i, strategies[i].s);
  7089. selected = curses_int("Select strategy number type");
  7090. if (selected < 0 || selected > TOP_STRATEGY) {
  7091. wlogprint("Invalid selection\n");
  7092. goto retry;
  7093. }
  7094. if (selected == POOL_ROTATE) {
  7095. opt_rotate_period = curses_int("Select interval in minutes");
  7096. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  7097. opt_rotate_period = 0;
  7098. wlogprint("Invalid selection\n");
  7099. goto retry;
  7100. }
  7101. }
  7102. mutex_lock(&lp_lock);
  7103. pool_strategy = selected;
  7104. pthread_cond_broadcast(&lp_cond);
  7105. mutex_unlock(&lp_lock);
  7106. switch_pools(NULL);
  7107. goto updated;
  7108. } else if (!strncasecmp(&input, "i", 1)) {
  7109. selected = curses_int("Select pool number");
  7110. if (selected < 0 || selected >= total_pools) {
  7111. wlogprint("Invalid selection\n");
  7112. goto retry;
  7113. }
  7114. pool = pools[selected];
  7115. display_pool_summary(pool);
  7116. goto retry;
  7117. } else if (!strncasecmp(&input, "q", 1)) {
  7118. selected = curses_int("Select pool number");
  7119. if (selected < 0 || selected >= total_pools) {
  7120. wlogprint("Invalid selection\n");
  7121. goto retry;
  7122. }
  7123. pool = pools[selected];
  7124. selected = curses_int("Set quota");
  7125. if (selected < 0) {
  7126. wlogprint("Invalid negative quota\n");
  7127. goto retry;
  7128. }
  7129. pool->quota = selected;
  7130. adjust_quota_gcd();
  7131. goto updated;
  7132. } else if (!strncasecmp(&input, "f", 1)) {
  7133. opt_fail_only ^= true;
  7134. goto updated;
  7135. } else if (!strncasecmp(&input, "p", 1)) {
  7136. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  7137. if (!prilist)
  7138. {
  7139. wlogprint("Not changing priorities\n");
  7140. goto retry;
  7141. }
  7142. int res = prioritize_pools(prilist, &i);
  7143. free(prilist);
  7144. switch (res) {
  7145. case MSG_NOPOOL:
  7146. wlogprint("No pools\n");
  7147. goto retry;
  7148. case MSG_MISPID:
  7149. wlogprint("Missing pool id parameter\n");
  7150. goto retry;
  7151. case MSG_INVPID:
  7152. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  7153. goto retry;
  7154. case MSG_DUPPID:
  7155. wlogprint("Duplicate pool specified %d\n", i);
  7156. goto retry;
  7157. case MSG_POOLPRIO:
  7158. default:
  7159. goto updated;
  7160. }
  7161. }
  7162. immedok(logwin, false);
  7163. loginput_mode(0);
  7164. }
  7165. static const char *summary_detail_level_str(void)
  7166. {
  7167. if (opt_compact)
  7168. return "compact";
  7169. if (opt_show_procs)
  7170. return "processors";
  7171. return "devices";
  7172. }
  7173. static void display_options(void)
  7174. {
  7175. int selected;
  7176. char input;
  7177. immedok(logwin, true);
  7178. loginput_mode(12);
  7179. retry:
  7180. clear_logwin();
  7181. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  7182. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  7183. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  7184. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  7185. opt_debug_console ? "on" : "off",
  7186. want_per_device_stats? "on" : "off",
  7187. opt_quiet ? "on" : "off",
  7188. opt_log_output ? "on" : "off",
  7189. opt_protocol ? "on" : "off",
  7190. opt_worktime ? "on" : "off",
  7191. summary_detail_level_str(),
  7192. opt_log_interval,
  7193. opt_weighed_stats ? "weighed" : "absolute");
  7194. wlogprint("Select an option or any other key to return\n");
  7195. logwin_update();
  7196. input = getch();
  7197. if (!strncasecmp(&input, "q", 1)) {
  7198. opt_quiet ^= true;
  7199. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  7200. goto retry;
  7201. } else if (!strncasecmp(&input, "v", 1)) {
  7202. opt_log_output ^= true;
  7203. if (opt_log_output)
  7204. opt_quiet = false;
  7205. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  7206. goto retry;
  7207. } else if (!strncasecmp(&input, "n", 1)) {
  7208. opt_log_output = false;
  7209. opt_debug_console = false;
  7210. opt_quiet = false;
  7211. opt_protocol = false;
  7212. opt_compact = false;
  7213. opt_show_procs = false;
  7214. devsummaryYOffset = 0;
  7215. want_per_device_stats = false;
  7216. wlogprint("Output mode reset to normal\n");
  7217. switch_logsize();
  7218. goto retry;
  7219. } else if (!strncasecmp(&input, "d", 1)) {
  7220. opt_debug = true;
  7221. opt_debug_console ^= true;
  7222. opt_log_output = opt_debug_console;
  7223. if (opt_debug_console)
  7224. opt_quiet = false;
  7225. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  7226. goto retry;
  7227. } else if (!strncasecmp(&input, "m", 1)) {
  7228. if (opt_compact)
  7229. opt_compact = false;
  7230. else
  7231. if (!opt_show_procs)
  7232. opt_show_procs = true;
  7233. else
  7234. {
  7235. opt_compact = true;
  7236. opt_show_procs = false;
  7237. devsummaryYOffset = 0;
  7238. }
  7239. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  7240. switch_logsize();
  7241. goto retry;
  7242. } else if (!strncasecmp(&input, "p", 1)) {
  7243. want_per_device_stats ^= true;
  7244. opt_log_output = want_per_device_stats;
  7245. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  7246. goto retry;
  7247. } else if (!strncasecmp(&input, "r", 1)) {
  7248. opt_protocol ^= true;
  7249. if (opt_protocol)
  7250. opt_quiet = false;
  7251. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  7252. goto retry;
  7253. } else if (!strncasecmp(&input, "c", 1))
  7254. clear_logwin();
  7255. else if (!strncasecmp(&input, "l", 1)) {
  7256. selected = curses_int("Interval in seconds");
  7257. if (selected < 0 || selected > 9999) {
  7258. wlogprint("Invalid selection\n");
  7259. goto retry;
  7260. }
  7261. opt_log_interval = selected;
  7262. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  7263. goto retry;
  7264. } else if (!strncasecmp(&input, "s", 1)) {
  7265. opt_realquiet = true;
  7266. } else if (!strncasecmp(&input, "w", 1)) {
  7267. opt_worktime ^= true;
  7268. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  7269. goto retry;
  7270. } else if (!strncasecmp(&input, "t", 1)) {
  7271. opt_weighed_stats ^= true;
  7272. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  7273. goto retry;
  7274. } else if (!strncasecmp(&input, "z", 1)) {
  7275. zero_stats();
  7276. goto retry;
  7277. }
  7278. immedok(logwin, false);
  7279. loginput_mode(0);
  7280. }
  7281. #endif
  7282. void default_save_file(char *filename)
  7283. {
  7284. #if defined(unix) || defined(__APPLE__)
  7285. if (getenv("HOME") && *getenv("HOME")) {
  7286. strcpy(filename, getenv("HOME"));
  7287. strcat(filename, "/");
  7288. }
  7289. else
  7290. strcpy(filename, "");
  7291. strcat(filename, ".bfgminer/");
  7292. mkdir(filename, 0777);
  7293. #else
  7294. strcpy(filename, "");
  7295. #endif
  7296. strcat(filename, def_conf);
  7297. }
  7298. #ifdef HAVE_CURSES
  7299. static void set_options(void)
  7300. {
  7301. int selected;
  7302. char input;
  7303. immedok(logwin, true);
  7304. loginput_mode(8);
  7305. retry:
  7306. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  7307. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  7308. "[W]rite config file\n[B]FGMiner restart\n",
  7309. opt_queue, opt_scantime, opt_expiry, opt_retries);
  7310. wlogprint("Select an option or any other key to return\n");
  7311. logwin_update();
  7312. input = getch();
  7313. if (!strncasecmp(&input, "q", 1)) {
  7314. selected = curses_int("Extra work items to queue");
  7315. if (selected < 0 || selected > 9999) {
  7316. wlogprint("Invalid selection\n");
  7317. goto retry;
  7318. }
  7319. opt_queue = selected;
  7320. goto retry;
  7321. } else if (!strncasecmp(&input, "l", 1)) {
  7322. if (want_longpoll)
  7323. stop_longpoll();
  7324. else
  7325. start_longpoll();
  7326. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  7327. goto retry;
  7328. } else if (!strncasecmp(&input, "s", 1)) {
  7329. selected = curses_int("Set scantime in seconds");
  7330. if (selected < 0 || selected > 9999) {
  7331. wlogprint("Invalid selection\n");
  7332. goto retry;
  7333. }
  7334. opt_scantime = selected;
  7335. goto retry;
  7336. } else if (!strncasecmp(&input, "e", 1)) {
  7337. selected = curses_int("Set expiry time in seconds");
  7338. if (selected < 0 || selected > 9999) {
  7339. wlogprint("Invalid selection\n");
  7340. goto retry;
  7341. }
  7342. opt_expiry = selected;
  7343. goto retry;
  7344. } else if (!strncasecmp(&input, "r", 1)) {
  7345. selected = curses_int("Retries before failing (-1 infinite)");
  7346. if (selected < -1 || selected > 9999) {
  7347. wlogprint("Invalid selection\n");
  7348. goto retry;
  7349. }
  7350. opt_retries = selected;
  7351. goto retry;
  7352. } else if (!strncasecmp(&input, "w", 1)) {
  7353. FILE *fcfg;
  7354. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  7355. default_save_file(filename);
  7356. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  7357. str = curses_input(prompt);
  7358. if (str) {
  7359. struct stat statbuf;
  7360. strcpy(filename, str);
  7361. free(str);
  7362. if (!stat(filename, &statbuf)) {
  7363. wlogprint("File exists, overwrite?\n");
  7364. input = getch();
  7365. if (strncasecmp(&input, "y", 1))
  7366. goto retry;
  7367. }
  7368. }
  7369. fcfg = fopen(filename, "w");
  7370. if (!fcfg) {
  7371. wlogprint("Cannot open or create file\n");
  7372. goto retry;
  7373. }
  7374. write_config(fcfg);
  7375. fclose(fcfg);
  7376. goto retry;
  7377. } else if (!strncasecmp(&input, "b", 1)) {
  7378. wlogprint("Are you sure?\n");
  7379. input = getch();
  7380. if (!strncasecmp(&input, "y", 1))
  7381. app_restart();
  7382. else
  7383. clear_logwin();
  7384. } else
  7385. clear_logwin();
  7386. loginput_mode(0);
  7387. immedok(logwin, false);
  7388. }
  7389. int scan_serial(const char *);
  7390. static
  7391. void _managetui_msg(const char *repr, const char **msg)
  7392. {
  7393. if (*msg)
  7394. {
  7395. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  7396. wattron(logwin, A_BOLD);
  7397. wlogprint("%s", *msg);
  7398. wattroff(logwin, A_BOLD);
  7399. *msg = NULL;
  7400. }
  7401. logwin_update();
  7402. }
  7403. void manage_device(void)
  7404. {
  7405. char logline[256];
  7406. const char *msg = NULL;
  7407. struct cgpu_info *cgpu;
  7408. const struct device_drv *drv;
  7409. selecting_device = true;
  7410. immedok(logwin, true);
  7411. loginput_mode(12);
  7412. devchange:
  7413. if (unlikely(!total_devices))
  7414. {
  7415. clear_logwin();
  7416. wlogprint("(no devices)\n");
  7417. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  7418. _managetui_msg("(none)", &msg);
  7419. int input = getch();
  7420. switch (input)
  7421. {
  7422. case '+': case '=': // add new device
  7423. goto addnew;
  7424. default:
  7425. goto out;
  7426. }
  7427. }
  7428. cgpu = devices[selected_device];
  7429. drv = cgpu->drv;
  7430. refresh_devstatus();
  7431. refresh:
  7432. clear_logwin();
  7433. wlogprint("Select processor to manage using up/down arrow keys\n");
  7434. get_statline3(logline, sizeof(logline), cgpu, true, true);
  7435. wattron(logwin, A_BOLD);
  7436. wlogprint("%s", logline);
  7437. wattroff(logwin, A_BOLD);
  7438. wlogprint("\n");
  7439. if (cgpu->dev_manufacturer)
  7440. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  7441. else
  7442. if (cgpu->dev_product)
  7443. wlogprint(" %s\n", cgpu->dev_product);
  7444. if (cgpu->dev_serial)
  7445. wlogprint("Serial: %s\n", cgpu->dev_serial);
  7446. if (cgpu->kname)
  7447. wlogprint("Kernel: %s\n", cgpu->kname);
  7448. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  7449. drv->proc_wlogprint_status(cgpu);
  7450. wlogprint("\n");
  7451. // TODO: Last share at TIMESTAMP on pool N
  7452. // TODO: Custom device info/commands
  7453. if (cgpu->deven != DEV_ENABLED)
  7454. wlogprint("[E]nable ");
  7455. if (cgpu->deven != DEV_DISABLED)
  7456. wlogprint("[D]isable ");
  7457. if (drv->identify_device)
  7458. wlogprint("[I]dentify ");
  7459. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  7460. drv->proc_tui_wlogprint_choices(cgpu);
  7461. wlogprint("\n");
  7462. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  7463. _managetui_msg(cgpu->proc_repr, &msg);
  7464. while (true)
  7465. {
  7466. int input = getch();
  7467. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  7468. switch (input) {
  7469. case 'd': case 'D':
  7470. if (cgpu->deven == DEV_DISABLED)
  7471. msg = "Processor already disabled\n";
  7472. else
  7473. {
  7474. cgpu->deven = DEV_DISABLED;
  7475. msg = "Processor being disabled\n";
  7476. }
  7477. goto refresh;
  7478. case 'e': case 'E':
  7479. if (cgpu->deven == DEV_ENABLED)
  7480. msg = "Processor already enabled\n";
  7481. else
  7482. {
  7483. proc_enable(cgpu);
  7484. msg = "Processor being enabled\n";
  7485. }
  7486. goto refresh;
  7487. case 'i': case 'I':
  7488. if (drv->identify_device && drv->identify_device(cgpu))
  7489. msg = "Identify command sent\n";
  7490. else
  7491. goto key_default;
  7492. goto refresh;
  7493. case KEY_DOWN:
  7494. if (selected_device >= total_devices - 1)
  7495. break;
  7496. ++selected_device;
  7497. goto devchange;
  7498. case KEY_UP:
  7499. if (selected_device <= 0)
  7500. break;
  7501. --selected_device;
  7502. goto devchange;
  7503. case KEY_NPAGE:
  7504. {
  7505. if (selected_device >= total_devices - 1)
  7506. break;
  7507. struct cgpu_info *mdev = devices[selected_device]->device;
  7508. do {
  7509. ++selected_device;
  7510. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  7511. goto devchange;
  7512. }
  7513. case KEY_PPAGE:
  7514. {
  7515. if (selected_device <= 0)
  7516. break;
  7517. struct cgpu_info *mdev = devices[selected_device]->device;
  7518. do {
  7519. --selected_device;
  7520. } while (devices[selected_device]->device == mdev && selected_device > 0);
  7521. goto devchange;
  7522. }
  7523. case '/': case '?': // find device
  7524. {
  7525. static char *pattern = NULL;
  7526. char *newpattern = curses_input("Enter pattern");
  7527. if (newpattern)
  7528. {
  7529. free(pattern);
  7530. pattern = newpattern;
  7531. }
  7532. else
  7533. if (!pattern)
  7534. pattern = calloc(1, 1);
  7535. int match = cgpu_search(pattern, selected_device + 1);
  7536. if (match == -1)
  7537. {
  7538. msg = "Couldn't find device\n";
  7539. goto refresh;
  7540. }
  7541. selected_device = match;
  7542. goto devchange;
  7543. }
  7544. case '+': case '=': // add new device
  7545. {
  7546. addnew:
  7547. clear_logwin();
  7548. _wlogprint(
  7549. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  7550. "Prefix by a driver name and colon to only probe a specific driver.\n"
  7551. "For example: erupter:"
  7552. #ifdef WIN32
  7553. "\\\\.\\COM40"
  7554. #elif defined(__APPLE__)
  7555. "/dev/cu.SLAB_USBtoUART"
  7556. #else
  7557. "/dev/ttyUSB39"
  7558. #endif
  7559. "\n"
  7560. );
  7561. char *scanser = curses_input("Enter target");
  7562. if (scan_serial(scanser))
  7563. {
  7564. selected_device = total_devices - 1;
  7565. msg = "Device scan succeeded\n";
  7566. }
  7567. else
  7568. msg = "No new devices found\n";
  7569. goto devchange;
  7570. }
  7571. case 'Q': case 'q':
  7572. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  7573. case '\x1b': // ESC
  7574. case KEY_ENTER:
  7575. case '\r': // Ctrl-M on Windows, with nonl
  7576. #ifdef PADENTER
  7577. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  7578. #endif
  7579. case '\n':
  7580. goto out;
  7581. default:
  7582. ;
  7583. key_default:
  7584. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  7585. {
  7586. msg = drv->proc_tui_handle_choice(cgpu, input);
  7587. if (msg)
  7588. goto refresh;
  7589. }
  7590. }
  7591. }
  7592. out:
  7593. selecting_device = false;
  7594. loginput_mode(0);
  7595. immedok(logwin, false);
  7596. }
  7597. void show_help(void)
  7598. {
  7599. loginput_mode(11);
  7600. // NOTE: wlogprint is a macro with a buffer limit
  7601. _wlogprint(
  7602. "LU: oldest explicit work update currently being used for new work\n"
  7603. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  7604. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  7605. "E: # shares * diff per 2kB bw | I: expected income | BS: best share ever found\n"
  7606. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7607. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7608. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7609. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  7610. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7611. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7612. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE
  7613. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7614. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7615. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7616. "\n"
  7617. "devices/processors hashing (only for totals line), hottest temperature\n"
  7618. );
  7619. wlogprint(
  7620. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  7621. , opt_log_interval);
  7622. _wlogprint(
  7623. "A: accepted shares | R: rejected+discarded(% of total)\n"
  7624. "HW: hardware errors / % nonces invalid\n"
  7625. "\n"
  7626. "Press any key to clear"
  7627. );
  7628. logwin_update();
  7629. getch();
  7630. loginput_mode(0);
  7631. }
  7632. static void *input_thread(void __maybe_unused *userdata)
  7633. {
  7634. RenameThread("input");
  7635. if (!curses_active)
  7636. return NULL;
  7637. while (1) {
  7638. int input;
  7639. input = getch();
  7640. switch (input) {
  7641. case 'h': case 'H': case '?':
  7642. case KEY_F(1):
  7643. show_help();
  7644. break;
  7645. case 'q': case 'Q':
  7646. kill_work();
  7647. return NULL;
  7648. case 'd': case 'D':
  7649. display_options();
  7650. break;
  7651. case 'm': case 'M':
  7652. manage_device();
  7653. break;
  7654. case 'p': case 'P':
  7655. display_pools();
  7656. break;
  7657. case 's': case 'S':
  7658. set_options();
  7659. break;
  7660. #ifdef HAVE_CURSES
  7661. case KEY_DOWN:
  7662. {
  7663. const int visible_lines = logcursor - devcursor;
  7664. const int invisible_lines = total_lines - visible_lines;
  7665. if (devsummaryYOffset <= -invisible_lines)
  7666. break;
  7667. devsummaryYOffset -= 2;
  7668. }
  7669. case KEY_UP:
  7670. if (devsummaryYOffset == 0)
  7671. break;
  7672. ++devsummaryYOffset;
  7673. refresh_devstatus();
  7674. break;
  7675. case KEY_NPAGE:
  7676. {
  7677. const int visible_lines = logcursor - devcursor;
  7678. const int invisible_lines = total_lines - visible_lines;
  7679. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  7680. devsummaryYOffset = -invisible_lines;
  7681. else
  7682. devsummaryYOffset -= visible_lines;
  7683. refresh_devstatus();
  7684. break;
  7685. }
  7686. case KEY_PPAGE:
  7687. {
  7688. const int visible_lines = logcursor - devcursor;
  7689. if (devsummaryYOffset + visible_lines >= 0)
  7690. devsummaryYOffset = 0;
  7691. else
  7692. devsummaryYOffset += visible_lines;
  7693. refresh_devstatus();
  7694. break;
  7695. }
  7696. #endif
  7697. }
  7698. if (opt_realquiet) {
  7699. disable_curses();
  7700. break;
  7701. }
  7702. }
  7703. return NULL;
  7704. }
  7705. #endif
  7706. static void *api_thread(void *userdata)
  7707. {
  7708. struct thr_info *mythr = userdata;
  7709. pthread_detach(pthread_self());
  7710. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7711. RenameThread("rpc");
  7712. api(api_thr_id);
  7713. mythr->has_pth = false;
  7714. return NULL;
  7715. }
  7716. void thread_reportin(struct thr_info *thr)
  7717. {
  7718. cgtime(&thr->last);
  7719. thr->cgpu->status = LIFE_WELL;
  7720. thr->getwork = 0;
  7721. thr->cgpu->device_last_well = time(NULL);
  7722. }
  7723. void thread_reportout(struct thr_info *thr)
  7724. {
  7725. thr->getwork = time(NULL);
  7726. }
  7727. static void hashmeter(int thr_id, struct timeval *diff,
  7728. uint64_t hashes_done)
  7729. {
  7730. char logstatusline[256];
  7731. struct timeval temp_tv_end, total_diff;
  7732. double secs;
  7733. double local_secs;
  7734. static double local_mhashes_done = 0;
  7735. double local_mhashes = (double)hashes_done / 1000000.0;
  7736. bool showlog = false;
  7737. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[ALLOC_H2B_SPACED+3+1];
  7738. char rejpcbuf[6];
  7739. char bnbuf[6];
  7740. struct thr_info *thr;
  7741. /* Update the last time this thread reported in */
  7742. if (thr_id >= 0) {
  7743. thr = get_thread(thr_id);
  7744. cgtime(&(thr->last));
  7745. thr->cgpu->device_last_well = time(NULL);
  7746. }
  7747. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  7748. /* So we can call hashmeter from a non worker thread */
  7749. if (thr_id >= 0) {
  7750. struct cgpu_info *cgpu = thr->cgpu;
  7751. int threadobj = cgpu->threads ?: 1;
  7752. double thread_rolling = 0.0;
  7753. int i;
  7754. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  7755. thr_id, hashes_done, hashes_done / 1000 / secs);
  7756. /* Rolling average for each thread and each device */
  7757. decay_time(&thr->rolling, local_mhashes / secs, secs);
  7758. for (i = 0; i < threadobj; i++)
  7759. thread_rolling += cgpu->thr[i]->rolling;
  7760. mutex_lock(&hash_lock);
  7761. decay_time(&cgpu->rolling, thread_rolling, secs);
  7762. cgpu->total_mhashes += local_mhashes;
  7763. mutex_unlock(&hash_lock);
  7764. // If needed, output detailed, per-device stats
  7765. if (want_per_device_stats) {
  7766. struct timeval now;
  7767. struct timeval elapsed;
  7768. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  7769. cgtime(&now);
  7770. timersub(&now, last_msg_tv, &elapsed);
  7771. if (opt_log_interval <= elapsed.tv_sec) {
  7772. struct cgpu_info *cgpu = thr->cgpu;
  7773. char logline[255];
  7774. *last_msg_tv = now;
  7775. get_statline(logline, sizeof(logline), cgpu);
  7776. if (!curses_active) {
  7777. printf("\n%s\r", logline);
  7778. fflush(stdout);
  7779. } else
  7780. applog(LOG_INFO, "%s", logline);
  7781. }
  7782. }
  7783. }
  7784. /* Totals are updated by all threads so can race without locking */
  7785. mutex_lock(&hash_lock);
  7786. cgtime(&temp_tv_end);
  7787. timersub(&temp_tv_end, &total_tv_start, &total_diff);
  7788. total_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7789. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  7790. total_mhashes_done += local_mhashes;
  7791. local_mhashes_done += local_mhashes;
  7792. /* Only update with opt_log_interval */
  7793. if (total_diff.tv_sec < opt_log_interval)
  7794. goto out_unlock;
  7795. showlog = true;
  7796. cgtime(&total_tv_end);
  7797. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7798. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  7799. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  7800. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  7801. multi_format_unit_array2(
  7802. ((char*[]){cHr, aHr, uHr}),
  7803. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  7804. true, "h/s", H2B_SHORT,
  7805. 3,
  7806. 1e6*total_rolling,
  7807. 1e6*total_mhashes_done / total_secs,
  7808. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  7809. int ui_accepted, ui_rejected, ui_stale;
  7810. if (opt_weighed_stats)
  7811. {
  7812. ui_accepted = total_diff_accepted;
  7813. ui_rejected = total_diff_rejected;
  7814. ui_stale = total_diff_stale;
  7815. }
  7816. else
  7817. {
  7818. ui_accepted = total_accepted;
  7819. ui_rejected = total_rejected;
  7820. ui_stale = total_stale;
  7821. }
  7822. #ifdef HAVE_CURSES
  7823. if (curses_active_locked()) {
  7824. float temp = 0;
  7825. struct cgpu_info *proc, *last_working_dev = NULL;
  7826. int i, working_devs = 0, working_procs = 0;
  7827. int divx;
  7828. bool bad = false;
  7829. // Find the highest temperature of all processors
  7830. for (i = 0; i < total_devices; ++i)
  7831. {
  7832. proc = get_devices(i);
  7833. if (proc->temp > temp)
  7834. temp = proc->temp;
  7835. if (unlikely(proc->deven == DEV_DISABLED))
  7836. ; // Just need to block it off from both conditions
  7837. else
  7838. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  7839. {
  7840. if (proc->rolling > .1)
  7841. {
  7842. ++working_procs;
  7843. if (proc->device != last_working_dev)
  7844. {
  7845. ++working_devs;
  7846. last_working_dev = proc->device;
  7847. }
  7848. }
  7849. }
  7850. else
  7851. bad = true;
  7852. }
  7853. if (working_devs == working_procs)
  7854. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  7855. else
  7856. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  7857. divx = 7;
  7858. if (opt_show_procs && !opt_compact)
  7859. divx += max_lpdigits;
  7860. if (bad)
  7861. {
  7862. divx += sizeof(U8_BAD_START)-1;
  7863. strcpy(&statusline[divx], U8_BAD_END);
  7864. divx += sizeof(U8_BAD_END)-1;
  7865. }
  7866. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  7867. format_statline(statusline, sizeof(statusline),
  7868. cHr, aHr,
  7869. uHr,
  7870. ui_accepted,
  7871. ui_rejected,
  7872. ui_stale,
  7873. total_diff_rejected + total_diff_stale, total_diff_accepted,
  7874. hw_errors,
  7875. total_bad_diff1, total_bad_diff1 + total_diff1);
  7876. unlock_curses();
  7877. }
  7878. #endif
  7879. // Add a space
  7880. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  7881. uHr[5] = ' ';
  7882. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  7883. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  7884. snprintf(logstatusline, sizeof(logstatusline),
  7885. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  7886. want_per_device_stats ? "ALL " : "",
  7887. opt_log_interval,
  7888. cHr, aHr,
  7889. uHr,
  7890. ui_accepted,
  7891. ui_rejected,
  7892. ui_stale,
  7893. rejpcbuf,
  7894. hw_errors,
  7895. bnbuf
  7896. );
  7897. local_mhashes_done = 0;
  7898. out_unlock:
  7899. mutex_unlock(&hash_lock);
  7900. if (showlog) {
  7901. if (!curses_active) {
  7902. if (want_per_device_stats)
  7903. printf("\n%s\r", logstatusline);
  7904. else
  7905. {
  7906. const int logstatusline_len = strlen(logstatusline);
  7907. int padding;
  7908. if (last_logstatusline_len > logstatusline_len)
  7909. padding = (last_logstatusline_len - logstatusline_len);
  7910. else
  7911. {
  7912. padding = 0;
  7913. if (last_logstatusline_len == -1)
  7914. puts("");
  7915. }
  7916. printf("%s%*s\r", logstatusline, padding, "");
  7917. last_logstatusline_len = logstatusline_len;
  7918. }
  7919. fflush(stdout);
  7920. } else
  7921. applog(LOG_INFO, "%s", logstatusline);
  7922. }
  7923. }
  7924. void hashmeter2(struct thr_info *thr)
  7925. {
  7926. struct timeval tv_now, tv_elapsed;
  7927. timerclear(&thr->tv_hashes_done);
  7928. cgtime(&tv_now);
  7929. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  7930. /* Update the hashmeter at most 5 times per second */
  7931. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  7932. tv_elapsed.tv_sec >= opt_log_interval) {
  7933. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  7934. thr->hashes_done = 0;
  7935. thr->tv_lastupdate = tv_now;
  7936. }
  7937. }
  7938. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  7939. struct stratum_share *sshare)
  7940. {
  7941. struct work *work = sshare->work;
  7942. share_result(val, res_val, err_val, work, false, "");
  7943. }
  7944. /* Parses stratum json responses and tries to find the id that the request
  7945. * matched to and treat it accordingly. */
  7946. bool parse_stratum_response(struct pool *pool, char *s)
  7947. {
  7948. json_t *val = NULL, *err_val, *res_val, *id_val;
  7949. struct stratum_share *sshare;
  7950. json_error_t err;
  7951. bool ret = false;
  7952. int id;
  7953. val = JSON_LOADS(s, &err);
  7954. if (!val) {
  7955. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  7956. goto out;
  7957. }
  7958. res_val = json_object_get(val, "result");
  7959. err_val = json_object_get(val, "error");
  7960. id_val = json_object_get(val, "id");
  7961. if (json_is_null(id_val) || !id_val) {
  7962. char *ss;
  7963. if (err_val)
  7964. ss = json_dumps(err_val, JSON_INDENT(3));
  7965. else
  7966. ss = strdup("(unknown reason)");
  7967. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  7968. free(ss);
  7969. goto out;
  7970. }
  7971. if (!json_is_integer(id_val)) {
  7972. if (json_is_string(id_val)
  7973. && !strncmp(json_string_value(id_val), "txlist", 6))
  7974. {
  7975. const bool is_array = json_is_array(res_val);
  7976. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  7977. is_array ? "transaction list" : "no-transaction-list response",
  7978. pool->pool_no, &json_string_value(id_val)[6]);
  7979. if (!is_array)
  7980. {
  7981. // No need to wait for a timeout
  7982. timer_unset(&pool->swork.tv_transparency);
  7983. pool_set_opaque(pool, true);
  7984. goto fishy;
  7985. }
  7986. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id))
  7987. // We only care about a transaction list for the current job id
  7988. goto fishy;
  7989. // Check that the transactions actually hash to the merkle links
  7990. {
  7991. unsigned maxtx = 1 << pool->swork.merkles;
  7992. unsigned mintx = maxtx >> 1;
  7993. --maxtx;
  7994. unsigned acttx = (unsigned)json_array_size(res_val);
  7995. if (acttx < mintx || acttx > maxtx) {
  7996. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  7997. pool->pool_no, acttx, mintx, maxtx);
  7998. goto fishy;
  7999. }
  8000. // TODO: Check hashes match actual merkle links
  8001. }
  8002. pool_set_opaque(pool, false);
  8003. timer_unset(&pool->swork.tv_transparency);
  8004. fishy:
  8005. ret = true;
  8006. }
  8007. goto out;
  8008. }
  8009. id = json_integer_value(id_val);
  8010. mutex_lock(&sshare_lock);
  8011. HASH_FIND_INT(stratum_shares, &id, sshare);
  8012. if (sshare)
  8013. HASH_DEL(stratum_shares, sshare);
  8014. mutex_unlock(&sshare_lock);
  8015. if (!sshare) {
  8016. double pool_diff;
  8017. /* Since the share is untracked, we can only guess at what the
  8018. * work difficulty is based on the current pool diff. */
  8019. cg_rlock(&pool->data_lock);
  8020. pool_diff = target_diff(pool->swork.target);
  8021. cg_runlock(&pool->data_lock);
  8022. if (json_is_true(res_val)) {
  8023. struct mining_goal_info * const goal = pool->goal;
  8024. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  8025. /* We don't know what device this came from so we can't
  8026. * attribute the work to the relevant cgpu */
  8027. mutex_lock(&stats_lock);
  8028. total_accepted++;
  8029. pool->accepted++;
  8030. total_diff_accepted += pool_diff;
  8031. pool->diff_accepted += pool_diff;
  8032. goal->diff_accepted += pool_diff;
  8033. mutex_unlock(&stats_lock);
  8034. } else {
  8035. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  8036. mutex_lock(&stats_lock);
  8037. total_rejected++;
  8038. pool->rejected++;
  8039. total_diff_rejected += pool_diff;
  8040. pool->diff_rejected += pool_diff;
  8041. mutex_unlock(&stats_lock);
  8042. }
  8043. goto out;
  8044. }
  8045. else {
  8046. mutex_lock(&submitting_lock);
  8047. --total_submitting;
  8048. mutex_unlock(&submitting_lock);
  8049. }
  8050. stratum_share_result(val, res_val, err_val, sshare);
  8051. free_work(sshare->work);
  8052. free(sshare);
  8053. ret = true;
  8054. out:
  8055. if (val)
  8056. json_decref(val);
  8057. return ret;
  8058. }
  8059. static void shutdown_stratum(struct pool *pool)
  8060. {
  8061. // Shut down Stratum as if we never had it
  8062. pool->stratum_active = false;
  8063. pool->stratum_init = false;
  8064. pool->has_stratum = false;
  8065. shutdown(pool->sock, SHUT_RDWR);
  8066. free(pool->stratum_url);
  8067. if (pool->sockaddr_url == pool->stratum_url)
  8068. pool->sockaddr_url = NULL;
  8069. pool->stratum_url = NULL;
  8070. }
  8071. void clear_stratum_shares(struct pool *pool)
  8072. {
  8073. int my_mining_threads = mining_threads; // Cached outside of locking
  8074. struct stratum_share *sshare, *tmpshare;
  8075. struct work *work;
  8076. struct cgpu_info *cgpu;
  8077. double diff_cleared = 0;
  8078. double thr_diff_cleared[my_mining_threads];
  8079. int cleared = 0;
  8080. int thr_cleared[my_mining_threads];
  8081. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  8082. for (int i = 0; i < my_mining_threads; ++i)
  8083. {
  8084. thr_diff_cleared[i] = 0;
  8085. thr_cleared[i] = 0;
  8086. }
  8087. mutex_lock(&sshare_lock);
  8088. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  8089. work = sshare->work;
  8090. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  8091. HASH_DEL(stratum_shares, sshare);
  8092. sharelog("disconnect", work);
  8093. diff_cleared += sshare->work->work_difficulty;
  8094. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  8095. ++thr_cleared[work->thr_id];
  8096. free_work(sshare->work);
  8097. free(sshare);
  8098. cleared++;
  8099. }
  8100. }
  8101. mutex_unlock(&sshare_lock);
  8102. if (cleared) {
  8103. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  8104. mutex_lock(&stats_lock);
  8105. pool->stale_shares += cleared;
  8106. total_stale += cleared;
  8107. pool->diff_stale += diff_cleared;
  8108. total_diff_stale += diff_cleared;
  8109. for (int i = 0; i < my_mining_threads; ++i)
  8110. if (thr_cleared[i])
  8111. {
  8112. cgpu = get_thr_cgpu(i);
  8113. cgpu->diff_stale += thr_diff_cleared[i];
  8114. cgpu->stale += thr_cleared[i];
  8115. }
  8116. mutex_unlock(&stats_lock);
  8117. mutex_lock(&submitting_lock);
  8118. total_submitting -= cleared;
  8119. mutex_unlock(&submitting_lock);
  8120. }
  8121. }
  8122. static void resubmit_stratum_shares(struct pool *pool)
  8123. {
  8124. struct stratum_share *sshare, *tmpshare;
  8125. struct work *work;
  8126. unsigned resubmitted = 0;
  8127. mutex_lock(&sshare_lock);
  8128. mutex_lock(&submitting_lock);
  8129. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  8130. if (sshare->work->pool != pool)
  8131. continue;
  8132. HASH_DEL(stratum_shares, sshare);
  8133. work = sshare->work;
  8134. DL_APPEND(submit_waiting, work);
  8135. free(sshare);
  8136. ++resubmitted;
  8137. }
  8138. mutex_unlock(&submitting_lock);
  8139. mutex_unlock(&sshare_lock);
  8140. if (resubmitted) {
  8141. notifier_wake(submit_waiting_notifier);
  8142. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  8143. }
  8144. }
  8145. static void clear_pool_work(struct pool *pool)
  8146. {
  8147. struct work *work, *tmp;
  8148. int cleared = 0;
  8149. mutex_lock(stgd_lock);
  8150. HASH_ITER(hh, staged_work, work, tmp) {
  8151. if (work->pool == pool) {
  8152. unstage_work(work);
  8153. free_work(work);
  8154. cleared++;
  8155. }
  8156. }
  8157. mutex_unlock(stgd_lock);
  8158. }
  8159. static int cp_prio(void)
  8160. {
  8161. int prio;
  8162. cg_rlock(&control_lock);
  8163. prio = currentpool->prio;
  8164. cg_runlock(&control_lock);
  8165. return prio;
  8166. }
  8167. /* We only need to maintain a secondary pool connection when we need the
  8168. * capacity to get work from the backup pools while still on the primary */
  8169. static bool cnx_needed(struct pool *pool)
  8170. {
  8171. struct pool *cp;
  8172. // We want to keep a connection open for rejecting or misbehaving pools, to detect when/if they change their tune
  8173. if (pool->enabled == POOL_DISABLED)
  8174. return false;
  8175. /* Idle stratum pool needs something to kick it alive again */
  8176. if (pool->has_stratum && pool->idle)
  8177. return true;
  8178. /* Getwork pools without opt_fail_only need backup pools up to be able
  8179. * to leak shares */
  8180. cp = current_pool();
  8181. if (pool_actively_desired(pool, cp))
  8182. return true;
  8183. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  8184. return true;
  8185. /* Keep the connection open to allow any stray shares to be submitted
  8186. * on switching pools for 2 minutes. */
  8187. if (timer_elapsed(&pool->tv_last_work_time, NULL) < 120)
  8188. return true;
  8189. /* If the pool has only just come to life and is higher priority than
  8190. * the current pool keep the connection open so we can fail back to
  8191. * it. */
  8192. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8193. return true;
  8194. if (pool_unworkable(cp))
  8195. return true;
  8196. /* We've run out of work, bring anything back to life. */
  8197. if (no_work)
  8198. return true;
  8199. // If the current pool lacks its own block change detection, see if we are needed for that
  8200. if (pool_active_lp_pool(cp) == pool)
  8201. return true;
  8202. return false;
  8203. }
  8204. static void wait_lpcurrent(struct pool *pool);
  8205. static void pool_resus(struct pool *pool);
  8206. static void stratum_resumed(struct pool *pool)
  8207. {
  8208. if (!pool->stratum_notify)
  8209. return;
  8210. if (pool_tclear(pool, &pool->idle)) {
  8211. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  8212. pool_resus(pool);
  8213. }
  8214. }
  8215. static bool supports_resume(struct pool *pool)
  8216. {
  8217. bool ret;
  8218. cg_rlock(&pool->data_lock);
  8219. ret = (pool->sessionid != NULL);
  8220. cg_runlock(&pool->data_lock);
  8221. return ret;
  8222. }
  8223. static bool pools_active;
  8224. /* One stratum thread per pool that has stratum waits on the socket checking
  8225. * for new messages and for the integrity of the socket connection. We reset
  8226. * the connection based on the integrity of the receive side only as the send
  8227. * side will eventually expire data it fails to send. */
  8228. static void *stratum_thread(void *userdata)
  8229. {
  8230. struct pool *pool = (struct pool *)userdata;
  8231. pthread_detach(pthread_self());
  8232. char threadname[20];
  8233. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  8234. RenameThread(threadname);
  8235. srand(time(NULL) + (intptr_t)userdata);
  8236. while (42) {
  8237. struct timeval timeout;
  8238. int sel_ret;
  8239. fd_set rd;
  8240. char *s;
  8241. int sock;
  8242. if (unlikely(!pool->has_stratum))
  8243. break;
  8244. /* Check to see whether we need to maintain this connection
  8245. * indefinitely or just bring it up when we switch to this
  8246. * pool */
  8247. while (true)
  8248. {
  8249. sock = pool->sock;
  8250. if (sock == INVSOCK)
  8251. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  8252. pool->pool_no);
  8253. else
  8254. if (!sock_full(pool) && !cnx_needed(pool) && pools_active)
  8255. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  8256. pool->pool_no);
  8257. else
  8258. break;
  8259. suspend_stratum(pool);
  8260. clear_stratum_shares(pool);
  8261. clear_pool_work(pool);
  8262. wait_lpcurrent(pool);
  8263. if (!restart_stratum(pool)) {
  8264. pool_died(pool);
  8265. while (!restart_stratum(pool)) {
  8266. if (pool->removed)
  8267. goto out;
  8268. cgsleep_ms(30000);
  8269. }
  8270. }
  8271. }
  8272. FD_ZERO(&rd);
  8273. FD_SET(sock, &rd);
  8274. timeout.tv_sec = 120;
  8275. timeout.tv_usec = 0;
  8276. /* If we fail to receive any notify messages for 2 minutes we
  8277. * assume the connection has been dropped and treat this pool
  8278. * as dead */
  8279. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  8280. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  8281. s = NULL;
  8282. } else
  8283. s = recv_line(pool);
  8284. if (!s) {
  8285. if (!pool->has_stratum)
  8286. break;
  8287. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  8288. pool->getfail_occasions++;
  8289. total_go++;
  8290. mutex_lock(&pool->stratum_lock);
  8291. pool->stratum_active = pool->stratum_notify = false;
  8292. pool->sock = INVSOCK;
  8293. mutex_unlock(&pool->stratum_lock);
  8294. /* If the socket to our stratum pool disconnects, all
  8295. * submissions need to be discarded or resent. */
  8296. if (!supports_resume(pool))
  8297. clear_stratum_shares(pool);
  8298. else
  8299. resubmit_stratum_shares(pool);
  8300. clear_pool_work(pool);
  8301. if (pool == current_pool())
  8302. restart_threads();
  8303. if (restart_stratum(pool))
  8304. continue;
  8305. shutdown_stratum(pool);
  8306. pool_died(pool);
  8307. break;
  8308. }
  8309. /* Check this pool hasn't died while being a backup pool and
  8310. * has not had its idle flag cleared */
  8311. stratum_resumed(pool);
  8312. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  8313. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  8314. free(s);
  8315. if (pool->swork.clean) {
  8316. struct work *work = make_work();
  8317. /* Generate a single work item to update the current
  8318. * block database */
  8319. pool->swork.clean = false;
  8320. gen_stratum_work(pool, work);
  8321. /* Try to extract block height from coinbase scriptSig */
  8322. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  8323. unsigned char cb_height_sz;
  8324. cb_height_sz = bin_height[-1];
  8325. if (cb_height_sz == 3) {
  8326. // FIXME: The block number will overflow this by AD 2173
  8327. struct mining_goal_info * const goal = pool->goal;
  8328. const void * const prevblkhash = &work->data[4];
  8329. uint32_t height = 0;
  8330. memcpy(&height, bin_height, 3);
  8331. height = le32toh(height);
  8332. have_block_height(goal, prevblkhash, height);
  8333. }
  8334. pool->swork.work_restart_id =
  8335. ++pool->work_restart_id;
  8336. pool_update_work_restart_time(pool);
  8337. if (test_work_current(work)) {
  8338. /* Only accept a work update if this stratum
  8339. * connection is from the current pool */
  8340. struct pool * const cp = current_pool();
  8341. if (pool == cp)
  8342. restart_threads();
  8343. applog(
  8344. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  8345. "Stratum from pool %d requested work update", pool->pool_no);
  8346. } else
  8347. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  8348. free_work(work);
  8349. }
  8350. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  8351. // More than 4 timmills past since requested transactions
  8352. timer_unset(&pool->swork.tv_transparency);
  8353. pool_set_opaque(pool, true);
  8354. }
  8355. }
  8356. out:
  8357. return NULL;
  8358. }
  8359. static void init_stratum_thread(struct pool *pool)
  8360. {
  8361. struct mining_goal_info * const goal = pool->goal;
  8362. goal->have_longpoll = true;
  8363. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  8364. quit(1, "Failed to create stratum thread");
  8365. }
  8366. static void *longpoll_thread(void *userdata);
  8367. static bool stratum_works(struct pool *pool)
  8368. {
  8369. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  8370. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  8371. return false;
  8372. if (pool->stratum_active)
  8373. return true;
  8374. if (!initiate_stratum(pool))
  8375. return false;
  8376. return true;
  8377. }
  8378. static
  8379. bool pool_recently_got_work(struct pool * const pool, const struct timeval * const tvp_now)
  8380. {
  8381. return (timer_isset(&pool->tv_last_work_time) && timer_elapsed(&pool->tv_last_work_time, tvp_now) < 60);
  8382. }
  8383. static bool pool_active(struct pool *pool, bool pinging)
  8384. {
  8385. struct timeval tv_now, tv_getwork, tv_getwork_reply;
  8386. bool ret = false;
  8387. json_t *val;
  8388. CURL *curl = NULL;
  8389. int rolltime;
  8390. char *rpc_req;
  8391. struct work *work;
  8392. enum pool_protocol proto;
  8393. if (pool->stratum_init)
  8394. {
  8395. if (pool->stratum_active)
  8396. return true;
  8397. }
  8398. else
  8399. if (!pool->idle)
  8400. {
  8401. timer_set_now(&tv_now);
  8402. if (pool_recently_got_work(pool, &tv_now))
  8403. return true;
  8404. }
  8405. mutex_lock(&pool->pool_test_lock);
  8406. if (pool->stratum_init)
  8407. {
  8408. ret = pool->stratum_active;
  8409. goto out;
  8410. }
  8411. timer_set_now(&tv_now);
  8412. if (pool->idle)
  8413. {
  8414. if (timer_elapsed(&pool->tv_idle, &tv_now) < 30)
  8415. goto out;
  8416. }
  8417. else
  8418. if (pool_recently_got_work(pool, &tv_now))
  8419. {
  8420. ret = true;
  8421. goto out;
  8422. }
  8423. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  8424. /* This is the central point we activate stratum when we can */
  8425. curl = curl_easy_init();
  8426. if (unlikely(!curl)) {
  8427. applog(LOG_ERR, "CURL initialisation failed");
  8428. goto out;
  8429. }
  8430. if (!(want_gbt || want_getwork))
  8431. goto nohttp;
  8432. work = make_work();
  8433. /* Probe for GBT support on first pass */
  8434. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  8435. tryagain:
  8436. rpc_req = prepare_rpc_req_probe(work, proto, NULL, pool);
  8437. work->pool = pool;
  8438. if (!rpc_req)
  8439. goto out;
  8440. pool->probed = false;
  8441. cgtime(&tv_getwork);
  8442. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  8443. true, false, &rolltime, pool, false);
  8444. cgtime(&tv_getwork_reply);
  8445. free(rpc_req);
  8446. /* Detect if a http getwork pool has an X-Stratum header at startup,
  8447. * and if so, switch to that in preference to getwork if it works */
  8448. if (pool->stratum_url && want_stratum && pool_may_redirect_to(pool, pool->stratum_url) && (pool->has_stratum || stratum_works(pool))) {
  8449. if (!pool->has_stratum) {
  8450. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  8451. if (!pool->rpc_url)
  8452. pool_set_uri(pool, strdup(pool->stratum_url));
  8453. pool->has_stratum = true;
  8454. }
  8455. free_work(work);
  8456. if (val)
  8457. json_decref(val);
  8458. retry_stratum:
  8459. ;
  8460. /* We create the stratum thread for each pool just after
  8461. * successful authorisation. Once the init flag has been set
  8462. * we never unset it and the stratum thread is responsible for
  8463. * setting/unsetting the active flag */
  8464. bool init = pool_tset(pool, &pool->stratum_init);
  8465. if (!init) {
  8466. ret = initiate_stratum(pool) && auth_stratum(pool);
  8467. if (ret)
  8468. {
  8469. detect_algo = 2;
  8470. init_stratum_thread(pool);
  8471. }
  8472. else
  8473. {
  8474. pool_tclear(pool, &pool->stratum_init);
  8475. pool->tv_idle = tv_getwork_reply;
  8476. }
  8477. goto out;
  8478. }
  8479. ret = pool->stratum_active;
  8480. goto out;
  8481. }
  8482. else if (pool->has_stratum)
  8483. shutdown_stratum(pool);
  8484. if (val) {
  8485. bool rc;
  8486. json_t *res;
  8487. res = json_object_get(val, "result");
  8488. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  8489. goto badwork;
  8490. work->rolltime = rolltime;
  8491. rc = work_decode(pool, work, val);
  8492. if (rc) {
  8493. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  8494. pool->pool_no, pool->rpc_url);
  8495. work->pool = pool;
  8496. copy_time(&work->tv_getwork, &tv_getwork);
  8497. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  8498. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  8499. calc_diff(work, 0);
  8500. update_last_work(work);
  8501. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  8502. stage_work(work);
  8503. total_getworks++;
  8504. pool->getwork_requested++;
  8505. ret = true;
  8506. pool->tv_idle = tv_getwork_reply;
  8507. } else {
  8508. badwork:
  8509. json_decref(val);
  8510. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  8511. pool->pool_no, pool->rpc_url);
  8512. pool->proto = proto = pool_protocol_fallback(proto);
  8513. if (PLP_NONE != proto)
  8514. goto tryagain;
  8515. pool->tv_idle = tv_getwork_reply;
  8516. free_work(work);
  8517. goto out;
  8518. }
  8519. json_decref(val);
  8520. if (proto != pool->proto) {
  8521. pool->proto = proto;
  8522. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  8523. }
  8524. if (pool->lp_url)
  8525. goto out;
  8526. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  8527. const struct blktmpl_longpoll_req *lp;
  8528. if (work->tr && (lp = blktmpl_get_longpoll(work->tr->tmpl))) {
  8529. // NOTE: work_decode takes care of lp id
  8530. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  8531. if (!pool->lp_url)
  8532. {
  8533. ret = false;
  8534. goto out;
  8535. }
  8536. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  8537. }
  8538. else
  8539. if (pool->hdr_path && want_getwork) {
  8540. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  8541. if (!pool->lp_url)
  8542. {
  8543. ret = false;
  8544. goto out;
  8545. }
  8546. pool->lp_proto = PLP_GETWORK;
  8547. } else
  8548. pool->lp_url = NULL;
  8549. if (want_longpoll && !pool->lp_started) {
  8550. pool->lp_started = true;
  8551. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8552. quit(1, "Failed to create pool longpoll thread");
  8553. }
  8554. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  8555. pool->proto = proto;
  8556. goto tryagain;
  8557. } else {
  8558. pool->tv_idle = tv_getwork_reply;
  8559. free_work(work);
  8560. nohttp:
  8561. /* If we failed to parse a getwork, this could be a stratum
  8562. * url without the prefix stratum+tcp:// so let's check it */
  8563. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  8564. pool->has_stratum = true;
  8565. goto retry_stratum;
  8566. }
  8567. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  8568. pool->pool_no, pool->rpc_url);
  8569. if (!pinging)
  8570. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  8571. }
  8572. out:
  8573. if (curl)
  8574. curl_easy_cleanup(curl);
  8575. mutex_unlock(&pool->pool_test_lock);
  8576. return ret;
  8577. }
  8578. static void pool_resus(struct pool *pool)
  8579. {
  8580. if (pool->enabled == POOL_ENABLED && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8581. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  8582. else
  8583. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  8584. }
  8585. static
  8586. void *cmd_idle_thread(void * const __maybe_unused userp)
  8587. {
  8588. pthread_detach(pthread_self());
  8589. RenameThread("cmd-idle");
  8590. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8591. sleep(opt_log_interval);
  8592. pthread_testcancel();
  8593. run_cmd(cmd_idle);
  8594. return NULL;
  8595. }
  8596. static struct work *hash_pop(struct cgpu_info * const proc)
  8597. {
  8598. int hc;
  8599. struct work *work, *work_found, *tmp;
  8600. enum {
  8601. HPWS_NONE = 0,
  8602. HPWS_LOWDIFF = 1,
  8603. HPWS_ROLLABLE = 2,
  8604. HPWS_PERFECT = 3,
  8605. } work_score = HPWS_NONE;
  8606. bool did_cmd_idle = false;
  8607. pthread_t cmd_idle_thr;
  8608. retry:
  8609. mutex_lock(stgd_lock);
  8610. while (true)
  8611. {
  8612. work_found = NULL;
  8613. work_score = 0;
  8614. hc = HASH_COUNT(staged_work);
  8615. HASH_ITER(hh, staged_work, work, tmp)
  8616. {
  8617. const struct mining_algorithm * const work_malgo = work_mining_algorithm(work);
  8618. const float min_nonce_diff = drv_min_nonce_diff(proc->drv, proc, work_malgo);
  8619. if (min_nonce_diff < work->work_difficulty)
  8620. {
  8621. if (unlikely(min_nonce_diff >= 0 && work_score < HPWS_LOWDIFF))
  8622. {
  8623. work_found = work;
  8624. work_score = HPWS_LOWDIFF;
  8625. }
  8626. continue;
  8627. }
  8628. if (work->rolltime && hc > staged_rollable)
  8629. {
  8630. if (work_score < HPWS_ROLLABLE)
  8631. {
  8632. work_found = work;
  8633. work_score = HPWS_ROLLABLE;
  8634. }
  8635. continue;
  8636. }
  8637. // Good match
  8638. work_found = work;
  8639. work_score = HPWS_PERFECT;
  8640. break;
  8641. }
  8642. if (work_found)
  8643. {
  8644. work = work_found;
  8645. break;
  8646. }
  8647. // Failed to get a usable work
  8648. if (unlikely(staged_full))
  8649. {
  8650. if (likely(opt_queue < 10 + mining_threads))
  8651. {
  8652. ++opt_queue;
  8653. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  8654. }
  8655. else
  8656. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  8657. staged_full = false; // Let it fill up before triggering an underrun again
  8658. no_work = true;
  8659. }
  8660. pthread_cond_signal(&gws_cond);
  8661. if (cmd_idle && !did_cmd_idle)
  8662. {
  8663. if (likely(!pthread_create(&cmd_idle_thr, NULL, cmd_idle_thread, NULL)))
  8664. did_cmd_idle = true;
  8665. }
  8666. pthread_cond_wait(&getq->cond, stgd_lock);
  8667. }
  8668. if (did_cmd_idle)
  8669. pthread_cancel(cmd_idle_thr);
  8670. no_work = false;
  8671. if (can_roll(work) && should_roll(work))
  8672. {
  8673. // Instead of consuming it, force it to be cloned and grab the clone
  8674. mutex_unlock(stgd_lock);
  8675. clone_available();
  8676. goto retry;
  8677. }
  8678. unstage_work(work);
  8679. /* Signal the getwork scheduler to look for more work */
  8680. pthread_cond_signal(&gws_cond);
  8681. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  8682. pthread_cond_signal(&getq->cond);
  8683. mutex_unlock(stgd_lock);
  8684. work->pool->last_work_time = time(NULL);
  8685. cgtime(&work->pool->tv_last_work_time);
  8686. return work;
  8687. }
  8688. /* Clones work by rolling it if possible, and returning a clone instead of the
  8689. * original work item which gets staged again to possibly be rolled again in
  8690. * the future */
  8691. static struct work *clone_work(struct work *work)
  8692. {
  8693. int mrs = mining_threads + opt_queue - total_staged();
  8694. struct work *work_clone;
  8695. bool cloned;
  8696. if (mrs < 1)
  8697. return work;
  8698. cloned = false;
  8699. work_clone = make_clone(work);
  8700. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  8701. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  8702. stage_work(work_clone);
  8703. roll_work(work);
  8704. work_clone = make_clone(work);
  8705. /* Roll it again to prevent duplicates should this be used
  8706. * directly later on */
  8707. roll_work(work);
  8708. cloned = true;
  8709. }
  8710. if (cloned) {
  8711. stage_work(work);
  8712. return work_clone;
  8713. }
  8714. free_work(work_clone);
  8715. return work;
  8716. }
  8717. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  8718. {
  8719. unsigned char hash1[32];
  8720. sha256(data, len, hash1);
  8721. sha256(hash1, 32, hash);
  8722. }
  8723. /* PDiff 1 is a 256 bit unsigned integer of
  8724. * 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  8725. * so we use a big endian 32 bit unsigned integer positioned at the Nth byte to
  8726. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  8727. static void pdiff_target_leadzero(void * const target_p, double diff)
  8728. {
  8729. uint8_t *target = target_p;
  8730. diff *= 0x100000000;
  8731. int skip = log2(diff) / 8;
  8732. if (skip)
  8733. {
  8734. if (skip > 0x1c)
  8735. skip = 0x1c;
  8736. diff /= pow(0x100, skip);
  8737. memset(target, 0, skip);
  8738. }
  8739. uint32_t n = 0xffffffff;
  8740. n = (double)n / diff;
  8741. n = htobe32(n);
  8742. memcpy(&target[skip], &n, sizeof(n));
  8743. memset(&target[skip + sizeof(n)], 0xff, 32 - (skip + sizeof(n)));
  8744. }
  8745. void set_target_to_pdiff(void * const dest_target, const double pdiff)
  8746. {
  8747. unsigned char rtarget[32];
  8748. pdiff_target_leadzero(rtarget, pdiff);
  8749. swab256(dest_target, rtarget);
  8750. if (opt_debug) {
  8751. char htarget[65];
  8752. bin2hex(htarget, rtarget, 32);
  8753. applog(LOG_DEBUG, "Generated target %s", htarget);
  8754. }
  8755. }
  8756. void set_target_to_bdiff(void * const dest_target, const double bdiff)
  8757. {
  8758. set_target_to_pdiff(dest_target, bdiff_to_pdiff(bdiff));
  8759. }
  8760. void _test_target(void * const funcp, const char * const funcname, const bool little_endian, const void * const expectp, const double diff)
  8761. {
  8762. uint8_t bufr[32], buf[32], expectr[32], expect[32];
  8763. int off;
  8764. void (*func)(void *, double) = funcp;
  8765. func(little_endian ? bufr : buf, diff);
  8766. if (little_endian)
  8767. swab256(buf, bufr);
  8768. swap32tobe(expect, expectp, 256/32);
  8769. // Fuzzy comparison: the first 32 bits set must match, and the actual target must be >= the expected
  8770. for (off = 0; off < 28 && !buf[off]; ++off)
  8771. {}
  8772. if (memcmp(&buf[off], &expect[off], 4))
  8773. {
  8774. testfail: ;
  8775. ++unittest_failures;
  8776. char hexbuf[65], expectbuf[65];
  8777. bin2hex(hexbuf, buf, 32);
  8778. bin2hex(expectbuf, expect, 32);
  8779. applogr(, LOG_WARNING, "%s test failed: diff %g got %s (expected %s)",
  8780. funcname, diff, hexbuf, expectbuf);
  8781. }
  8782. if (!little_endian)
  8783. swab256(bufr, buf);
  8784. swab256(expectr, expect);
  8785. if (!hash_target_check(expectr, bufr))
  8786. goto testfail;
  8787. }
  8788. #define TEST_TARGET(func, le, expect, diff) \
  8789. _test_target(func, #func, le, expect, diff)
  8790. void test_target()
  8791. {
  8792. uint32_t expect[8] = {0};
  8793. // bdiff 1 should be exactly 00000000ffff0000000006f29cfd29510a6caee84634e86a57257cf03152537f due to floating-point imprecision (pdiff1 / 1.0000152590218966)
  8794. expect[0] = 0x0000ffff;
  8795. TEST_TARGET(set_target_to_bdiff, true, expect, 1./0x10000);
  8796. expect[0] = 0;
  8797. expect[1] = 0xffff0000;
  8798. TEST_TARGET(set_target_to_bdiff, true, expect, 1);
  8799. expect[1] >>= 1;
  8800. TEST_TARGET(set_target_to_bdiff, true, expect, 2);
  8801. expect[1] >>= 3;
  8802. TEST_TARGET(set_target_to_bdiff, true, expect, 0x10);
  8803. expect[1] >>= 4;
  8804. TEST_TARGET(set_target_to_bdiff, true, expect, 0x100);
  8805. memset(&expect[1], '\xff', 28);
  8806. expect[0] = 0x0000ffff;
  8807. TEST_TARGET(set_target_to_pdiff, true, expect, 1./0x10000);
  8808. expect[0] = 0;
  8809. TEST_TARGET(set_target_to_pdiff, true, expect, 1);
  8810. expect[1] >>= 1;
  8811. TEST_TARGET(set_target_to_pdiff, true, expect, 2);
  8812. expect[1] >>= 3;
  8813. TEST_TARGET(set_target_to_pdiff, true, expect, 0x10);
  8814. expect[1] >>= 4;
  8815. TEST_TARGET(set_target_to_pdiff, true, expect, 0x100);
  8816. }
  8817. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  8818. {
  8819. *dst = *src;
  8820. if (dst->tr)
  8821. tmpl_incref(dst->tr);
  8822. dst->nonce1 = maybe_strdup(src->nonce1);
  8823. dst->job_id = maybe_strdup(src->job_id);
  8824. bytes_cpy(&dst->coinbase, &src->coinbase);
  8825. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  8826. }
  8827. void stratum_work_clean(struct stratum_work * const swork)
  8828. {
  8829. if (swork->tr)
  8830. tmpl_decref(swork->tr);
  8831. free(swork->nonce1);
  8832. free(swork->job_id);
  8833. bytes_free(&swork->coinbase);
  8834. bytes_free(&swork->merkle_bin);
  8835. }
  8836. bool pool_has_usable_swork(const struct pool * const pool)
  8837. {
  8838. if (opt_benchmark)
  8839. return true;
  8840. if (pool->swork.tr)
  8841. {
  8842. // GBT
  8843. struct timeval tv_now;
  8844. timer_set_now(&tv_now);
  8845. return blkmk_time_left(pool->swork.tr->tmpl, tv_now.tv_sec);
  8846. }
  8847. return pool->stratum_notify;
  8848. }
  8849. /* Generates stratum based work based on the most recent notify information
  8850. * from the pool. This will keep generating work while a pool is down so we use
  8851. * other means to detect when the pool has died in stratum_thread */
  8852. static void gen_stratum_work(struct pool *pool, struct work *work)
  8853. {
  8854. clean_work(work);
  8855. cg_wlock(&pool->data_lock);
  8856. pool->swork.data_lock_p = &pool->data_lock;
  8857. const int n2size = pool->swork.n2size;
  8858. bytes_resize(&work->nonce2, n2size);
  8859. if (pool->nonce2sz < n2size)
  8860. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, n2size - pool->nonce2sz);
  8861. memcpy(bytes_buf(&work->nonce2),
  8862. #ifdef WORDS_BIGENDIAN
  8863. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  8864. &((char*)&pool->nonce2)[pool->nonce2off],
  8865. #else
  8866. &pool->nonce2,
  8867. #endif
  8868. pool->nonce2sz);
  8869. pool->nonce2++;
  8870. work->pool = pool;
  8871. work->work_restart_id = pool->swork.work_restart_id;
  8872. gen_stratum_work2(work, &pool->swork);
  8873. cgtime(&work->tv_staged);
  8874. }
  8875. void gen_stratum_work2(struct work *work, struct stratum_work *swork)
  8876. {
  8877. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  8878. uint8_t *merkle_bin;
  8879. uint32_t *data32, *swap32;
  8880. int i;
  8881. /* Generate coinbase */
  8882. coinbase = bytes_buf(&swork->coinbase);
  8883. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8884. /* Downgrade to a read lock to read off the variables */
  8885. if (swork->data_lock_p)
  8886. cg_dwlock(swork->data_lock_p);
  8887. /* Generate merkle root */
  8888. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  8889. memcpy(merkle_sha, merkle_root, 32);
  8890. merkle_bin = bytes_buf(&swork->merkle_bin);
  8891. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  8892. memcpy(merkle_sha + 32, merkle_bin, 32);
  8893. gen_hash(merkle_sha, merkle_root, 64);
  8894. memcpy(merkle_sha, merkle_root, 32);
  8895. }
  8896. data32 = (uint32_t *)merkle_sha;
  8897. swap32 = (uint32_t *)merkle_root;
  8898. flip32(swap32, data32);
  8899. memcpy(&work->data[0], swork->header1, 36);
  8900. memcpy(&work->data[36], merkle_root, 32);
  8901. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  8902. memcpy(&work->data[72], swork->diffbits, 4);
  8903. memset(&work->data[76], 0, 4); // nonce
  8904. memcpy(&work->data[80], workpadding_bin, 48);
  8905. work->ntime_roll_limits = swork->ntime_roll_limits;
  8906. /* Copy parameters required for share submission */
  8907. memcpy(work->target, swork->target, sizeof(work->target));
  8908. work->job_id = maybe_strdup(swork->job_id);
  8909. work->nonce1 = maybe_strdup(swork->nonce1);
  8910. if (swork->data_lock_p)
  8911. cg_runlock(swork->data_lock_p);
  8912. if (opt_debug)
  8913. {
  8914. char header[161];
  8915. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  8916. bin2hex(header, work->data, 80);
  8917. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8918. applog(LOG_DEBUG, "Generated stratum header %s", header);
  8919. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  8920. }
  8921. calc_midstate(work);
  8922. local_work++;
  8923. work->stratum = true;
  8924. work->blk.nonce = 0;
  8925. work->id = total_work++;
  8926. work->longpoll = false;
  8927. work->getwork_mode = GETWORK_MODE_STRATUM;
  8928. calc_diff(work, 0);
  8929. }
  8930. void request_work(struct thr_info *thr)
  8931. {
  8932. struct cgpu_info *cgpu = thr->cgpu;
  8933. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8934. /* Tell the watchdog thread this thread is waiting on getwork and
  8935. * should not be restarted */
  8936. thread_reportout(thr);
  8937. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  8938. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8939. {
  8940. if (proc->threads)
  8941. break;
  8942. thread_reportout(proc->thr[0]);
  8943. }
  8944. cgtime(&dev_stats->_get_start);
  8945. }
  8946. // FIXME: Make this non-blocking (and remove HACK above)
  8947. struct work *get_work(struct thr_info *thr)
  8948. {
  8949. const int thr_id = thr->id;
  8950. struct cgpu_info *cgpu = thr->cgpu;
  8951. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8952. struct cgminer_stats *pool_stats;
  8953. struct timeval tv_get;
  8954. struct work *work = NULL;
  8955. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  8956. while (!work) {
  8957. work = hash_pop(cgpu);
  8958. if (stale_work(work, false)) {
  8959. staged_full = false; // It wasn't really full, since it was stale :(
  8960. discard_work(work);
  8961. work = NULL;
  8962. wake_gws();
  8963. }
  8964. }
  8965. last_getwork = time(NULL);
  8966. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  8967. cgpu->proc_repr, work->id, thr_id);
  8968. work->thr_id = thr_id;
  8969. thread_reportin(thr);
  8970. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  8971. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8972. {
  8973. if (proc->threads)
  8974. break;
  8975. thread_reportin(proc->thr[0]);
  8976. }
  8977. work->mined = true;
  8978. work->blk.nonce = 0;
  8979. cgtime(&tv_get);
  8980. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  8981. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  8982. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  8983. dev_stats->getwork_wait_max = tv_get;
  8984. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  8985. dev_stats->getwork_wait_min = tv_get;
  8986. ++dev_stats->getwork_calls;
  8987. pool_stats = &(work->pool->cgminer_stats);
  8988. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  8989. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  8990. pool_stats->getwork_wait_max = tv_get;
  8991. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  8992. pool_stats->getwork_wait_min = tv_get;
  8993. ++pool_stats->getwork_calls;
  8994. if (work->work_difficulty < 1)
  8995. {
  8996. const float min_nonce_diff = drv_min_nonce_diff(cgpu->drv, cgpu, work_mining_algorithm(work));
  8997. if (unlikely(work->work_difficulty < min_nonce_diff))
  8998. {
  8999. if (min_nonce_diff - work->work_difficulty > 1./0x10000000)
  9000. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  9001. cgpu->proc_repr);
  9002. work->nonce_diff = min_nonce_diff;
  9003. }
  9004. else
  9005. work->nonce_diff = work->work_difficulty;
  9006. }
  9007. else
  9008. work->nonce_diff = 1;
  9009. return work;
  9010. }
  9011. struct dupe_hash_elem {
  9012. uint8_t hash[0x20];
  9013. struct timeval tv_prune;
  9014. UT_hash_handle hh;
  9015. };
  9016. static
  9017. void _submit_work_async(struct work *work)
  9018. {
  9019. applog(LOG_DEBUG, "Pushing submit work to work thread");
  9020. if (opt_benchmark)
  9021. {
  9022. json_t * const jn = json_null(), *result = NULL;
  9023. work_check_for_block(work);
  9024. {
  9025. static struct dupe_hash_elem *dupe_hashes;
  9026. struct dupe_hash_elem *dhe, *dhetmp;
  9027. HASH_FIND(hh, dupe_hashes, &work->hash, sizeof(dhe->hash), dhe);
  9028. if (dhe)
  9029. result = json_string("duplicate");
  9030. else
  9031. {
  9032. struct timeval tv_now;
  9033. timer_set_now(&tv_now);
  9034. // Prune old entries
  9035. HASH_ITER(hh, dupe_hashes, dhe, dhetmp)
  9036. {
  9037. if (!timer_passed(&dhe->tv_prune, &tv_now))
  9038. break;
  9039. HASH_DEL(dupe_hashes, dhe);
  9040. free(dhe);
  9041. }
  9042. dhe = malloc(sizeof(*dhe));
  9043. memcpy(dhe->hash, work->hash, sizeof(dhe->hash));
  9044. timer_set_delay(&dhe->tv_prune, &tv_now, 337500000);
  9045. HASH_ADD(hh, dupe_hashes, hash, sizeof(dhe->hash), dhe);
  9046. }
  9047. }
  9048. if (result)
  9049. {}
  9050. else
  9051. if (stale_work(work, true))
  9052. {
  9053. char stalemsg[0x10];
  9054. snprintf(stalemsg, sizeof(stalemsg), "stale %us", benchmark_update_interval * (work->pool->work_restart_id - work->work_restart_id));
  9055. result = json_string(stalemsg);
  9056. }
  9057. else
  9058. result = json_incref(jn);
  9059. share_result(jn, result, jn, work, false, "");
  9060. free_work(work);
  9061. json_decref(result);
  9062. json_decref(jn);
  9063. return;
  9064. }
  9065. mutex_lock(&submitting_lock);
  9066. ++total_submitting;
  9067. DL_APPEND(submit_waiting, work);
  9068. mutex_unlock(&submitting_lock);
  9069. notifier_wake(submit_waiting_notifier);
  9070. }
  9071. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  9072. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  9073. {
  9074. if (tv_work_found)
  9075. copy_time(&work->tv_work_found, tv_work_found);
  9076. _submit_work_async(work);
  9077. }
  9078. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  9079. {
  9080. struct cgpu_info * const cgpu = thr->cgpu;
  9081. if (bad_nonce_p)
  9082. {
  9083. if (bad_nonce_p == UNKNOWN_NONCE)
  9084. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  9085. cgpu->proc_repr);
  9086. else
  9087. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  9088. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  9089. }
  9090. mutex_lock(&stats_lock);
  9091. hw_errors++;
  9092. ++cgpu->hw_errors;
  9093. if (bad_nonce_p)
  9094. {
  9095. total_bad_diff1 += nonce_diff;
  9096. cgpu->bad_diff1 += nonce_diff;
  9097. }
  9098. mutex_unlock(&stats_lock);
  9099. if (thr->cgpu->drv->hw_error)
  9100. thr->cgpu->drv->hw_error(thr);
  9101. }
  9102. void work_hash(struct work * const work)
  9103. {
  9104. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  9105. malgo->hash_data_f(work->hash, work->data);
  9106. }
  9107. static
  9108. bool test_hash(const void * const phash, const float diff)
  9109. {
  9110. const uint32_t * const hash = phash;
  9111. if (diff >= 1.)
  9112. // FIXME: > 1 should check more
  9113. return !hash[7];
  9114. const uint32_t Htarg = (uint32_t)ceil((1. / diff) - 1);
  9115. const uint32_t tmp_hash7 = le32toh(hash[7]);
  9116. applog(LOG_DEBUG, "htarget %08lx hash %08lx",
  9117. (long unsigned int)Htarg,
  9118. (long unsigned int)tmp_hash7);
  9119. return (tmp_hash7 <= Htarg);
  9120. }
  9121. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  9122. {
  9123. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  9124. *work_nonce = htole32(nonce);
  9125. work_hash(work);
  9126. if (!test_hash(work->hash, work->nonce_diff))
  9127. return TNR_BAD;
  9128. if (checktarget && !hash_target_check_v(work->hash, work->target))
  9129. {
  9130. bool high_hash = true;
  9131. struct pool * const pool = work->pool;
  9132. if (pool->stratum_active)
  9133. {
  9134. // 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
  9135. if (memcmp(pool->next_target, work->target, sizeof(work->target)))
  9136. {
  9137. applog(LOG_DEBUG, "Stratum pool %u target has changed since work job issued, checking that too",
  9138. pool->pool_no);
  9139. if (hash_target_check_v(work->hash, pool->next_target))
  9140. high_hash = false;
  9141. }
  9142. }
  9143. if (high_hash)
  9144. return TNR_HIGH;
  9145. }
  9146. return TNR_GOOD;
  9147. }
  9148. /* Returns true if nonce for work was a valid share */
  9149. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  9150. {
  9151. return submit_noffset_nonce(thr, work, nonce, 0);
  9152. }
  9153. /* Allows drivers to submit work items where the driver has changed the ntime
  9154. * value by noffset. Must be only used with a work protocol that does not ntime
  9155. * roll itself intrinsically to generate work (eg stratum). We do not touch
  9156. * the original work struct, but the copy of it only. */
  9157. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  9158. int noffset)
  9159. {
  9160. struct work *work = make_work();
  9161. _copy_work(work, work_in, noffset);
  9162. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  9163. struct timeval tv_work_found;
  9164. enum test_nonce2_result res;
  9165. bool ret = true;
  9166. thread_reportout(thr);
  9167. cgtime(&tv_work_found);
  9168. *work_nonce = htole32(nonce);
  9169. work->thr_id = thr->id;
  9170. /* Do one last check before attempting to submit the work */
  9171. /* Side effect: sets work->data and work->hash for us */
  9172. res = test_nonce2(work, nonce);
  9173. if (unlikely(res == TNR_BAD))
  9174. {
  9175. inc_hw_errors(thr, work, nonce);
  9176. ret = false;
  9177. goto out;
  9178. }
  9179. mutex_lock(&stats_lock);
  9180. total_diff1 += work->nonce_diff;
  9181. thr ->cgpu->diff1 += work->nonce_diff;
  9182. work->pool->diff1 += work->nonce_diff;
  9183. thr->cgpu->last_device_valid_work = time(NULL);
  9184. mutex_unlock(&stats_lock);
  9185. if (noncelog_file)
  9186. noncelog(work);
  9187. if (res == TNR_HIGH)
  9188. {
  9189. // Share above target, normal
  9190. /* Check the diff of the share, even if it didn't reach the
  9191. * target, just to set the best share value if it's higher. */
  9192. share_diff(work);
  9193. goto out;
  9194. }
  9195. submit_work_async2(work, &tv_work_found);
  9196. work = NULL; // Taken by submit_work_async2
  9197. out:
  9198. if (work)
  9199. free_work(work);
  9200. thread_reportin(thr);
  9201. return ret;
  9202. }
  9203. // return true of we should stop working on this piece of work
  9204. // returning false means we will keep scanning for a nonce
  9205. // assumptions: work->blk.nonce is the number of nonces completed in the work
  9206. // see minerloop_scanhash comments for more details & usage
  9207. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t max_hashes)
  9208. {
  9209. if (work->blk.nonce == 0xffffffff || // known we are scanning a full nonce range
  9210. wdiff->tv_sec > opt_scantime || // scan-time has elapsed (user specified, default 60s)
  9211. work->blk.nonce >= 0xfffffffe - max_hashes || // are there enough nonces left in the work
  9212. max_hashes >= 0xfffffffe || // assume we are scanning a full nonce range
  9213. stale_work(work, false)) // work is stale
  9214. return true;
  9215. return false;
  9216. }
  9217. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  9218. {
  9219. struct cgpu_info *proc = thr->cgpu;
  9220. if (proc->threads > 1)
  9221. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  9222. else
  9223. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  9224. }
  9225. // Called by asynchronous minerloops, when they find their processor should be disabled
  9226. void mt_disable_start(struct thr_info *mythr)
  9227. {
  9228. struct cgpu_info *cgpu = mythr->cgpu;
  9229. struct device_drv *drv = cgpu->drv;
  9230. if (drv->thread_disable)
  9231. drv->thread_disable(mythr);
  9232. hashmeter2(mythr);
  9233. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  9234. mythr->rolling = mythr->cgpu->rolling = 0;
  9235. thread_reportout(mythr);
  9236. mythr->_mt_disable_called = true;
  9237. }
  9238. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  9239. * the driver tells us it's full so that it may extract the work item using
  9240. * the get_queued() function which adds it to the hashtable on
  9241. * cgpu->queued_work. */
  9242. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  9243. {
  9244. thread_reportout(mythr);
  9245. do {
  9246. bool need_work;
  9247. /* Do this lockless just to know if we need more unqueued work. */
  9248. need_work = (!cgpu->unqueued_work);
  9249. /* get_work is a blocking function so do it outside of lock
  9250. * to prevent deadlocks with other locks. */
  9251. if (need_work) {
  9252. struct work *work = get_work(mythr);
  9253. wr_lock(&cgpu->qlock);
  9254. /* Check we haven't grabbed work somehow between
  9255. * checking and picking up the lock. */
  9256. if (likely(!cgpu->unqueued_work))
  9257. cgpu->unqueued_work = work;
  9258. else
  9259. need_work = false;
  9260. wr_unlock(&cgpu->qlock);
  9261. if (unlikely(!need_work))
  9262. discard_work(work);
  9263. }
  9264. /* The queue_full function should be used by the driver to
  9265. * actually place work items on the physical device if it
  9266. * does have a queue. */
  9267. } while (drv->queue_full && !drv->queue_full(cgpu));
  9268. }
  9269. /* Add a work item to a cgpu's queued hashlist */
  9270. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  9271. {
  9272. cgpu->queued_count++;
  9273. HASH_ADD_INT(cgpu->queued_work, id, work);
  9274. }
  9275. /* This function is for retrieving one work item from the unqueued pointer and
  9276. * adding it to the hashtable of queued work. Code using this function must be
  9277. * able to handle NULL as a return which implies there is no work available. */
  9278. struct work *get_queued(struct cgpu_info *cgpu)
  9279. {
  9280. struct work *work = NULL;
  9281. wr_lock(&cgpu->qlock);
  9282. if (cgpu->unqueued_work) {
  9283. work = cgpu->unqueued_work;
  9284. if (unlikely(stale_work(work, false))) {
  9285. discard_work(work);
  9286. work = NULL;
  9287. wake_gws();
  9288. } else
  9289. __add_queued(cgpu, work);
  9290. cgpu->unqueued_work = NULL;
  9291. }
  9292. wr_unlock(&cgpu->qlock);
  9293. return work;
  9294. }
  9295. void add_queued(struct cgpu_info *cgpu, struct work *work)
  9296. {
  9297. wr_lock(&cgpu->qlock);
  9298. __add_queued(cgpu, work);
  9299. wr_unlock(&cgpu->qlock);
  9300. }
  9301. /* Get fresh work and add it to cgpu's queued hashlist */
  9302. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  9303. {
  9304. struct work *work = get_work(thr);
  9305. add_queued(cgpu, work);
  9306. return work;
  9307. }
  9308. /* This function is for finding an already queued work item in the
  9309. * given que hashtable. Code using this function must be able
  9310. * to handle NULL as a return which implies there is no matching work.
  9311. * The calling function must lock access to the que if it is required.
  9312. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9313. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9314. {
  9315. struct work *work, *tmp, *ret = NULL;
  9316. HASH_ITER(hh, que, work, tmp) {
  9317. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  9318. memcmp(work->data + offset, data, datalen) == 0) {
  9319. ret = work;
  9320. break;
  9321. }
  9322. }
  9323. return ret;
  9324. }
  9325. /* This function is for finding an already queued work item in the
  9326. * device's queued_work hashtable. Code using this function must be able
  9327. * to handle NULL as a return which implies there is no matching work.
  9328. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9329. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9330. {
  9331. struct work *ret;
  9332. rd_lock(&cgpu->qlock);
  9333. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9334. rd_unlock(&cgpu->qlock);
  9335. return ret;
  9336. }
  9337. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9338. {
  9339. struct work *work, *ret = NULL;
  9340. rd_lock(&cgpu->qlock);
  9341. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9342. if (work)
  9343. ret = copy_work(work);
  9344. rd_unlock(&cgpu->qlock);
  9345. return ret;
  9346. }
  9347. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  9348. {
  9349. cgpu->queued_count--;
  9350. HASH_DEL(cgpu->queued_work, work);
  9351. }
  9352. /* This iterates over a queued hashlist finding work started more than secs
  9353. * seconds ago and discards the work as completed. The driver must set the
  9354. * work->tv_work_start value appropriately. Returns the number of items aged. */
  9355. int age_queued_work(struct cgpu_info *cgpu, double secs)
  9356. {
  9357. struct work *work, *tmp;
  9358. struct timeval tv_now;
  9359. int aged = 0;
  9360. cgtime(&tv_now);
  9361. wr_lock(&cgpu->qlock);
  9362. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  9363. if (tdiff(&tv_now, &work->tv_work_start) > secs) {
  9364. __work_completed(cgpu, work);
  9365. aged++;
  9366. }
  9367. }
  9368. wr_unlock(&cgpu->qlock);
  9369. return aged;
  9370. }
  9371. /* This function should be used by queued device drivers when they're sure
  9372. * the work struct is no longer in use. */
  9373. void work_completed(struct cgpu_info *cgpu, struct work *work)
  9374. {
  9375. wr_lock(&cgpu->qlock);
  9376. __work_completed(cgpu, work);
  9377. wr_unlock(&cgpu->qlock);
  9378. free_work(work);
  9379. }
  9380. /* Combines find_queued_work_bymidstate and work_completed in one function
  9381. * withOUT destroying the work so the driver must free it. */
  9382. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9383. {
  9384. struct work *work;
  9385. wr_lock(&cgpu->qlock);
  9386. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9387. if (work)
  9388. __work_completed(cgpu, work);
  9389. wr_unlock(&cgpu->qlock);
  9390. return work;
  9391. }
  9392. void flush_queue(struct cgpu_info *cgpu)
  9393. {
  9394. struct work *work = NULL;
  9395. wr_lock(&cgpu->qlock);
  9396. work = cgpu->unqueued_work;
  9397. cgpu->unqueued_work = NULL;
  9398. wr_unlock(&cgpu->qlock);
  9399. if (work) {
  9400. free_work(work);
  9401. applog(LOG_DEBUG, "Discarded queued work item");
  9402. }
  9403. }
  9404. /* This version of hash work is for devices that are fast enough to always
  9405. * perform a full nonce range and need a queue to maintain the device busy.
  9406. * Work creation and destruction is not done from within this function
  9407. * directly. */
  9408. void hash_queued_work(struct thr_info *mythr)
  9409. {
  9410. const long cycle = opt_log_interval / 5 ? : 1;
  9411. struct timeval tv_start = {0, 0}, tv_end;
  9412. struct cgpu_info *cgpu = mythr->cgpu;
  9413. struct device_drv *drv = cgpu->drv;
  9414. const int thr_id = mythr->id;
  9415. int64_t hashes_done = 0;
  9416. if (unlikely(cgpu->deven != DEV_ENABLED))
  9417. mt_disable(mythr);
  9418. while (likely(!cgpu->shutdown)) {
  9419. struct timeval diff;
  9420. int64_t hashes;
  9421. fill_queue(mythr, cgpu, drv, thr_id);
  9422. thread_reportin(mythr);
  9423. hashes = drv->scanwork(mythr);
  9424. /* Reset the bool here in case the driver looks for it
  9425. * synchronously in the scanwork loop. */
  9426. mythr->work_restart = false;
  9427. if (unlikely(hashes == -1 )) {
  9428. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  9429. cgpu->deven = DEV_DISABLED;
  9430. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  9431. mt_disable(mythr);
  9432. }
  9433. hashes_done += hashes;
  9434. cgtime(&tv_end);
  9435. timersub(&tv_end, &tv_start, &diff);
  9436. if (diff.tv_sec >= cycle) {
  9437. hashmeter(thr_id, &diff, hashes_done);
  9438. hashes_done = 0;
  9439. copy_time(&tv_start, &tv_end);
  9440. }
  9441. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  9442. mt_disable(mythr);
  9443. if (unlikely(mythr->work_restart)) {
  9444. flush_queue(cgpu);
  9445. if (drv->flush_work)
  9446. drv->flush_work(cgpu);
  9447. }
  9448. }
  9449. // cgpu->deven = DEV_DISABLED; set in miner_thread
  9450. }
  9451. // Called by minerloop, when it is re-enabling a processor
  9452. void mt_disable_finish(struct thr_info *mythr)
  9453. {
  9454. struct device_drv *drv = mythr->cgpu->drv;
  9455. thread_reportin(mythr);
  9456. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  9457. if (drv->thread_enable)
  9458. drv->thread_enable(mythr);
  9459. mythr->_mt_disable_called = false;
  9460. }
  9461. // Called by synchronous minerloops, when they find their processor should be disabled
  9462. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  9463. void mt_disable(struct thr_info *mythr)
  9464. {
  9465. const struct cgpu_info * const cgpu = mythr->cgpu;
  9466. mt_disable_start(mythr);
  9467. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  9468. do {
  9469. notifier_read(mythr->notifier);
  9470. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  9471. mt_disable_finish(mythr);
  9472. }
  9473. enum {
  9474. STAT_SLEEP_INTERVAL = 1,
  9475. STAT_CTR_INTERVAL = 10000000,
  9476. FAILURE_INTERVAL = 30,
  9477. };
  9478. /* Stage another work item from the work returned in a longpoll */
  9479. 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)
  9480. {
  9481. bool rc;
  9482. work->rolltime = rolltime;
  9483. rc = work_decode(pool, work, val);
  9484. if (unlikely(!rc)) {
  9485. applog(LOG_ERR, "Could not convert longpoll data to work");
  9486. free_work(work);
  9487. return;
  9488. }
  9489. total_getworks++;
  9490. pool->getwork_requested++;
  9491. work->pool = pool;
  9492. copy_time(&work->tv_getwork, tv_lp);
  9493. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  9494. calc_diff(work, 0);
  9495. if (pool->enabled == POOL_REJECTING)
  9496. work->mandatory = true;
  9497. work->longpoll = true;
  9498. work->getwork_mode = GETWORK_MODE_LP;
  9499. update_last_work(work);
  9500. /* We'll be checking this work item twice, but we already know it's
  9501. * from a new block so explicitly force the new block detection now
  9502. * rather than waiting for it to hit the stage thread. This also
  9503. * allows testwork to know whether LP discovered the block or not. */
  9504. test_work_current(work);
  9505. /* Don't use backup LPs as work if we have failover-only enabled. Use
  9506. * the longpoll work from a pool that has been rejecting shares as a
  9507. * way to detect when the pool has recovered.
  9508. */
  9509. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  9510. free_work(work);
  9511. return;
  9512. }
  9513. work = clone_work(work);
  9514. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  9515. stage_work(work);
  9516. applog(LOG_DEBUG, "Converted longpoll data to work");
  9517. }
  9518. /* If we want longpoll, enable it for the chosen default pool, or, if
  9519. * the pool does not support longpoll, find the first one that does
  9520. * and use its longpoll support */
  9521. static
  9522. struct pool *_select_longpoll_pool(struct pool *cp, bool(*func)(struct pool *))
  9523. {
  9524. int i;
  9525. if (func(cp))
  9526. return cp;
  9527. for (i = 0; i < total_pools; i++) {
  9528. struct pool *pool = pools[i];
  9529. if (cp->goal != pool->goal)
  9530. continue;
  9531. if (func(pool))
  9532. return pool;
  9533. }
  9534. return NULL;
  9535. }
  9536. /* This will make the longpoll thread wait till it's the current pool, or it
  9537. * has been flagged as rejecting, before attempting to open any connections.
  9538. */
  9539. static void wait_lpcurrent(struct pool *pool)
  9540. {
  9541. mutex_lock(&lp_lock);
  9542. while (!cnx_needed(pool))
  9543. {
  9544. pool->lp_active = false;
  9545. pthread_cond_wait(&lp_cond, &lp_lock);
  9546. }
  9547. mutex_unlock(&lp_lock);
  9548. }
  9549. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  9550. struct pool *pool = vpool;
  9551. curl_socket_t sock = bfg_socket(addr->family, addr->socktype, addr->protocol);
  9552. pool->lp_socket = sock;
  9553. return sock;
  9554. }
  9555. static void *longpoll_thread(void *userdata)
  9556. {
  9557. struct pool *cp = (struct pool *)userdata;
  9558. /* This *pool is the source of the actual longpoll, not the pool we've
  9559. * tied it to */
  9560. struct timeval start, reply, end;
  9561. struct pool *pool = NULL;
  9562. char threadname[20];
  9563. CURL *curl = NULL;
  9564. int failures = 0;
  9565. char *lp_url;
  9566. int rolltime;
  9567. #ifndef HAVE_PTHREAD_CANCEL
  9568. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9569. #endif
  9570. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  9571. RenameThread(threadname);
  9572. curl = curl_easy_init();
  9573. if (unlikely(!curl)) {
  9574. applog(LOG_ERR, "CURL initialisation failed");
  9575. return NULL;
  9576. }
  9577. retry_pool:
  9578. pool = select_longpoll_pool(cp);
  9579. if (!pool) {
  9580. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  9581. while (!pool) {
  9582. cgsleep_ms(60000);
  9583. pool = select_longpoll_pool(cp);
  9584. }
  9585. }
  9586. if (pool->has_stratum) {
  9587. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9588. cp->rpc_url, pool->rpc_url);
  9589. goto out;
  9590. }
  9591. /* Any longpoll from any pool is enough for this to be true */
  9592. pool->goal->have_longpoll = true;
  9593. wait_lpcurrent(cp);
  9594. {
  9595. lp_url = pool->lp_url;
  9596. if (cp == pool)
  9597. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  9598. else
  9599. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  9600. }
  9601. while (42) {
  9602. json_t *val, *soval;
  9603. struct work *work = make_work();
  9604. char *lpreq;
  9605. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id, pool);
  9606. work->pool = pool;
  9607. if (!lpreq)
  9608. {
  9609. free_work(work);
  9610. goto lpfail;
  9611. }
  9612. wait_lpcurrent(cp);
  9613. cgtime(&start);
  9614. /* Longpoll connections can be persistent for a very long time
  9615. * and any number of issues could have come up in the meantime
  9616. * so always establish a fresh connection instead of relying on
  9617. * a persistent one. */
  9618. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  9619. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  9620. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  9621. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  9622. lpreq, false, true, &rolltime, pool, false);
  9623. pool->lp_socket = CURL_SOCKET_BAD;
  9624. cgtime(&reply);
  9625. free(lpreq);
  9626. if (likely(val)) {
  9627. soval = json_object_get(json_object_get(val, "result"), "submitold");
  9628. if (soval)
  9629. pool->submit_old = json_is_true(soval);
  9630. else
  9631. pool->submit_old = false;
  9632. convert_to_work(val, rolltime, pool, work, &start, &reply);
  9633. failures = 0;
  9634. json_decref(val);
  9635. } else {
  9636. /* Some pools regularly drop the longpoll request so
  9637. * only see this as longpoll failure if it happens
  9638. * immediately and just restart it the rest of the
  9639. * time. */
  9640. cgtime(&end);
  9641. free_work(work);
  9642. if (end.tv_sec - start.tv_sec <= 30)
  9643. {
  9644. if (failures == 1)
  9645. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  9646. lpfail:
  9647. cgsleep_ms(30000);
  9648. }
  9649. }
  9650. if (pool != cp) {
  9651. pool = select_longpoll_pool(cp);
  9652. if (pool->has_stratum) {
  9653. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9654. cp->rpc_url, pool->rpc_url);
  9655. break;
  9656. }
  9657. if (unlikely(!pool))
  9658. goto retry_pool;
  9659. }
  9660. if (unlikely(pool->removed))
  9661. break;
  9662. }
  9663. out:
  9664. pool->lp_active = false;
  9665. curl_easy_cleanup(curl);
  9666. return NULL;
  9667. }
  9668. static void stop_longpoll(void)
  9669. {
  9670. int i;
  9671. want_longpoll = false;
  9672. for (i = 0; i < total_pools; ++i)
  9673. {
  9674. struct pool *pool = pools[i];
  9675. if (unlikely(!pool->lp_started))
  9676. continue;
  9677. pool->lp_started = false;
  9678. pthread_cancel(pool->longpoll_thread);
  9679. }
  9680. struct mining_goal_info *goal, *tmpgoal;
  9681. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  9682. {
  9683. goal->have_longpoll = false;
  9684. }
  9685. }
  9686. static void start_longpoll(void)
  9687. {
  9688. int i;
  9689. want_longpoll = true;
  9690. for (i = 0; i < total_pools; ++i)
  9691. {
  9692. struct pool *pool = pools[i];
  9693. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  9694. continue;
  9695. pool->lp_started = true;
  9696. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  9697. quit(1, "Failed to create pool longpoll thread");
  9698. }
  9699. }
  9700. void reinit_device(struct cgpu_info *cgpu)
  9701. {
  9702. if (cgpu->drv->reinit_device)
  9703. cgpu->drv->reinit_device(cgpu);
  9704. }
  9705. static struct timeval rotate_tv;
  9706. /* We reap curls if they are unused for over a minute */
  9707. static void reap_curl(struct pool *pool)
  9708. {
  9709. struct curl_ent *ent, *iter;
  9710. struct timeval now;
  9711. int reaped = 0;
  9712. cgtime(&now);
  9713. mutex_lock(&pool->pool_lock);
  9714. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  9715. if (pool->curls < 2)
  9716. break;
  9717. if (now.tv_sec - ent->tv.tv_sec > 300) {
  9718. reaped++;
  9719. pool->curls--;
  9720. LL_DELETE(pool->curllist, ent);
  9721. curl_easy_cleanup(ent->curl);
  9722. free(ent);
  9723. }
  9724. }
  9725. mutex_unlock(&pool->pool_lock);
  9726. if (reaped)
  9727. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  9728. }
  9729. static void *watchpool_thread(void __maybe_unused *userdata)
  9730. {
  9731. int intervals = 0;
  9732. #ifndef HAVE_PTHREAD_CANCEL
  9733. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9734. #endif
  9735. RenameThread("watchpool");
  9736. while (42) {
  9737. struct timeval now;
  9738. int i;
  9739. if (++intervals > 20)
  9740. intervals = 0;
  9741. cgtime(&now);
  9742. for (i = 0; i < total_pools; i++) {
  9743. struct pool *pool = pools[i];
  9744. if (!opt_benchmark)
  9745. reap_curl(pool);
  9746. /* Get a rolling utility per pool over 10 mins */
  9747. if (intervals > 19) {
  9748. int shares = pool->diff1 - pool->last_shares;
  9749. pool->last_shares = pool->diff1;
  9750. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  9751. pool->shares = pool->utility;
  9752. }
  9753. if (pool->enabled == POOL_DISABLED)
  9754. continue;
  9755. /* Don't start testing any pools if the test threads
  9756. * from startup are still doing their first attempt. */
  9757. if (unlikely(pool->testing)) {
  9758. pthread_join(pool->test_thread, NULL);
  9759. }
  9760. /* Test pool is idle once every minute */
  9761. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  9762. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  9763. pool_resus(pool);
  9764. }
  9765. /* Only switch pools if the failback pool has been
  9766. * alive for more than 5 minutes (default) to prevent
  9767. * intermittently failing pools from being used. */
  9768. 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)
  9769. {
  9770. if (opt_fail_switch_delay % 60)
  9771. applog(LOG_WARNING, "Pool %d %s stable for %d second%s",
  9772. pool->pool_no, pool->rpc_url,
  9773. opt_fail_switch_delay,
  9774. (opt_fail_switch_delay == 1 ? "" : "s"));
  9775. else
  9776. applog(LOG_WARNING, "Pool %d %s stable for %d minute%s",
  9777. pool->pool_no, pool->rpc_url,
  9778. opt_fail_switch_delay / 60,
  9779. (opt_fail_switch_delay == 60 ? "" : "s"));
  9780. switch_pools(NULL);
  9781. }
  9782. }
  9783. if (current_pool()->idle)
  9784. switch_pools(NULL);
  9785. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  9786. cgtime(&rotate_tv);
  9787. switch_pools(NULL);
  9788. }
  9789. cgsleep_ms(30000);
  9790. }
  9791. return NULL;
  9792. }
  9793. void mt_enable(struct thr_info *thr)
  9794. {
  9795. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  9796. notifier_wake(thr->notifier);
  9797. }
  9798. void proc_enable(struct cgpu_info *cgpu)
  9799. {
  9800. int j;
  9801. cgpu->deven = DEV_ENABLED;
  9802. for (j = cgpu->threads ?: 1; j--; )
  9803. mt_enable(cgpu->thr[j]);
  9804. }
  9805. #define device_recovered(cgpu) proc_enable(cgpu)
  9806. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  9807. {
  9808. struct string_elist *setstr_elist;
  9809. const char *p, *p2;
  9810. char replybuf[0x2000];
  9811. size_t L;
  9812. DL_FOREACH(opt_set_device_list, setstr_elist)
  9813. {
  9814. const char * const setstr = setstr_elist->string;
  9815. p = strchr(setstr, ':');
  9816. if (!p)
  9817. p = setstr;
  9818. {
  9819. L = p - setstr;
  9820. char pattern[L + 1];
  9821. if (L)
  9822. memcpy(pattern, setstr, L);
  9823. pattern[L] = '\0';
  9824. if (!cgpu_match(pattern, cgpu))
  9825. continue;
  9826. }
  9827. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  9828. cgpu->proc_repr, __func__, setstr);
  9829. if (p[0] == ':')
  9830. ++p;
  9831. p2 = strchr(p, '=');
  9832. if (!p2)
  9833. {
  9834. L = strlen(p);
  9835. p2 = "";
  9836. }
  9837. else
  9838. {
  9839. L = p2 - p;
  9840. ++p2;
  9841. }
  9842. char opt[L + 1];
  9843. if (L)
  9844. memcpy(opt, p, L);
  9845. opt[L] = '\0';
  9846. L = strlen(p2);
  9847. char setval[L + 1];
  9848. if (L)
  9849. memcpy(setval, p2, L);
  9850. setval[L] = '\0';
  9851. enum bfg_set_device_replytype success;
  9852. p = proc_set_device(cgpu, opt, setval, replybuf, &success);
  9853. switch (success)
  9854. {
  9855. case SDR_OK:
  9856. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s%s%s",
  9857. cgpu->proc_repr, setstr,
  9858. p ? ": " : "", p ?: "");
  9859. break;
  9860. case SDR_ERR:
  9861. case SDR_HELP:
  9862. case SDR_UNKNOWN:
  9863. applog(LOG_DEBUG, "%"PRIpreprv": Applying rule %s: %s",
  9864. cgpu->proc_repr, setstr, p);
  9865. break;
  9866. case SDR_AUTO:
  9867. case SDR_NOSUPP:
  9868. applog(LOG_DEBUG, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  9869. cgpu->proc_repr, setstr);
  9870. }
  9871. }
  9872. cgpu->already_set_defaults = true;
  9873. }
  9874. 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)
  9875. {
  9876. struct device_drv dummy_drv = *drv;
  9877. struct cgpu_info dummy_cgpu = {
  9878. .drv = &dummy_drv,
  9879. .device = &dummy_cgpu,
  9880. .device_id = -1,
  9881. .proc_id = -1,
  9882. .device_data = userp,
  9883. .device_path = devpath,
  9884. .dev_serial = serial,
  9885. };
  9886. strcpy(dummy_cgpu.proc_repr, drv->name);
  9887. switch (mode)
  9888. {
  9889. case 0:
  9890. dummy_drv.set_device = datap;
  9891. break;
  9892. case 1:
  9893. dummy_drv.set_device = NULL;
  9894. dummy_cgpu.set_device_funcs = datap;
  9895. break;
  9896. }
  9897. cgpu_set_defaults(&dummy_cgpu);
  9898. }
  9899. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  9900. * the screen at regular intervals, and restarts threads if they appear to have
  9901. * died. */
  9902. #define WATCHDOG_SICK_TIME 60
  9903. #define WATCHDOG_DEAD_TIME 600
  9904. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  9905. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  9906. static void *watchdog_thread(void __maybe_unused *userdata)
  9907. {
  9908. const unsigned int interval = WATCHDOG_INTERVAL;
  9909. struct timeval zero_tv;
  9910. #ifndef HAVE_PTHREAD_CANCEL
  9911. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9912. #endif
  9913. RenameThread("watchdog");
  9914. memset(&zero_tv, 0, sizeof(struct timeval));
  9915. cgtime(&rotate_tv);
  9916. while (1) {
  9917. int i;
  9918. struct timeval now;
  9919. sleep(interval);
  9920. discard_stale();
  9921. hashmeter(-1, &zero_tv, 0);
  9922. #ifdef HAVE_CURSES
  9923. const int ts = total_staged();
  9924. if (curses_active_locked()) {
  9925. change_logwinsize();
  9926. curses_print_status(ts);
  9927. _refresh_devstatus(true);
  9928. touchwin(logwin);
  9929. wrefresh(logwin);
  9930. unlock_curses();
  9931. }
  9932. #endif
  9933. cgtime(&now);
  9934. if (!sched_paused && !should_run()) {
  9935. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  9936. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9937. if (!schedstart.enable) {
  9938. quit(0, "Terminating execution as planned");
  9939. break;
  9940. }
  9941. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  9942. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  9943. sched_paused = true;
  9944. rd_lock(&mining_thr_lock);
  9945. for (i = 0; i < mining_threads; i++)
  9946. mining_thr[i]->pause = true;
  9947. rd_unlock(&mining_thr_lock);
  9948. } else if (sched_paused && should_run()) {
  9949. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  9950. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  9951. if (schedstop.enable)
  9952. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  9953. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9954. sched_paused = false;
  9955. for (i = 0; i < mining_threads; i++) {
  9956. struct thr_info *thr;
  9957. thr = get_thread(i);
  9958. thr->pause = false;
  9959. }
  9960. for (i = 0; i < total_devices; ++i)
  9961. {
  9962. struct cgpu_info *cgpu = get_devices(i);
  9963. /* Don't touch disabled devices */
  9964. if (cgpu->deven == DEV_DISABLED)
  9965. continue;
  9966. proc_enable(cgpu);
  9967. }
  9968. }
  9969. for (i = 0; i < total_devices; ++i) {
  9970. struct cgpu_info *cgpu = get_devices(i);
  9971. if (!cgpu->disable_watchdog)
  9972. bfg_watchdog(cgpu, &now);
  9973. }
  9974. }
  9975. return NULL;
  9976. }
  9977. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  9978. {
  9979. struct thr_info *thr = cgpu->thr[0];
  9980. enum dev_enable *denable;
  9981. char *dev_str = cgpu->proc_repr;
  9982. if (likely(drv_ready(cgpu)))
  9983. {
  9984. if (unlikely(!cgpu->already_set_defaults))
  9985. cgpu_set_defaults(cgpu);
  9986. if (cgpu->drv->get_stats)
  9987. cgpu->drv->get_stats(cgpu);
  9988. }
  9989. denable = &cgpu->deven;
  9990. if (cgpu->drv->watchdog)
  9991. cgpu->drv->watchdog(cgpu, tvp_now);
  9992. /* Thread is disabled */
  9993. if (*denable == DEV_DISABLED)
  9994. return;
  9995. else
  9996. if (*denable == DEV_RECOVER_ERR) {
  9997. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  9998. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  9999. dev_str);
  10000. if (cgpu->reinit_backoff < 300)
  10001. cgpu->reinit_backoff *= 2;
  10002. device_recovered(cgpu);
  10003. }
  10004. return;
  10005. }
  10006. else
  10007. if (*denable == DEV_RECOVER) {
  10008. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  10009. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  10010. dev_str);
  10011. device_recovered(cgpu);
  10012. }
  10013. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  10014. return;
  10015. }
  10016. else
  10017. if (cgpu->temp > cgpu->cutofftemp)
  10018. {
  10019. applog(LOG_WARNING, "%s hit thermal cutoff limit at %dC, disabling!",
  10020. dev_str, (int)cgpu->temp);
  10021. *denable = DEV_RECOVER;
  10022. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  10023. run_cmd(cmd_idle);
  10024. }
  10025. if (thr->getwork) {
  10026. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  10027. int thrid;
  10028. bool cgpu_idle = true;
  10029. thr->rolling = 0;
  10030. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  10031. if (!cgpu->thr[thrid]->getwork)
  10032. cgpu_idle = false;
  10033. if (cgpu_idle) {
  10034. cgpu->rolling = 0;
  10035. cgpu->status = LIFE_WAIT;
  10036. }
  10037. }
  10038. return;
  10039. }
  10040. else if (cgpu->status == LIFE_WAIT)
  10041. cgpu->status = LIFE_WELL;
  10042. #ifdef WANT_CPUMINE
  10043. if (!strcmp(cgpu->drv->dname, "cpu"))
  10044. return;
  10045. #endif
  10046. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  10047. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  10048. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  10049. cgpu->status = LIFE_WELL;
  10050. cgpu->device_last_well = time(NULL);
  10051. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  10052. thr->rolling = cgpu->rolling = 0;
  10053. cgpu->status = LIFE_SICK;
  10054. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  10055. cgtime(&thr->sick);
  10056. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  10057. run_cmd(cmd_sick);
  10058. if (opt_restart && cgpu->drv->reinit_device) {
  10059. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  10060. reinit_device(cgpu);
  10061. }
  10062. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  10063. cgpu->status = LIFE_DEAD;
  10064. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  10065. cgtime(&thr->sick);
  10066. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  10067. run_cmd(cmd_dead);
  10068. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  10069. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  10070. /* Attempt to restart a GPU that's sick or dead once every minute */
  10071. cgtime(&thr->sick);
  10072. if (opt_restart)
  10073. reinit_device(cgpu);
  10074. }
  10075. }
  10076. static void log_print_status(struct cgpu_info *cgpu)
  10077. {
  10078. char logline[255];
  10079. get_statline(logline, sizeof(logline), cgpu);
  10080. applog(LOG_WARNING, "%s", logline);
  10081. }
  10082. void print_summary(void)
  10083. {
  10084. struct timeval diff;
  10085. int hours, mins, secs, i;
  10086. double utility, efficiency = 0.0;
  10087. char xfer[(ALLOC_H2B_SPACED*2)+4+1], bw[(ALLOC_H2B_SPACED*2)+6+1];
  10088. int pool_secs;
  10089. timersub(&total_tv_end, &total_tv_start, &diff);
  10090. hours = diff.tv_sec / 3600;
  10091. mins = (diff.tv_sec % 3600) / 60;
  10092. secs = diff.tv_sec % 60;
  10093. utility = total_accepted / total_secs * 60;
  10094. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  10095. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  10096. applog(LOG_WARNING, "Started at %s", datestamp);
  10097. if (total_pools == 1)
  10098. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  10099. #ifdef WANT_CPUMINE
  10100. if (opt_n_threads > 0)
  10101. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  10102. #endif
  10103. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  10104. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  10105. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  10106. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  10107. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  10108. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  10109. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  10110. total_rejected, total_stale,
  10111. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  10112. );
  10113. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  10114. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  10115. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  10116. applog(LOG_WARNING, "Network transfer: %s (%s)",
  10117. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  10118. (float)total_bytes_rcvd,
  10119. (float)total_bytes_sent),
  10120. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  10121. (float)(total_bytes_rcvd / total_secs),
  10122. (float)(total_bytes_sent / total_secs)));
  10123. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  10124. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  10125. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  10126. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  10127. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  10128. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  10129. if (total_pools > 1) {
  10130. for (i = 0; i < total_pools; i++) {
  10131. struct pool *pool = pools[i];
  10132. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  10133. if (pool->solved)
  10134. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  10135. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  10136. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  10137. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  10138. pool->rejected, pool->stale_shares,
  10139. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  10140. );
  10141. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  10142. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  10143. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  10144. applog(LOG_WARNING, " Network transfer: %s (%s)",
  10145. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  10146. (float)pool->cgminer_pool_stats.net_bytes_received,
  10147. (float)pool->cgminer_pool_stats.net_bytes_sent),
  10148. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  10149. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  10150. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  10151. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  10152. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  10153. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  10154. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  10155. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  10156. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  10157. }
  10158. }
  10159. if (opt_quit_summary != BQS_NONE)
  10160. {
  10161. if (opt_quit_summary == BQS_DEFAULT)
  10162. {
  10163. if (total_devices < 25)
  10164. opt_quit_summary = BQS_PROCS;
  10165. else
  10166. opt_quit_summary = BQS_DEVS;
  10167. }
  10168. if (opt_quit_summary == BQS_DETAILED)
  10169. include_serial_in_statline = true;
  10170. applog(LOG_WARNING, "Summary of per device statistics:\n");
  10171. for (i = 0; i < total_devices; ++i) {
  10172. struct cgpu_info *cgpu = get_devices(i);
  10173. if (!cgpu->proc_id)
  10174. {
  10175. // Device summary line
  10176. opt_show_procs = false;
  10177. log_print_status(cgpu);
  10178. opt_show_procs = true;
  10179. }
  10180. if ((opt_quit_summary == BQS_PROCS || opt_quit_summary == BQS_DETAILED) && cgpu->procs > 1)
  10181. log_print_status(cgpu);
  10182. }
  10183. }
  10184. if (opt_shares) {
  10185. applog(LOG_WARNING, "Mined %g accepted shares of %g requested\n", total_diff_accepted, opt_shares);
  10186. if (opt_shares > total_diff_accepted)
  10187. applog(LOG_WARNING, "WARNING - Mined only %g shares of %g requested.", total_diff_accepted, opt_shares);
  10188. }
  10189. applog(LOG_WARNING, " ");
  10190. fflush(stderr);
  10191. fflush(stdout);
  10192. }
  10193. void _bfg_clean_up(bool restarting)
  10194. {
  10195. #ifdef HAVE_OPENCL
  10196. clear_adl(nDevs);
  10197. #endif
  10198. #ifdef HAVE_LIBUSB
  10199. if (likely(have_libusb))
  10200. libusb_exit(NULL);
  10201. #endif
  10202. cgtime(&total_tv_end);
  10203. #ifdef WIN32
  10204. timeEndPeriod(1);
  10205. #endif
  10206. if (!restarting) {
  10207. /* Attempting to disable curses or print a summary during a
  10208. * restart can lead to a deadlock. */
  10209. #ifdef HAVE_CURSES
  10210. disable_curses();
  10211. #endif
  10212. if (!opt_realquiet && successful_connect)
  10213. print_summary();
  10214. }
  10215. if (opt_n_threads > 0)
  10216. free(cpus);
  10217. curl_global_cleanup();
  10218. #ifdef WIN32
  10219. WSACleanup();
  10220. #endif
  10221. }
  10222. void _quit(int status)
  10223. {
  10224. if (status) {
  10225. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  10226. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  10227. int *p = NULL;
  10228. // NOTE debugger can bypass with: p = &p
  10229. *p = status; // Segfault, hopefully dumping core
  10230. }
  10231. }
  10232. #if defined(unix) || defined(__APPLE__)
  10233. if (forkpid > 0) {
  10234. kill(forkpid, SIGTERM);
  10235. forkpid = 0;
  10236. }
  10237. #endif
  10238. exit(status);
  10239. }
  10240. #ifdef HAVE_CURSES
  10241. char *curses_input(const char *query)
  10242. {
  10243. char *input;
  10244. echo();
  10245. input = malloc(255);
  10246. if (!input)
  10247. quit(1, "Failed to malloc input");
  10248. leaveok(logwin, false);
  10249. wlogprint("%s:\n", query);
  10250. wgetnstr(logwin, input, 255);
  10251. if (!strlen(input))
  10252. {
  10253. free(input);
  10254. input = NULL;
  10255. }
  10256. leaveok(logwin, true);
  10257. noecho();
  10258. return input;
  10259. }
  10260. #endif
  10261. static void *test_pool_thread(void *arg)
  10262. {
  10263. struct pool *pool = (struct pool *)arg;
  10264. if (pool_active(pool, false)) {
  10265. pool_tset(pool, &pool->lagging);
  10266. pool_tclear(pool, &pool->idle);
  10267. bool first_pool = false;
  10268. cg_wlock(&control_lock);
  10269. if (!pools_active) {
  10270. currentpool = pool;
  10271. if (pool->pool_no != 0)
  10272. first_pool = true;
  10273. pools_active = true;
  10274. }
  10275. cg_wunlock(&control_lock);
  10276. if (unlikely(first_pool))
  10277. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  10278. else
  10279. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  10280. switch_pools(NULL);
  10281. } else
  10282. pool_died(pool);
  10283. pool->testing = false;
  10284. return NULL;
  10285. }
  10286. /* Always returns true that the pool details were added unless we are not
  10287. * live, implying this is the only pool being added, so if no pools are
  10288. * active it returns false. */
  10289. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  10290. {
  10291. size_t siz;
  10292. pool_set_uri(pool, url);
  10293. pool->rpc_user = user;
  10294. pool->rpc_pass = pass;
  10295. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  10296. pool->rpc_userpass = malloc(siz);
  10297. if (!pool->rpc_userpass)
  10298. quit(1, "Failed to malloc userpass");
  10299. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  10300. pool->testing = true;
  10301. pool->idle = true;
  10302. enable_pool(pool);
  10303. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  10304. if (!live) {
  10305. pthread_join(pool->test_thread, NULL);
  10306. return pools_active;
  10307. }
  10308. return true;
  10309. }
  10310. #ifdef HAVE_CURSES
  10311. static bool input_pool(bool live)
  10312. {
  10313. char *url = NULL, *user = NULL, *pass = NULL;
  10314. struct pool *pool;
  10315. bool ret = false;
  10316. immedok(logwin, true);
  10317. wlogprint("Input server details.\n");
  10318. url = curses_input("URL");
  10319. if (!url)
  10320. goto out;
  10321. user = curses_input("Username");
  10322. if (!user)
  10323. goto out;
  10324. pass = curses_input("Password");
  10325. if (!pass)
  10326. pass = calloc(1, 1);
  10327. pool = add_pool();
  10328. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  10329. strncmp(url, "https://", 8)) {
  10330. char *httpinput;
  10331. httpinput = malloc(256);
  10332. if (!httpinput)
  10333. quit(1, "Failed to malloc httpinput");
  10334. strcpy(httpinput, "http://");
  10335. strncat(httpinput, url, 248);
  10336. free(url);
  10337. url = httpinput;
  10338. }
  10339. ret = add_pool_details(pool, live, url, user, pass);
  10340. out:
  10341. immedok(logwin, false);
  10342. if (!ret) {
  10343. if (url)
  10344. free(url);
  10345. if (user)
  10346. free(user);
  10347. if (pass)
  10348. free(pass);
  10349. }
  10350. return ret;
  10351. }
  10352. #endif
  10353. #if BLKMAKER_VERSION > 1
  10354. static
  10355. bool _add_local_gbt(const char * const filepath, void *userp)
  10356. {
  10357. const bool * const live_p = userp;
  10358. struct pool *pool;
  10359. char buf[0x100];
  10360. char *rpcuser = NULL, *rpcpass = NULL, *rpcconnect = NULL;
  10361. int rpcport = 0, rpcssl = -101;
  10362. FILE * const F = fopen(filepath, "r");
  10363. if (!F)
  10364. applogr(false, LOG_WARNING, "%s: Failed to open %s for reading", "add_local_gbt", filepath);
  10365. while (fgets(buf, sizeof(buf), F))
  10366. {
  10367. if (!strncasecmp(buf, "rpcuser=", 8))
  10368. rpcuser = trimmed_strdup(&buf[8]);
  10369. else
  10370. if (!strncasecmp(buf, "rpcpassword=", 12))
  10371. rpcpass = trimmed_strdup(&buf[12]);
  10372. else
  10373. if (!strncasecmp(buf, "rpcport=", 8))
  10374. rpcport = atoi(&buf[8]);
  10375. else
  10376. if (!strncasecmp(buf, "rpcssl=", 7))
  10377. rpcssl = atoi(&buf[7]);
  10378. else
  10379. if (!strncasecmp(buf, "rpcconnect=", 11))
  10380. rpcconnect = trimmed_strdup(&buf[11]);
  10381. else
  10382. continue;
  10383. if (rpcuser && rpcpass && rpcport && rpcssl != -101 && rpcconnect)
  10384. break;
  10385. }
  10386. fclose(F);
  10387. if (!rpcpass)
  10388. {
  10389. applog(LOG_DEBUG, "%s: Did not find rpcpassword in %s", "add_local_gbt", filepath);
  10390. err:
  10391. free(rpcuser);
  10392. free(rpcpass);
  10393. goto out;
  10394. }
  10395. if (!rpcport)
  10396. rpcport = 8332;
  10397. if (rpcssl == -101)
  10398. rpcssl = 0;
  10399. const bool have_cbaddr = get_mining_goal("default")->generation_script;
  10400. const int uri_sz = 0x30;
  10401. char * const uri = malloc(uri_sz);
  10402. snprintf(uri, uri_sz, "http%s://%s:%d/%s#allblocks", rpcssl ? "s" : "", rpcconnect ?: "localhost", rpcport, have_cbaddr ? "" : "#getcbaddr");
  10403. char hfuri[0x40];
  10404. if (rpcconnect)
  10405. snprintf(hfuri, sizeof(hfuri), "%s:%d", rpcconnect, rpcport);
  10406. else
  10407. snprintf(hfuri, sizeof(hfuri), "port %d", rpcport);
  10408. applog(LOG_DEBUG, "Local bitcoin RPC server on %s found in %s", hfuri, filepath);
  10409. for (int i = 0; i < total_pools; ++i)
  10410. {
  10411. struct pool *pool = pools[i];
  10412. if (!(strcmp(pool->rpc_url, uri) || strcmp(pool->rpc_pass, rpcpass)))
  10413. {
  10414. applog(LOG_DEBUG, "Server on %s is already configured, not adding as failover", hfuri);
  10415. free(uri);
  10416. goto err;
  10417. }
  10418. }
  10419. pool = add_pool();
  10420. if (!pool)
  10421. {
  10422. applog(LOG_ERR, "%s: Error adding pool for bitcoin configured in %s", "add_local_gbt", filepath);
  10423. goto err;
  10424. }
  10425. if (!rpcuser)
  10426. rpcuser = "";
  10427. pool->quota = 0;
  10428. adjust_quota_gcd();
  10429. pool->failover_only = true;
  10430. add_pool_details(pool, *live_p, uri, rpcuser, rpcpass);
  10431. applog(LOG_NOTICE, "Added local bitcoin RPC server on %s as pool %d", hfuri, pool->pool_no);
  10432. out:
  10433. return false;
  10434. }
  10435. static
  10436. void add_local_gbt(bool live)
  10437. {
  10438. appdata_file_call("Bitcoin", "bitcoin.conf", _add_local_gbt, &live);
  10439. }
  10440. #endif
  10441. #if defined(unix) || defined(__APPLE__)
  10442. static void fork_monitor()
  10443. {
  10444. // Make a pipe: [readFD, writeFD]
  10445. int pfd[2];
  10446. int r = pipe(pfd);
  10447. if (r < 0) {
  10448. perror("pipe - failed to create pipe for --monitor");
  10449. exit(1);
  10450. }
  10451. // Make stderr write end of pipe
  10452. fflush(stderr);
  10453. r = dup2(pfd[1], 2);
  10454. if (r < 0) {
  10455. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  10456. exit(1);
  10457. }
  10458. r = close(pfd[1]);
  10459. if (r < 0) {
  10460. perror("close - failed to close write end of pipe for --monitor");
  10461. exit(1);
  10462. }
  10463. // Don't allow a dying monitor to kill the main process
  10464. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  10465. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  10466. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  10467. perror("signal - failed to edit signal mask for --monitor");
  10468. exit(1);
  10469. }
  10470. // Fork a child process
  10471. forkpid = fork();
  10472. if (forkpid < 0) {
  10473. perror("fork - failed to fork child process for --monitor");
  10474. exit(1);
  10475. }
  10476. // Child: launch monitor command
  10477. if (0 == forkpid) {
  10478. // Make stdin read end of pipe
  10479. r = dup2(pfd[0], 0);
  10480. if (r < 0) {
  10481. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  10482. exit(1);
  10483. }
  10484. close(pfd[0]);
  10485. if (r < 0) {
  10486. perror("close - in child, failed to close read end of pipe for --monitor");
  10487. exit(1);
  10488. }
  10489. // Launch user specified command
  10490. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  10491. perror("execl - in child failed to exec user specified command for --monitor");
  10492. exit(1);
  10493. }
  10494. // Parent: clean up unused fds and bail
  10495. r = close(pfd[0]);
  10496. if (r < 0) {
  10497. perror("close - failed to close read end of pipe for --monitor");
  10498. exit(1);
  10499. }
  10500. }
  10501. #endif // defined(unix)
  10502. #ifdef HAVE_CURSES
  10503. #ifdef USE_UNICODE
  10504. static
  10505. wchar_t select_unicode_char(const wchar_t *opt)
  10506. {
  10507. for ( ; *opt; ++opt)
  10508. if (iswprint(*opt))
  10509. return *opt;
  10510. return '?';
  10511. }
  10512. #endif
  10513. void enable_curses(void) {
  10514. int x;
  10515. __maybe_unused int y;
  10516. lock_curses();
  10517. if (curses_active) {
  10518. unlock_curses();
  10519. return;
  10520. }
  10521. #ifdef USE_UNICODE
  10522. if (use_unicode)
  10523. {
  10524. setlocale(LC_CTYPE, "");
  10525. if (iswprint(0xb0))
  10526. have_unicode_degrees = true;
  10527. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  10528. }
  10529. #endif
  10530. mainwin = initscr();
  10531. start_color();
  10532. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  10533. if (ERR != use_default_colors())
  10534. default_bgcolor = -1;
  10535. #endif
  10536. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  10537. {
  10538. menu_attr = COLOR_PAIR(1);
  10539. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  10540. attr_bad |= COLOR_PAIR(2);
  10541. }
  10542. keypad(mainwin, true);
  10543. getmaxyx(mainwin, y, x);
  10544. statuswin = newwin(logstart, x, 0, 0);
  10545. leaveok(statuswin, true);
  10546. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  10547. // We resize the window later anyway, so just start it off at 1 :)
  10548. logwin = newwin(1, 0, logcursor, 0);
  10549. idlok(logwin, true);
  10550. scrollok(logwin, true);
  10551. leaveok(logwin, true);
  10552. cbreak();
  10553. noecho();
  10554. nonl();
  10555. curses_active = true;
  10556. statusy = logstart;
  10557. unlock_curses();
  10558. }
  10559. #endif
  10560. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  10561. #ifndef WANT_CPUMINE
  10562. struct device_drv cpu_drv;
  10563. struct device_drv cpu_drv = {
  10564. .name = "CPU",
  10565. };
  10566. #endif
  10567. static int cgminer_id_count = 0;
  10568. static int device_line_id_count;
  10569. void register_device(struct cgpu_info *cgpu)
  10570. {
  10571. cgpu->deven = DEV_ENABLED;
  10572. wr_lock(&devices_lock);
  10573. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  10574. wr_unlock(&devices_lock);
  10575. if (!cgpu->proc_id)
  10576. cgpu->device_line_id = device_line_id_count++;
  10577. int thr_objs = cgpu->threads ?: 1;
  10578. mining_threads += thr_objs;
  10579. base_queue += thr_objs + cgpu->extra_work_queue;
  10580. {
  10581. const struct device_drv * const drv = cgpu->drv;
  10582. struct mining_algorithm *malgo;
  10583. LL_FOREACH(mining_algorithms, malgo)
  10584. {
  10585. if (drv_min_nonce_diff(drv, cgpu, malgo) < 0)
  10586. continue;
  10587. malgo->base_queue += thr_objs + cgpu->extra_work_queue;
  10588. }
  10589. }
  10590. #ifdef HAVE_CURSES
  10591. adj_width(mining_threads, &dev_width);
  10592. #endif
  10593. rwlock_init(&cgpu->qlock);
  10594. cgpu->queued_work = NULL;
  10595. }
  10596. struct _cgpu_devid_counter {
  10597. char name[4];
  10598. int lastid;
  10599. UT_hash_handle hh;
  10600. };
  10601. void renumber_cgpu(struct cgpu_info *cgpu)
  10602. {
  10603. static struct _cgpu_devid_counter *devids = NULL;
  10604. struct _cgpu_devid_counter *d;
  10605. HASH_FIND_STR(devids, cgpu->drv->name, d);
  10606. if (d)
  10607. cgpu->device_id = ++d->lastid;
  10608. else {
  10609. d = malloc(sizeof(*d));
  10610. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  10611. cgpu->device_id = d->lastid = 0;
  10612. HASH_ADD_STR(devids, name, d);
  10613. }
  10614. // Build repr strings
  10615. sprintf(cgpu->dev_repr, "%s%2u", cgpu->drv->name, cgpu->device_id % 100);
  10616. sprintf(cgpu->dev_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id % 100);
  10617. strcpy(cgpu->proc_repr, cgpu->dev_repr);
  10618. sprintf(cgpu->proc_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id);
  10619. const int lpcount = cgpu->procs;
  10620. if (lpcount > 1)
  10621. {
  10622. int ns;
  10623. struct cgpu_info *slave;
  10624. int lpdigits = 1;
  10625. for (int i = lpcount; i > 26 && lpdigits < 3; i /= 26)
  10626. ++lpdigits;
  10627. if (lpdigits > max_lpdigits)
  10628. max_lpdigits = lpdigits;
  10629. memset(&cgpu->proc_repr[5], 'a', lpdigits);
  10630. cgpu->proc_repr[5 + lpdigits] = '\0';
  10631. ns = strlen(cgpu->proc_repr_ns);
  10632. strcpy(&cgpu->proc_repr_ns[ns], &cgpu->proc_repr[5]);
  10633. slave = cgpu;
  10634. for (int i = 1; i < lpcount; ++i)
  10635. {
  10636. slave = slave->next_proc;
  10637. strcpy(slave->proc_repr, cgpu->proc_repr);
  10638. strcpy(slave->proc_repr_ns, cgpu->proc_repr_ns);
  10639. for (int x = i, y = lpdigits; --y, x; x /= 26)
  10640. {
  10641. slave->proc_repr_ns[ns + y] =
  10642. slave->proc_repr[5 + y] += (x % 26);
  10643. }
  10644. }
  10645. }
  10646. }
  10647. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  10648. {
  10649. sha256(buffer, length, digest);
  10650. return true;
  10651. }
  10652. static
  10653. bool drv_algo_check(const struct device_drv * const drv)
  10654. {
  10655. struct mining_goal_info *goal, *tmpgoal;
  10656. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  10657. {
  10658. if (drv_min_nonce_diff(drv, NULL, goal->malgo) >= 0)
  10659. return true;
  10660. }
  10661. return false;
  10662. }
  10663. #ifndef HAVE_PTHREAD_CANCEL
  10664. extern void setup_pthread_cancel_workaround();
  10665. extern struct sigaction pcwm_orig_term_handler;
  10666. #endif
  10667. bool bfg_need_detect_rescan;
  10668. extern void probe_device(struct lowlevel_device_info *);
  10669. static void schedule_rescan(const struct timeval *);
  10670. static
  10671. void drv_detect_all()
  10672. {
  10673. bool rescanning = false;
  10674. rescan:
  10675. bfg_need_detect_rescan = false;
  10676. #ifdef HAVE_BFG_LOWLEVEL
  10677. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  10678. LL_FOREACH_SAFE(infolist, info, infotmp)
  10679. probe_device(info);
  10680. LL_FOREACH_SAFE(infolist, info, infotmp)
  10681. pthread_join(info->probe_pth, NULL);
  10682. #endif
  10683. struct driver_registration *reg, *tmp;
  10684. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  10685. {
  10686. const struct device_drv * const drv = reg->drv;
  10687. if (!(drv_algo_check(drv) && drv->drv_detect))
  10688. continue;
  10689. drv->drv_detect();
  10690. }
  10691. #ifdef HAVE_BFG_LOWLEVEL
  10692. lowlevel_scan_free();
  10693. #endif
  10694. if (bfg_need_detect_rescan)
  10695. {
  10696. if (rescanning)
  10697. {
  10698. applog(LOG_DEBUG, "Device rescan requested a second time, delaying");
  10699. struct timeval tv_when;
  10700. timer_set_delay_from_now(&tv_when, rescan_delay_ms * 1000);
  10701. schedule_rescan(&tv_when);
  10702. }
  10703. else
  10704. {
  10705. rescanning = true;
  10706. applog(LOG_DEBUG, "Device rescan requested");
  10707. goto rescan;
  10708. }
  10709. }
  10710. }
  10711. static
  10712. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  10713. {
  10714. struct thr_info *thr;
  10715. int j;
  10716. struct device_drv *api = cgpu->drv;
  10717. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10718. int threadobj = cgpu->threads;
  10719. if (!threadobj)
  10720. // Create a fake thread object to handle hashmeter etc
  10721. threadobj = 1;
  10722. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  10723. cgpu->thr[threadobj] = NULL;
  10724. cgpu->status = LIFE_INIT;
  10725. if (opt_devices_enabled_list)
  10726. {
  10727. struct string_elist *enablestr_elist;
  10728. cgpu->deven = DEV_DISABLED;
  10729. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  10730. {
  10731. const char * const enablestr = enablestr_elist->string;
  10732. if (cgpu_match(enablestr, cgpu))
  10733. {
  10734. cgpu->deven = DEV_ENABLED;
  10735. break;
  10736. }
  10737. }
  10738. }
  10739. cgpu->max_hashes = 0;
  10740. BFGINIT(cgpu->cutofftemp, opt_cutofftemp);
  10741. BFGINIT(cgpu->targettemp, cgpu->cutofftemp - 6);
  10742. // Setup thread structs before starting any of the threads, in case they try to interact
  10743. for (j = 0; j < threadobj; ++j, ++*kp) {
  10744. thr = get_thread(*kp);
  10745. thr->id = *kp;
  10746. thr->cgpu = cgpu;
  10747. thr->device_thread = j;
  10748. thr->work_restart_notifier[1] = INVSOCK;
  10749. thr->mutex_request[1] = INVSOCK;
  10750. thr->_job_transition_in_progress = true;
  10751. timerclear(&thr->tv_morework);
  10752. thr->scanhash_working = true;
  10753. thr->hashes_done = 0;
  10754. timerclear(&thr->tv_hashes_done);
  10755. cgtime(&thr->tv_lastupdate);
  10756. thr->tv_poll.tv_sec = -1;
  10757. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  10758. cgpu->thr[j] = thr;
  10759. }
  10760. if (!cgpu->device->threads)
  10761. notifier_init_invalid(cgpu->thr[0]->notifier);
  10762. else
  10763. if (!cgpu->threads)
  10764. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  10765. else
  10766. for (j = 0; j < cgpu->threads; ++j)
  10767. {
  10768. thr = cgpu->thr[j];
  10769. notifier_init(thr->notifier);
  10770. }
  10771. }
  10772. static
  10773. void start_cgpu(struct cgpu_info *cgpu)
  10774. {
  10775. struct thr_info *thr;
  10776. int j;
  10777. for (j = 0; j < cgpu->threads; ++j) {
  10778. thr = cgpu->thr[j];
  10779. /* Enable threads for devices set not to mine but disable
  10780. * their queue in case we wish to enable them later */
  10781. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  10782. continue;
  10783. thread_reportout(thr);
  10784. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  10785. quit(1, "thread %d create failed", thr->id);
  10786. notifier_wake(thr->notifier);
  10787. }
  10788. if (cgpu->deven == DEV_ENABLED)
  10789. proc_enable(cgpu);
  10790. }
  10791. static
  10792. void _scan_serial(void *p)
  10793. {
  10794. const char *s = p;
  10795. struct string_elist *iter, *tmp;
  10796. struct string_elist *orig_scan_devices = scan_devices;
  10797. if (s)
  10798. {
  10799. // Make temporary scan_devices list
  10800. scan_devices = NULL;
  10801. string_elist_add("noauto", &scan_devices);
  10802. add_serial(s);
  10803. }
  10804. drv_detect_all();
  10805. if (s)
  10806. {
  10807. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  10808. {
  10809. string_elist_del(&scan_devices, iter);
  10810. }
  10811. scan_devices = orig_scan_devices;
  10812. }
  10813. }
  10814. #ifdef HAVE_BFG_LOWLEVEL
  10815. static
  10816. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  10817. {
  10818. if (!(false
  10819. || (info->serial && !strcasecmp(ser, info->serial))
  10820. || (info->path && !strcasecmp(ser, info->path ))
  10821. || (info->devid && !strcasecmp(ser, info->devid ))
  10822. ))
  10823. {
  10824. char *devid = devpath_to_devid(ser);
  10825. if (!devid)
  10826. return false;
  10827. const bool different = strcmp(info->devid, devid);
  10828. free(devid);
  10829. if (different)
  10830. return false;
  10831. }
  10832. return true;
  10833. }
  10834. static
  10835. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  10836. {
  10837. struct driver_registration *dreg;
  10838. char dname[dnamelen];
  10839. int i;
  10840. for (i = 0; i < dnamelen; ++i)
  10841. dname[i] = tolower(_dname[i]);
  10842. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  10843. if (!dreg)
  10844. {
  10845. for (i = 0; i < dnamelen; ++i)
  10846. dname[i] = toupper(_dname[i]);
  10847. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  10848. if (!dreg)
  10849. return NULL;
  10850. }
  10851. if (!drv_algo_check(dreg->drv))
  10852. return NULL;
  10853. return dreg->drv;
  10854. }
  10855. static
  10856. bool _probe_device_do_probe(const struct device_drv * const drv, const struct lowlevel_device_info * const info, bool * const request_rescan_p)
  10857. {
  10858. bfg_probe_result_flags = 0;
  10859. if (drv->lowl_probe(info))
  10860. {
  10861. if (!(bfg_probe_result_flags & BPR_CONTINUE_PROBES))
  10862. return true;
  10863. }
  10864. else
  10865. if (request_rescan_p && opt_hotplug && !(bfg_probe_result_flags & BPR_DONT_RESCAN))
  10866. *request_rescan_p = true;
  10867. return false;
  10868. }
  10869. bool dummy_check_never_true = false;
  10870. static
  10871. void *probe_device_thread(void *p)
  10872. {
  10873. struct lowlevel_device_info * const infolist = p;
  10874. struct lowlevel_device_info *info = infolist;
  10875. bool request_rescan = false;
  10876. {
  10877. char threadname[5 + strlen(info->devid) + 1];
  10878. sprintf(threadname, "probe_%s", info->devid);
  10879. RenameThread(threadname);
  10880. }
  10881. // If already in use, ignore
  10882. if (bfg_claim_any(NULL, NULL, info->devid))
  10883. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  10884. __func__, info->product);
  10885. // if lowlevel device matches specific user assignment, probe requested driver(s)
  10886. struct string_elist *sd_iter, *sd_tmp;
  10887. struct driver_registration *dreg, *dreg_tmp;
  10888. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10889. {
  10890. const char * const dname = sd_iter->string;
  10891. const char * const colon = strpbrk(dname, ":@");
  10892. if (!(colon && colon != dname))
  10893. continue;
  10894. const char * const ser = &colon[1];
  10895. LL_FOREACH2(infolist, info, same_devid_next)
  10896. {
  10897. if (!_probe_device_match(info, ser))
  10898. continue;
  10899. const size_t dnamelen = (colon - dname);
  10900. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  10901. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  10902. continue;
  10903. if (_probe_device_do_probe(drv, info, &request_rescan))
  10904. return NULL;
  10905. }
  10906. }
  10907. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  10908. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  10909. {
  10910. const struct device_drv * const drv = dreg->drv;
  10911. if (!drv_algo_check(drv))
  10912. continue;
  10913. // Check for "noauto" flag
  10914. // NOTE: driver-specific configuration overrides general
  10915. bool doauto = true;
  10916. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10917. {
  10918. const char * const dname = sd_iter->string;
  10919. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  10920. const char *colon = strchr(dname, ':');
  10921. if (!colon)
  10922. colon = &dname[-1];
  10923. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  10924. continue;
  10925. const ssize_t dnamelen = (colon - dname);
  10926. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  10927. continue;
  10928. doauto = (tolower(colon[1]) == 'a');
  10929. if (dnamelen != -1)
  10930. break;
  10931. }
  10932. if (doauto && drv->lowl_match)
  10933. {
  10934. LL_FOREACH2(infolist, info, same_devid_next)
  10935. {
  10936. /*
  10937. The below call to applog is absolutely necessary
  10938. Starting with commit 76d0cc183b1c9ddcc0ef34d2e43bc696ef9de92e installing BFGMiner on
  10939. Mac OS X using Homebrew results in a binary that segfaults on startup
  10940. There are two unresolved issues:
  10941. 1) The BFGMiner authors cannot find a way to install BFGMiner with Homebrew that results
  10942. in debug symbols being available to help troubleshoot the issue
  10943. 2) The issue disappears when unrelated code changes are made, such as adding the following
  10944. call to applog with infolist and / or p
  10945. We would encourage revisiting this in the future to come up with a more concrete solution
  10946. Reproducing should only require commenting / removing the following line and installing
  10947. BFGMiner using "brew install bfgminer --HEAD"
  10948. */
  10949. if (dummy_check_never_true)
  10950. applog(LOG_DEBUG, "lowl_match: %p(%s) %p %p %p", drv, drv->dname, info, infolist, p);
  10951. if (!drv->lowl_match(info))
  10952. continue;
  10953. if (_probe_device_do_probe(drv, info, &request_rescan))
  10954. return NULL;
  10955. }
  10956. }
  10957. }
  10958. // probe driver(s) with 'all' enabled
  10959. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10960. {
  10961. const char * const dname = sd_iter->string;
  10962. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  10963. const char * const colon = strchr(dname, ':');
  10964. if (!colon)
  10965. {
  10966. LL_FOREACH2(infolist, info, same_devid_next)
  10967. {
  10968. if (
  10969. #ifdef NEED_BFG_LOWL_VCOM
  10970. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  10971. #endif
  10972. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  10973. {
  10974. bool dont_rescan = false;
  10975. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  10976. {
  10977. const struct device_drv * const drv = dreg->drv;
  10978. if (!drv_algo_check(drv))
  10979. continue;
  10980. if (drv->lowl_probe_by_name_only)
  10981. continue;
  10982. if (!drv->lowl_probe)
  10983. continue;
  10984. if (_probe_device_do_probe(drv, info, NULL))
  10985. return NULL;
  10986. if (bfg_probe_result_flags & BPR_DONT_RESCAN)
  10987. dont_rescan = true;
  10988. }
  10989. if (opt_hotplug && !dont_rescan)
  10990. request_rescan = true;
  10991. break;
  10992. }
  10993. }
  10994. continue;
  10995. }
  10996. if (strcasecmp(&colon[1], "all"))
  10997. continue;
  10998. const size_t dnamelen = (colon - dname);
  10999. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  11000. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  11001. continue;
  11002. LL_FOREACH2(infolist, info, same_devid_next)
  11003. {
  11004. if (info->lowl->exclude_from_all)
  11005. continue;
  11006. if (_probe_device_do_probe(drv, info, NULL))
  11007. return NULL;
  11008. }
  11009. }
  11010. // Only actually request a rescan if we never found any cgpu
  11011. if (request_rescan)
  11012. bfg_need_detect_rescan = true;
  11013. return NULL;
  11014. }
  11015. void probe_device(struct lowlevel_device_info * const info)
  11016. {
  11017. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  11018. }
  11019. #endif
  11020. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  11021. {
  11022. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  11023. int devcount, i, mining_threads_new = 0;
  11024. unsigned int k;
  11025. struct cgpu_info *cgpu;
  11026. struct thr_info *thr;
  11027. void *p;
  11028. mutex_lock(&mutex);
  11029. devcount = total_devices;
  11030. addfunc(arg);
  11031. if (!total_devices_new)
  11032. goto out;
  11033. wr_lock(&devices_lock);
  11034. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  11035. if (unlikely(!p))
  11036. {
  11037. wr_unlock(&devices_lock);
  11038. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  11039. goto out;
  11040. }
  11041. devices = p;
  11042. wr_unlock(&devices_lock);
  11043. for (i = 0; i < total_devices_new; ++i)
  11044. {
  11045. cgpu = devices_new[i];
  11046. mining_threads_new += cgpu->threads ?: 1;
  11047. }
  11048. wr_lock(&mining_thr_lock);
  11049. mining_threads_new += mining_threads;
  11050. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  11051. if (unlikely(!p))
  11052. {
  11053. wr_unlock(&mining_thr_lock);
  11054. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  11055. goto out;
  11056. }
  11057. mining_thr = p;
  11058. wr_unlock(&mining_thr_lock);
  11059. for (i = mining_threads; i < mining_threads_new; ++i) {
  11060. mining_thr[i] = calloc(1, sizeof(*thr));
  11061. if (!mining_thr[i])
  11062. {
  11063. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  11064. for ( ; --i >= mining_threads; )
  11065. free(mining_thr[i]);
  11066. goto out;
  11067. }
  11068. }
  11069. k = mining_threads;
  11070. for (i = 0; i < total_devices_new; ++i)
  11071. {
  11072. cgpu = devices_new[i];
  11073. allocate_cgpu(cgpu, &k);
  11074. }
  11075. for (i = 0; i < total_devices_new; ++i)
  11076. {
  11077. cgpu = devices_new[i];
  11078. start_cgpu(cgpu);
  11079. register_device(cgpu);
  11080. ++total_devices;
  11081. }
  11082. #ifdef HAVE_CURSES
  11083. switch_logsize();
  11084. #endif
  11085. out:
  11086. total_devices_new = 0;
  11087. devcount = total_devices - devcount;
  11088. mutex_unlock(&mutex);
  11089. return devcount;
  11090. }
  11091. int scan_serial(const char *s)
  11092. {
  11093. return create_new_cgpus(_scan_serial, (void*)s);
  11094. }
  11095. static pthread_mutex_t rescan_mutex = PTHREAD_MUTEX_INITIALIZER;
  11096. static bool rescan_active;
  11097. static struct timeval tv_rescan;
  11098. static notifier_t rescan_notifier;
  11099. static
  11100. void *rescan_thread(__maybe_unused void *p)
  11101. {
  11102. pthread_detach(pthread_self());
  11103. RenameThread("rescan");
  11104. struct timeval tv_timeout, tv_now;
  11105. fd_set rfds;
  11106. while (true)
  11107. {
  11108. mutex_lock(&rescan_mutex);
  11109. tv_timeout = tv_rescan;
  11110. if (!timer_isset(&tv_timeout))
  11111. {
  11112. rescan_active = false;
  11113. mutex_unlock(&rescan_mutex);
  11114. break;
  11115. }
  11116. mutex_unlock(&rescan_mutex);
  11117. FD_ZERO(&rfds);
  11118. FD_SET(rescan_notifier[0], &rfds);
  11119. const int maxfd = rescan_notifier[0];
  11120. timer_set_now(&tv_now);
  11121. if (select(maxfd+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now)) > 0)
  11122. notifier_read(rescan_notifier);
  11123. mutex_lock(&rescan_mutex);
  11124. if (timer_passed(&tv_rescan, NULL))
  11125. {
  11126. timer_unset(&tv_rescan);
  11127. mutex_unlock(&rescan_mutex);
  11128. applog(LOG_DEBUG, "Rescan timer expired, triggering");
  11129. scan_serial(NULL);
  11130. }
  11131. else
  11132. mutex_unlock(&rescan_mutex);
  11133. }
  11134. return NULL;
  11135. }
  11136. static
  11137. void _schedule_rescan(const struct timeval * const tvp_when)
  11138. {
  11139. if (rescan_active)
  11140. {
  11141. if (timercmp(tvp_when, &tv_rescan, <))
  11142. applog(LOG_DEBUG, "schedule_rescan: New schedule is before current, waiting it out");
  11143. else
  11144. {
  11145. applog(LOG_DEBUG, "schedule_rescan: New schedule is after current, delaying rescan");
  11146. tv_rescan = *tvp_when;
  11147. }
  11148. return;
  11149. }
  11150. applog(LOG_DEBUG, "schedule_rescan: Scheduling rescan (no rescans currently pending)");
  11151. tv_rescan = *tvp_when;
  11152. rescan_active = true;
  11153. static pthread_t pth;
  11154. if (unlikely(pthread_create(&pth, NULL, rescan_thread, NULL)))
  11155. applog(LOG_ERR, "Failed to start rescan thread");
  11156. }
  11157. static
  11158. void schedule_rescan(const struct timeval * const tvp_when)
  11159. {
  11160. mutex_lock(&rescan_mutex);
  11161. _schedule_rescan(tvp_when);
  11162. mutex_unlock(&rescan_mutex);
  11163. }
  11164. static
  11165. void hotplug_trigger()
  11166. {
  11167. applog(LOG_DEBUG, "%s: Scheduling rescan immediately", __func__);
  11168. struct timeval tv_now;
  11169. timer_set_now(&tv_now);
  11170. schedule_rescan(&tv_now);
  11171. }
  11172. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  11173. static
  11174. void *hotplug_thread(__maybe_unused void *p)
  11175. {
  11176. pthread_detach(pthread_self());
  11177. RenameThread("hotplug");
  11178. struct udev * const udev = udev_new();
  11179. if (unlikely(!udev))
  11180. applogfailr(NULL, LOG_ERR, "udev_new");
  11181. struct udev_monitor * const mon = udev_monitor_new_from_netlink(udev, "udev");
  11182. if (unlikely(!mon))
  11183. applogfailr(NULL, LOG_ERR, "udev_monitor_new_from_netlink");
  11184. if (unlikely(udev_monitor_enable_receiving(mon)))
  11185. applogfailr(NULL, LOG_ERR, "udev_monitor_enable_receiving");
  11186. const int epfd = epoll_create(1);
  11187. if (unlikely(epfd == -1))
  11188. applogfailr(NULL, LOG_ERR, "epoll_create");
  11189. {
  11190. const int fd = udev_monitor_get_fd(mon);
  11191. struct epoll_event ev = {
  11192. .events = EPOLLIN | EPOLLPRI,
  11193. .data.fd = fd,
  11194. };
  11195. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev))
  11196. applogfailr(NULL, LOG_ERR, "epoll_ctl");
  11197. }
  11198. struct epoll_event ev;
  11199. int rv;
  11200. bool pending = false;
  11201. while (true)
  11202. {
  11203. rv = epoll_wait(epfd, &ev, 1, pending ? hotplug_delay_ms : -1);
  11204. if (rv == -1)
  11205. {
  11206. if (errno == EAGAIN || errno == EINTR)
  11207. continue;
  11208. break;
  11209. }
  11210. if (!rv)
  11211. {
  11212. hotplug_trigger();
  11213. pending = false;
  11214. continue;
  11215. }
  11216. struct udev_device * const device = udev_monitor_receive_device(mon);
  11217. if (!device)
  11218. continue;
  11219. const char * const action = udev_device_get_action(device);
  11220. applog(LOG_DEBUG, "%s: Received %s event", __func__, action);
  11221. if (!strcmp(action, "add"))
  11222. pending = true;
  11223. udev_device_unref(device);
  11224. }
  11225. applogfailr(NULL, LOG_ERR, "epoll_wait");
  11226. }
  11227. #elif defined(WIN32)
  11228. static UINT_PTR _hotplug_wintimer_id;
  11229. VOID CALLBACK hotplug_win_timer(HWND hwnd, UINT msg, UINT_PTR idEvent, DWORD dwTime)
  11230. {
  11231. KillTimer(NULL, _hotplug_wintimer_id);
  11232. _hotplug_wintimer_id = 0;
  11233. hotplug_trigger();
  11234. }
  11235. LRESULT CALLBACK hotplug_win_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  11236. {
  11237. if (msg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED)
  11238. {
  11239. applog(LOG_DEBUG, "%s: Received DBT_DEVNODES_CHANGED event", __func__);
  11240. _hotplug_wintimer_id = SetTimer(NULL, _hotplug_wintimer_id, hotplug_delay_ms, hotplug_win_timer);
  11241. }
  11242. return DefWindowProc(hwnd, msg, wParam, lParam);
  11243. }
  11244. static
  11245. void *hotplug_thread(__maybe_unused void *p)
  11246. {
  11247. pthread_detach(pthread_self());
  11248. WNDCLASS DummyWinCls = {
  11249. .lpszClassName = "BFGDummyWinCls",
  11250. .lpfnWndProc = hotplug_win_callback,
  11251. };
  11252. ATOM a = RegisterClass(&DummyWinCls);
  11253. if (unlikely(!a))
  11254. applogfailinfor(NULL, LOG_ERR, "RegisterClass", "%d", (int)GetLastError());
  11255. HWND hwnd = CreateWindow((void*)(intptr_t)a, NULL, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
  11256. if (unlikely(!hwnd))
  11257. applogfailinfor(NULL, LOG_ERR, "CreateWindow", "%d", (int)GetLastError());
  11258. MSG msg;
  11259. while (GetMessage(&msg, NULL, 0, 0))
  11260. {
  11261. TranslateMessage(&msg);
  11262. DispatchMessage(&msg);
  11263. }
  11264. quit(0, "WM_QUIT received");
  11265. return NULL;
  11266. }
  11267. #endif
  11268. #ifdef HAVE_BFG_HOTPLUG
  11269. static
  11270. void hotplug_start()
  11271. {
  11272. pthread_t pth;
  11273. if (unlikely(pthread_create(&pth, NULL, hotplug_thread, NULL)))
  11274. applog(LOG_ERR, "Failed to start hotplug thread");
  11275. }
  11276. #endif
  11277. static void probe_pools(void)
  11278. {
  11279. int i;
  11280. for (i = 0; i < total_pools; i++) {
  11281. struct pool *pool = pools[i];
  11282. pool->testing = true;
  11283. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  11284. }
  11285. }
  11286. static void raise_fd_limits(void)
  11287. {
  11288. #ifdef HAVE_SETRLIMIT
  11289. struct rlimit fdlimit;
  11290. rlim_t old_soft_limit;
  11291. char frombuf[0x10] = "unlimited";
  11292. char hardbuf[0x10] = "unlimited";
  11293. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  11294. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  11295. old_soft_limit = fdlimit.rlim_cur;
  11296. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  11297. fdlimit.rlim_cur = FD_SETSIZE;
  11298. else
  11299. fdlimit.rlim_cur = fdlimit.rlim_max;
  11300. if (fdlimit.rlim_max != RLIM_INFINITY)
  11301. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  11302. if (old_soft_limit != RLIM_INFINITY)
  11303. snprintf(frombuf, sizeof(frombuf), "%lu", (unsigned long)old_soft_limit);
  11304. if (fdlimit.rlim_cur == old_soft_limit)
  11305. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11306. (unsigned long)old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  11307. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  11308. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11309. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11310. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11311. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11312. #else
  11313. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  11314. #endif
  11315. }
  11316. static
  11317. void bfg_atexit(void)
  11318. {
  11319. puts("");
  11320. }
  11321. extern void bfg_init_threadlocal();
  11322. extern void stratumsrv_start();
  11323. extern void test_aan_pll(void);
  11324. int main(int argc, char *argv[])
  11325. {
  11326. struct sigaction handler;
  11327. struct thr_info *thr;
  11328. unsigned int k;
  11329. int i;
  11330. int rearrange_pools = 0;
  11331. char *s;
  11332. #ifdef WIN32
  11333. LoadLibrary("backtrace.dll");
  11334. #endif
  11335. atexit(bfg_atexit);
  11336. b58_sha256_impl = my_blkmaker_sha256_callback;
  11337. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  11338. bfg_init_threadlocal();
  11339. #ifndef HAVE_PTHREAD_CANCEL
  11340. setup_pthread_cancel_workaround();
  11341. #endif
  11342. bfg_init_checksums();
  11343. #ifdef WIN32
  11344. {
  11345. WSADATA wsa;
  11346. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  11347. if (i)
  11348. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  11349. }
  11350. #endif
  11351. /* This dangerous functions tramples random dynamically allocated
  11352. * variables so do it before anything at all */
  11353. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  11354. quit(1, "Failed to curl_global_init");
  11355. initial_args = malloc(sizeof(char *) * (argc + 1));
  11356. for (i = 0; i < argc; i++)
  11357. initial_args[i] = strdup(argv[i]);
  11358. initial_args[argc] = NULL;
  11359. mutex_init(&hash_lock);
  11360. mutex_init(&console_lock);
  11361. cglock_init(&control_lock);
  11362. mutex_init(&stats_lock);
  11363. mutex_init(&sharelog_lock);
  11364. cglock_init(&ch_lock);
  11365. mutex_init(&sshare_lock);
  11366. rwlock_init(&blk_lock);
  11367. rwlock_init(&netacc_lock);
  11368. rwlock_init(&mining_thr_lock);
  11369. rwlock_init(&devices_lock);
  11370. mutex_init(&lp_lock);
  11371. if (unlikely(pthread_cond_init(&lp_cond, bfg_condattr)))
  11372. quit(1, "Failed to pthread_cond_init lp_cond");
  11373. if (unlikely(pthread_cond_init(&gws_cond, bfg_condattr)))
  11374. quit(1, "Failed to pthread_cond_init gws_cond");
  11375. notifier_init(submit_waiting_notifier);
  11376. timer_unset(&tv_rescan);
  11377. notifier_init(rescan_notifier);
  11378. /* Create a unique get work queue */
  11379. getq = tq_new();
  11380. if (!getq)
  11381. quit(1, "Failed to create getq");
  11382. /* We use the getq mutex as the staged lock */
  11383. stgd_lock = &getq->mutex;
  11384. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  11385. #ifdef WANT_CPUMINE
  11386. init_max_name_len();
  11387. #endif
  11388. handler.sa_handler = &sighandler;
  11389. handler.sa_flags = 0;
  11390. sigemptyset(&handler.sa_mask);
  11391. #ifdef HAVE_PTHREAD_CANCEL
  11392. sigaction(SIGTERM, &handler, &termhandler);
  11393. #else
  11394. // Need to let pthread_cancel emulation handle SIGTERM first
  11395. termhandler = pcwm_orig_term_handler;
  11396. pcwm_orig_term_handler = handler;
  11397. #endif
  11398. sigaction(SIGINT, &handler, &inthandler);
  11399. #ifndef WIN32
  11400. signal(SIGPIPE, SIG_IGN);
  11401. #else
  11402. timeBeginPeriod(1);
  11403. #endif
  11404. opt_kernel_path = CGMINER_PREFIX;
  11405. cgminer_path = alloca(PATH_MAX);
  11406. s = strdup(argv[0]);
  11407. strcpy(cgminer_path, dirname(s));
  11408. free(s);
  11409. strcat(cgminer_path, "/");
  11410. #if defined(WANT_CPUMINE) && defined(WIN32)
  11411. {
  11412. char buf[32];
  11413. int gev = GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, sizeof(buf));
  11414. if (gev > 0 && gev < sizeof(buf))
  11415. {
  11416. setup_benchmark_pool();
  11417. double rate = bench_algo_stage3(atoi(buf));
  11418. // Write result to shared memory for parent
  11419. char unique_name[64];
  11420. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32))
  11421. {
  11422. HANDLE map_handle = CreateFileMapping(
  11423. INVALID_HANDLE_VALUE, // use paging file
  11424. NULL, // default security attributes
  11425. PAGE_READWRITE, // read/write access
  11426. 0, // size: high 32-bits
  11427. 4096, // size: low 32-bits
  11428. unique_name // name of map object
  11429. );
  11430. if (NULL != map_handle) {
  11431. void *shared_mem = MapViewOfFile(
  11432. map_handle, // object to map view of
  11433. FILE_MAP_WRITE, // read/write access
  11434. 0, // high offset: map from
  11435. 0, // low offset: beginning
  11436. 0 // default: map entire file
  11437. );
  11438. if (NULL != shared_mem)
  11439. CopyMemory(shared_mem, &rate, sizeof(rate));
  11440. (void)UnmapViewOfFile(shared_mem);
  11441. }
  11442. (void)CloseHandle(map_handle);
  11443. }
  11444. exit(0);
  11445. }
  11446. }
  11447. #endif
  11448. #ifdef HAVE_CURSES
  11449. devcursor = 8;
  11450. logstart = devcursor;
  11451. logcursor = logstart;
  11452. #endif
  11453. mutex_init(&submitting_lock);
  11454. #ifdef HAVE_OPENCL
  11455. opencl_early_init();
  11456. #endif
  11457. schedstart.tm.tm_sec = 1;
  11458. schedstop .tm.tm_sec = 1;
  11459. opt_register_table(opt_early_table, NULL);
  11460. opt_register_table(opt_config_table, NULL);
  11461. opt_register_table(opt_cmdline_table, NULL);
  11462. opt_early_parse(argc, argv, applog_and_exit);
  11463. if (!config_loaded)
  11464. {
  11465. load_default_config();
  11466. rearrange_pools = total_pools;
  11467. }
  11468. opt_free_table();
  11469. /* parse command line */
  11470. opt_register_table(opt_config_table,
  11471. "Options for both config file and command line");
  11472. opt_register_table(opt_cmdline_table,
  11473. "Options for command line only");
  11474. opt_parse(&argc, argv, applog_and_exit);
  11475. if (argc != 1)
  11476. quit(1, "Unexpected extra commandline arguments");
  11477. if (rearrange_pools && rearrange_pools < total_pools)
  11478. {
  11479. // Prioritise commandline pools before default-config pools
  11480. for (i = 0; i < rearrange_pools; ++i)
  11481. pools[i]->prio += rearrange_pools;
  11482. for ( ; i < total_pools; ++i)
  11483. pools[i]->prio -= rearrange_pools;
  11484. }
  11485. #ifndef HAVE_PTHREAD_CANCEL
  11486. // Can't do this any earlier, or config isn't loaded
  11487. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  11488. #endif
  11489. #ifdef HAVE_PWD_H
  11490. struct passwd *user_info = NULL;
  11491. if (opt_setuid != NULL) {
  11492. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  11493. quit(1, "Unable to find setuid user information");
  11494. }
  11495. }
  11496. #endif
  11497. #ifdef HAVE_CHROOT
  11498. if (chroot_dir != NULL) {
  11499. #ifdef HAVE_PWD_H
  11500. if (user_info == NULL && getuid() == 0) {
  11501. applog(LOG_WARNING, "Running as root inside chroot");
  11502. }
  11503. #endif
  11504. if (chroot(chroot_dir) != 0) {
  11505. quit(1, "Unable to chroot");
  11506. }
  11507. if (chdir("/"))
  11508. quit(1, "Unable to chdir to chroot");
  11509. }
  11510. #endif
  11511. #ifdef HAVE_PWD_H
  11512. if (user_info != NULL) {
  11513. if (setgid((*user_info).pw_gid) != 0)
  11514. quit(1, "Unable to setgid");
  11515. if (setuid((*user_info).pw_uid) != 0)
  11516. quit(1, "Unable to setuid");
  11517. }
  11518. #endif
  11519. raise_fd_limits();
  11520. if (opt_benchmark) {
  11521. while (total_pools)
  11522. remove_pool(pools[0]);
  11523. setup_benchmark_pool();
  11524. }
  11525. if (opt_unittest) {
  11526. test_cgpu_match();
  11527. test_intrange();
  11528. test_decimal_width();
  11529. test_domain_funcs();
  11530. #ifdef USE_SCRYPT
  11531. test_scrypt();
  11532. #endif
  11533. test_target();
  11534. test_uri_get_param();
  11535. utf8_test();
  11536. #ifdef USE_JINGTIAN
  11537. test_aan_pll();
  11538. #endif
  11539. if (unittest_failures)
  11540. quit(1, "Unit tests failed");
  11541. }
  11542. #ifdef HAVE_CURSES
  11543. if (opt_realquiet || opt_display_devs)
  11544. use_curses = false;
  11545. setlocale(LC_ALL, "C");
  11546. if (use_curses)
  11547. enable_curses();
  11548. #endif
  11549. #ifdef HAVE_LIBUSB
  11550. int err = libusb_init(NULL);
  11551. if (err)
  11552. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  11553. else
  11554. have_libusb = true;
  11555. #endif
  11556. applog(LOG_WARNING, "Started %s", packagename);
  11557. {
  11558. struct bfg_loaded_configfile *configfile;
  11559. LL_FOREACH(bfg_loaded_configfiles, configfile)
  11560. {
  11561. char * const cnfbuf = configfile->filename;
  11562. int fileconf_load = configfile->fileconf_load;
  11563. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  11564. switch (fileconf_load) {
  11565. case 0:
  11566. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  11567. applog(LOG_WARNING, "Configuration file could not be used.");
  11568. break;
  11569. case -1:
  11570. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  11571. if (use_curses)
  11572. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  11573. break;
  11574. default:
  11575. break;
  11576. }
  11577. }
  11578. }
  11579. i = strlen(opt_kernel_path) + 2;
  11580. char __kernel_path[i];
  11581. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  11582. opt_kernel_path = __kernel_path;
  11583. if (want_per_device_stats)
  11584. opt_log_output = true;
  11585. bfg_devapi_init();
  11586. drv_detect_all();
  11587. total_devices = total_devices_new;
  11588. devices = devices_new;
  11589. total_devices_new = 0;
  11590. devices_new = NULL;
  11591. if (opt_display_devs) {
  11592. int devcount = 0;
  11593. applog(LOG_ERR, "Devices detected:");
  11594. for (i = 0; i < total_devices; ++i) {
  11595. struct cgpu_info *cgpu = devices[i];
  11596. char buf[0x100];
  11597. if (cgpu->device != cgpu)
  11598. continue;
  11599. if (cgpu->name)
  11600. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  11601. else
  11602. if (cgpu->dev_manufacturer)
  11603. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  11604. else
  11605. if (cgpu->dev_product)
  11606. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  11607. else
  11608. strcpy(buf, " Device");
  11609. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  11610. if (cgpu->dev_serial)
  11611. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  11612. if (cgpu->device_path)
  11613. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  11614. tailsprintf(buf, sizeof(buf), ")");
  11615. _applog(LOG_NOTICE, buf);
  11616. ++devcount;
  11617. }
  11618. quit(0, "%d devices listed", devcount);
  11619. }
  11620. mining_threads = 0;
  11621. for (i = 0; i < total_devices; ++i)
  11622. register_device(devices[i]);
  11623. if (!total_devices) {
  11624. applog(LOG_WARNING, "No devices detected!");
  11625. if (use_curses)
  11626. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  11627. else
  11628. applog(LOG_WARNING, "Waiting for devices");
  11629. }
  11630. #ifdef HAVE_CURSES
  11631. switch_logsize();
  11632. #endif
  11633. #if BLKMAKER_VERSION > 1
  11634. if (opt_load_bitcoin_conf && !(opt_scrypt || opt_benchmark))
  11635. add_local_gbt(total_pools);
  11636. #endif
  11637. if (!total_pools) {
  11638. applog(LOG_WARNING, "Need to specify at least one pool server.");
  11639. #ifdef HAVE_CURSES
  11640. if (!use_curses || !input_pool(false))
  11641. #endif
  11642. quit(1, "Pool setup failed");
  11643. }
  11644. for (i = 0; i < total_pools; i++) {
  11645. struct pool *pool = pools[i];
  11646. size_t siz;
  11647. if (!pool->rpc_url)
  11648. quit(1, "No URI supplied for pool %u", i);
  11649. if (!pool->rpc_userpass) {
  11650. if (!pool->rpc_user || !pool->rpc_pass)
  11651. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  11652. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  11653. pool->rpc_userpass = malloc(siz);
  11654. if (!pool->rpc_userpass)
  11655. quit(1, "Failed to malloc userpass");
  11656. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  11657. }
  11658. }
  11659. /* Set the currentpool to pool with priority 0 */
  11660. validate_pool_priorities();
  11661. for (i = 0; i < total_pools; i++) {
  11662. struct pool *pool = pools[i];
  11663. if (!pool->prio)
  11664. currentpool = pool;
  11665. }
  11666. #ifdef HAVE_SYSLOG_H
  11667. if (use_syslog)
  11668. openlog(PACKAGE, LOG_PID, LOG_USER);
  11669. #endif
  11670. #if defined(unix) || defined(__APPLE__)
  11671. if (opt_stderr_cmd)
  11672. fork_monitor();
  11673. #endif // defined(unix)
  11674. mining_thr = calloc(mining_threads, sizeof(thr));
  11675. if (!mining_thr)
  11676. quit(1, "Failed to calloc mining_thr");
  11677. for (i = 0; i < mining_threads; i++) {
  11678. mining_thr[i] = calloc(1, sizeof(*thr));
  11679. if (!mining_thr[i])
  11680. quit(1, "Failed to calloc mining_thr[%d]", i);
  11681. }
  11682. total_control_threads = 6;
  11683. control_thr = calloc(total_control_threads, sizeof(*thr));
  11684. if (!control_thr)
  11685. quit(1, "Failed to calloc control_thr");
  11686. if (opt_benchmark)
  11687. goto begin_bench;
  11688. applog(LOG_NOTICE, "Probing for an alive pool");
  11689. do {
  11690. bool still_testing;
  11691. int i;
  11692. /* Look for at least one active pool before starting */
  11693. probe_pools();
  11694. do {
  11695. sleep(1);
  11696. if (pools_active)
  11697. break;
  11698. still_testing = false;
  11699. for (int i = 0; i < total_pools; ++i)
  11700. if (pools[i]->testing)
  11701. still_testing = true;
  11702. } while (still_testing);
  11703. if (!pools_active) {
  11704. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  11705. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  11706. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  11707. for (i = 0; i < total_pools; i++) {
  11708. struct pool *pool;
  11709. pool = pools[i];
  11710. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  11711. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  11712. }
  11713. #ifdef HAVE_CURSES
  11714. if (use_curses) {
  11715. halfdelay(150);
  11716. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  11717. if (getch() != ERR)
  11718. quit(0, "No servers could be used! Exiting.");
  11719. cbreak();
  11720. } else
  11721. #endif
  11722. quit(0, "No servers could be used! Exiting.");
  11723. }
  11724. } while (!pools_active);
  11725. #ifdef USE_SCRYPT
  11726. if (detect_algo == 1 && !opt_scrypt) {
  11727. applog(LOG_NOTICE, "Detected scrypt algorithm");
  11728. set_malgo_scrypt();
  11729. }
  11730. #endif
  11731. detect_algo = 0;
  11732. begin_bench:
  11733. total_mhashes_done = 0;
  11734. for (i = 0; i < total_devices; i++) {
  11735. struct cgpu_info *cgpu = devices[i];
  11736. cgpu->rolling = cgpu->total_mhashes = 0;
  11737. }
  11738. cgtime(&total_tv_start);
  11739. cgtime(&total_tv_end);
  11740. miner_started = total_tv_start;
  11741. time_t miner_start_ts = time(NULL);
  11742. if (schedstart.tm.tm_sec)
  11743. localtime_r(&miner_start_ts, &schedstart.tm);
  11744. if (schedstop.tm.tm_sec)
  11745. localtime_r(&miner_start_ts, &schedstop .tm);
  11746. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  11747. // Initialise processors and threads
  11748. k = 0;
  11749. for (i = 0; i < total_devices; ++i) {
  11750. struct cgpu_info *cgpu = devices[i];
  11751. allocate_cgpu(cgpu, &k);
  11752. }
  11753. // Start threads
  11754. for (i = 0; i < total_devices; ++i) {
  11755. struct cgpu_info *cgpu = devices[i];
  11756. start_cgpu(cgpu);
  11757. }
  11758. #ifdef HAVE_OPENCL
  11759. for (i = 0; i < nDevs; i++)
  11760. pause_dynamic_threads(i);
  11761. #endif
  11762. #ifdef WANT_CPUMINE
  11763. if (opt_n_threads > 0)
  11764. applog(LOG_INFO, "%d cpu miner threads started, using '%s' algorithm.",
  11765. opt_n_threads, algo_names[opt_algo]);
  11766. #endif
  11767. cgtime(&total_tv_start);
  11768. cgtime(&total_tv_end);
  11769. if (!opt_benchmark)
  11770. {
  11771. pthread_t submit_thread;
  11772. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  11773. quit(1, "submit_work thread create failed");
  11774. }
  11775. watchpool_thr_id = 1;
  11776. thr = &control_thr[watchpool_thr_id];
  11777. /* start watchpool thread */
  11778. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  11779. quit(1, "watchpool thread create failed");
  11780. pthread_detach(thr->pth);
  11781. watchdog_thr_id = 2;
  11782. thr = &control_thr[watchdog_thr_id];
  11783. /* start watchdog thread */
  11784. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  11785. quit(1, "watchdog thread create failed");
  11786. pthread_detach(thr->pth);
  11787. #ifdef HAVE_OPENCL
  11788. /* Create reinit gpu thread */
  11789. gpur_thr_id = 3;
  11790. thr = &control_thr[gpur_thr_id];
  11791. thr->q = tq_new();
  11792. if (!thr->q)
  11793. quit(1, "tq_new failed for gpur_thr_id");
  11794. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  11795. quit(1, "reinit_gpu thread create failed");
  11796. #endif
  11797. /* Create API socket thread */
  11798. api_thr_id = 4;
  11799. thr = &control_thr[api_thr_id];
  11800. if (thr_info_create(thr, NULL, api_thread, thr))
  11801. quit(1, "API thread create failed");
  11802. #ifdef USE_LIBMICROHTTPD
  11803. if (httpsrv_port != -1)
  11804. httpsrv_start(httpsrv_port);
  11805. #endif
  11806. #ifdef USE_LIBEVENT
  11807. if (stratumsrv_port != -1)
  11808. stratumsrv_start();
  11809. #endif
  11810. #ifdef HAVE_BFG_HOTPLUG
  11811. if (opt_hotplug)
  11812. hotplug_start();
  11813. #endif
  11814. #ifdef HAVE_CURSES
  11815. /* Create curses input thread for keyboard input. Create this last so
  11816. * that we know all threads are created since this can call kill_work
  11817. * to try and shut down ll previous threads. */
  11818. input_thr_id = 5;
  11819. thr = &control_thr[input_thr_id];
  11820. if (thr_info_create(thr, NULL, input_thread, thr))
  11821. quit(1, "input thread create failed");
  11822. pthread_detach(thr->pth);
  11823. #endif
  11824. /* Just to be sure */
  11825. if (total_control_threads != 6)
  11826. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  11827. /* Once everything is set up, main() becomes the getwork scheduler */
  11828. while (42) {
  11829. int ts, max_staged = opt_queue;
  11830. struct pool *pool, *cp;
  11831. bool lagging = false;
  11832. struct curl_ent *ce;
  11833. struct work *work;
  11834. struct mining_algorithm *malgo = NULL;
  11835. cp = current_pool();
  11836. // Generally, each processor needs a new work, and all at once during work restarts
  11837. max_staged += base_queue;
  11838. mutex_lock(stgd_lock);
  11839. ts = __total_staged();
  11840. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  11841. lagging = true;
  11842. /* Wait until hash_pop tells us we need to create more work */
  11843. if (ts > max_staged) {
  11844. {
  11845. LL_FOREACH(mining_algorithms, malgo)
  11846. {
  11847. if (!malgo->goal_refs)
  11848. continue;
  11849. if (malgo->staged < malgo->base_queue + opt_queue)
  11850. {
  11851. mutex_unlock(stgd_lock);
  11852. goto need_malgo_queued;
  11853. }
  11854. }
  11855. malgo = NULL;
  11856. }
  11857. staged_full = true;
  11858. pthread_cond_wait(&gws_cond, stgd_lock);
  11859. ts = __total_staged();
  11860. }
  11861. mutex_unlock(stgd_lock);
  11862. if (ts > max_staged)
  11863. continue;
  11864. need_malgo_queued: ;
  11865. work = make_work();
  11866. if (lagging && !pool_tset(cp, &cp->lagging)) {
  11867. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  11868. cp->getfail_occasions++;
  11869. total_go++;
  11870. }
  11871. pool = select_pool(lagging, malgo);
  11872. retry:
  11873. if (pool->has_stratum) {
  11874. while (!pool->stratum_active || !pool->stratum_notify) {
  11875. struct pool *altpool = select_pool(true, malgo);
  11876. if (altpool == pool && pool->has_stratum)
  11877. cgsleep_ms(5000);
  11878. pool = altpool;
  11879. goto retry;
  11880. }
  11881. gen_stratum_work(pool, work);
  11882. applog(LOG_DEBUG, "Generated stratum work");
  11883. stage_work(work);
  11884. continue;
  11885. }
  11886. if (pool->last_work_copy) {
  11887. mutex_lock(&pool->last_work_lock);
  11888. struct work *last_work = pool->last_work_copy;
  11889. if (!last_work)
  11890. {}
  11891. else
  11892. if (can_roll(last_work) && should_roll(last_work)) {
  11893. struct timeval tv_now;
  11894. cgtime(&tv_now);
  11895. free_work(work);
  11896. work = make_clone(pool->last_work_copy);
  11897. mutex_unlock(&pool->last_work_lock);
  11898. roll_work(work);
  11899. 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));
  11900. stage_work(work);
  11901. continue;
  11902. } else if (last_work->tr && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tr->tmpl) > (unsigned long)mining_threads) {
  11903. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  11904. } else {
  11905. free_work(last_work);
  11906. pool->last_work_copy = NULL;
  11907. }
  11908. mutex_unlock(&pool->last_work_lock);
  11909. }
  11910. if (clone_available()) {
  11911. applog(LOG_DEBUG, "Cloned getwork work");
  11912. free_work(work);
  11913. continue;
  11914. }
  11915. if (opt_benchmark) {
  11916. get_benchmark_work(work, opt_benchmark_intense);
  11917. applog(LOG_DEBUG, "Generated benchmark work");
  11918. stage_work(work);
  11919. continue;
  11920. }
  11921. work->pool = pool;
  11922. ce = pop_curl_entry3(pool, 2);
  11923. /* obtain new work from bitcoin via JSON-RPC */
  11924. if (!get_upstream_work(work, ce->curl)) {
  11925. struct pool *next_pool;
  11926. /* Make sure the pool just hasn't stopped serving
  11927. * requests but is up as we'll keep hammering it */
  11928. push_curl_entry(ce, pool);
  11929. ++pool->seq_getfails;
  11930. pool_died(pool);
  11931. next_pool = select_pool(!opt_fail_only, malgo);
  11932. if (pool == next_pool) {
  11933. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  11934. cgsleep_ms(5000);
  11935. } else {
  11936. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  11937. pool = next_pool;
  11938. }
  11939. goto retry;
  11940. }
  11941. if (ts >= max_staged)
  11942. pool_tclear(pool, &pool->lagging);
  11943. if (pool_tclear(pool, &pool->idle))
  11944. pool_resus(pool);
  11945. applog(LOG_DEBUG, "Generated getwork work");
  11946. stage_work(work);
  11947. push_curl_entry(ce, pool);
  11948. }
  11949. return 0;
  11950. }